PackageManagerService.java revision 99dd37b3c5262910150ef955d16a33d32da264dd
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.InstantAppInfo;
132import android.content.pm.EphemeralRequest;
133import android.content.pm.EphemeralResolveInfo;
134import android.content.pm.EphemeralResponse;
135import android.content.pm.FallbackCategoryProvider;
136import android.content.pm.FeatureInfo;
137import android.content.pm.IOnPermissionsChangeListener;
138import android.content.pm.IPackageDataObserver;
139import android.content.pm.IPackageDeleteObserver;
140import android.content.pm.IPackageDeleteObserver2;
141import android.content.pm.IPackageInstallObserver2;
142import android.content.pm.IPackageInstaller;
143import android.content.pm.IPackageManager;
144import android.content.pm.IPackageMoveObserver;
145import android.content.pm.IPackageStatsObserver;
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.StorageManagerInternal;
208import android.os.storage.StorageEventListener;
209import android.os.storage.StorageManager;
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.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.DisplayMetrics;
224import android.util.EventLog;
225import android.util.ExceptionUtils;
226import android.util.Log;
227import android.util.LogPrinter;
228import android.util.MathUtils;
229import android.util.PackageUtils;
230import android.util.Pair;
231import android.util.PrintStreamPrinter;
232import android.util.Slog;
233import android.util.SparseArray;
234import android.util.SparseBooleanArray;
235import android.util.SparseIntArray;
236import android.util.Xml;
237import android.util.jar.StrictJarFile;
238import android.view.Display;
239
240import com.android.internal.R;
241import com.android.internal.annotations.GuardedBy;
242import com.android.internal.app.IMediaContainerService;
243import com.android.internal.app.ResolverActivity;
244import com.android.internal.content.NativeLibraryHelper;
245import com.android.internal.content.PackageHelper;
246import com.android.internal.logging.MetricsLogger;
247import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
248import com.android.internal.os.IParcelFileDescriptorFactory;
249import com.android.internal.os.RoSystemProperties;
250import com.android.internal.os.SomeArgs;
251import com.android.internal.os.Zygote;
252import com.android.internal.telephony.CarrierAppUtils;
253import com.android.internal.util.ArrayUtils;
254import com.android.internal.util.FastPrintWriter;
255import com.android.internal.util.FastXmlSerializer;
256import com.android.internal.util.IndentingPrintWriter;
257import com.android.internal.util.Preconditions;
258import com.android.internal.util.XmlUtils;
259import com.android.server.AttributeCache;
260import com.android.server.BackgroundDexOptJobService;
261import com.android.server.DeviceIdleController;
262import com.android.server.EventLogTags;
263import com.android.server.FgThread;
264import com.android.server.IntentResolver;
265import com.android.server.LocalServices;
266import com.android.server.ServiceThread;
267import com.android.server.SystemConfig;
268import com.android.server.Watchdog;
269import com.android.server.net.NetworkPolicyManagerInternal;
270import com.android.server.pm.Installer.InstallerException;
271import com.android.server.pm.PermissionsState.PermissionState;
272import com.android.server.pm.Settings.DatabaseVersion;
273import com.android.server.pm.Settings.VersionInfo;
274import com.android.server.pm.dex.DexManager;
275import com.android.server.storage.DeviceStorageMonitorInternal;
276
277import dalvik.system.CloseGuard;
278import dalvik.system.DexFile;
279import dalvik.system.VMRuntime;
280
281import libcore.io.IoUtils;
282import libcore.util.EmptyArray;
283
284import org.xmlpull.v1.XmlPullParser;
285import org.xmlpull.v1.XmlPullParserException;
286import org.xmlpull.v1.XmlSerializer;
287
288import java.io.BufferedOutputStream;
289import java.io.BufferedReader;
290import java.io.ByteArrayInputStream;
291import java.io.ByteArrayOutputStream;
292import java.io.File;
293import java.io.FileDescriptor;
294import java.io.FileInputStream;
295import java.io.FileNotFoundException;
296import java.io.FileOutputStream;
297import java.io.FileReader;
298import java.io.FilenameFilter;
299import java.io.IOException;
300import java.io.PrintWriter;
301import java.nio.charset.StandardCharsets;
302import java.security.DigestInputStream;
303import java.security.MessageDigest;
304import java.security.NoSuchAlgorithmException;
305import java.security.PublicKey;
306import java.security.SecureRandom;
307import java.security.cert.Certificate;
308import java.security.cert.CertificateEncodingException;
309import java.security.cert.CertificateException;
310import java.text.SimpleDateFormat;
311import java.util.ArrayList;
312import java.util.Arrays;
313import java.util.Collection;
314import java.util.Collections;
315import java.util.Comparator;
316import java.util.Date;
317import java.util.HashSet;
318import java.util.HashMap;
319import java.util.Iterator;
320import java.util.List;
321import java.util.Map;
322import java.util.Objects;
323import java.util.Set;
324import java.util.concurrent.CountDownLatch;
325import java.util.concurrent.TimeUnit;
326import java.util.concurrent.atomic.AtomicBoolean;
327import java.util.concurrent.atomic.AtomicInteger;
328
329/**
330 * Keep track of all those APKs everywhere.
331 * <p>
332 * Internally there are two important locks:
333 * <ul>
334 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
335 * and other related state. It is a fine-grained lock that should only be held
336 * momentarily, as it's one of the most contended locks in the system.
337 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
338 * operations typically involve heavy lifting of application data on disk. Since
339 * {@code installd} is single-threaded, and it's operations can often be slow,
340 * this lock should never be acquired while already holding {@link #mPackages}.
341 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
342 * holding {@link #mInstallLock}.
343 * </ul>
344 * Many internal methods rely on the caller to hold the appropriate locks, and
345 * this contract is expressed through method name suffixes:
346 * <ul>
347 * <li>fooLI(): the caller must hold {@link #mInstallLock}
348 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
349 * being modified must be frozen
350 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
351 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
352 * </ul>
353 * <p>
354 * Because this class is very central to the platform's security; please run all
355 * CTS and unit tests whenever making modifications:
356 *
357 * <pre>
358 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
359 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
360 * </pre>
361 */
362public class PackageManagerService extends IPackageManager.Stub {
363    static final String TAG = "PackageManager";
364    static final boolean DEBUG_SETTINGS = false;
365    static final boolean DEBUG_PREFERRED = false;
366    static final boolean DEBUG_UPGRADE = false;
367    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
368    private static final boolean DEBUG_BACKUP = false;
369    private static final boolean DEBUG_INSTALL = false;
370    private static final boolean DEBUG_REMOVE = false;
371    private static final boolean DEBUG_BROADCASTS = false;
372    private static final boolean DEBUG_SHOW_INFO = false;
373    private static final boolean DEBUG_PACKAGE_INFO = false;
374    private static final boolean DEBUG_INTENT_MATCHING = false;
375    private static final boolean DEBUG_PACKAGE_SCANNING = false;
376    private static final boolean DEBUG_VERIFY = false;
377    private static final boolean DEBUG_FILTERS = false;
378
379    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
380    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
381    // user, but by default initialize to this.
382    public static final boolean DEBUG_DEXOPT = false;
383
384    private static final boolean DEBUG_ABI_SELECTION = false;
385    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
386    private static final boolean DEBUG_TRIAGED_MISSING = false;
387    private static final boolean DEBUG_APP_DATA = false;
388
389    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
390    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
391
392    private static final boolean DISABLE_EPHEMERAL_APPS = false;
393    private static final boolean HIDE_EPHEMERAL_APIS = false;
394
395    private static final boolean ENABLE_QUOTA =
396            SystemProperties.getBoolean("persist.fw.quota", false);
397
398    private static final int RADIO_UID = Process.PHONE_UID;
399    private static final int LOG_UID = Process.LOG_UID;
400    private static final int NFC_UID = Process.NFC_UID;
401    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
402    private static final int SHELL_UID = Process.SHELL_UID;
403
404    // Cap the size of permission trees that 3rd party apps can define
405    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
406
407    // Suffix used during package installation when copying/moving
408    // package apks to install directory.
409    private static final String INSTALL_PACKAGE_SUFFIX = "-";
410
411    static final int SCAN_NO_DEX = 1<<1;
412    static final int SCAN_FORCE_DEX = 1<<2;
413    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
414    static final int SCAN_NEW_INSTALL = 1<<4;
415    static final int SCAN_UPDATE_TIME = 1<<5;
416    static final int SCAN_BOOTING = 1<<6;
417    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
418    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
419    static final int SCAN_REPLACING = 1<<9;
420    static final int SCAN_REQUIRE_KNOWN = 1<<10;
421    static final int SCAN_MOVE = 1<<11;
422    static final int SCAN_INITIAL = 1<<12;
423    static final int SCAN_CHECK_ONLY = 1<<13;
424    static final int SCAN_DONT_KILL_APP = 1<<14;
425    static final int SCAN_IGNORE_FROZEN = 1<<15;
426    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
427    static final int SCAN_AS_INSTANT_APP = 1<<17;
428    static final int SCAN_AS_FULL_APP = 1<<18;
429    /** Should not be with the scan flags */
430    static final int FLAGS_REMOVE_CHATTY = 1<<31;
431
432    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
433
434    private static final int[] EMPTY_INT_ARRAY = new int[0];
435
436    /**
437     * Timeout (in milliseconds) after which the watchdog should declare that
438     * our handler thread is wedged.  The usual default for such things is one
439     * minute but we sometimes do very lengthy I/O operations on this thread,
440     * such as installing multi-gigabyte applications, so ours needs to be longer.
441     */
442    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
443
444    /**
445     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
446     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
447     * settings entry if available, otherwise we use the hardcoded default.  If it's been
448     * more than this long since the last fstrim, we force one during the boot sequence.
449     *
450     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
451     * one gets run at the next available charging+idle time.  This final mandatory
452     * no-fstrim check kicks in only of the other scheduling criteria is never met.
453     */
454    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
455
456    /**
457     * Whether verification is enabled by default.
458     */
459    private static final boolean DEFAULT_VERIFY_ENABLE = true;
460
461    /**
462     * The default maximum time to wait for the verification agent to return in
463     * milliseconds.
464     */
465    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
466
467    /**
468     * The default response for package verification timeout.
469     *
470     * This can be either PackageManager.VERIFICATION_ALLOW or
471     * PackageManager.VERIFICATION_REJECT.
472     */
473    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
474
475    static final String PLATFORM_PACKAGE_NAME = "android";
476
477    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
478
479    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
480            DEFAULT_CONTAINER_PACKAGE,
481            "com.android.defcontainer.DefaultContainerService");
482
483    private static final String KILL_APP_REASON_GIDS_CHANGED =
484            "permission grant or revoke changed gids";
485
486    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
487            "permissions revoked";
488
489    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
490
491    private static final String PACKAGE_SCHEME = "package";
492
493    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
494    /**
495     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
496     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
497     * VENDOR_OVERLAY_DIR.
498     */
499    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
500    /**
501     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
502     * is in VENDOR_OVERLAY_THEME_PROPERTY.
503     */
504    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
505            = "persist.vendor.overlay.theme";
506
507    /** Permission grant: not grant the permission. */
508    private static final int GRANT_DENIED = 1;
509
510    /** Permission grant: grant the permission as an install permission. */
511    private static final int GRANT_INSTALL = 2;
512
513    /** Permission grant: grant the permission as a runtime one. */
514    private static final int GRANT_RUNTIME = 3;
515
516    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
517    private static final int GRANT_UPGRADE = 4;
518
519    /** Canonical intent used to identify what counts as a "web browser" app */
520    private static final Intent sBrowserIntent;
521    static {
522        sBrowserIntent = new Intent();
523        sBrowserIntent.setAction(Intent.ACTION_VIEW);
524        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
525        sBrowserIntent.setData(Uri.parse("http:"));
526    }
527
528    /**
529     * The set of all protected actions [i.e. those actions for which a high priority
530     * intent filter is disallowed].
531     */
532    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
533    static {
534        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
535        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
536        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
537        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
538    }
539
540    // Compilation reasons.
541    public static final int REASON_FIRST_BOOT = 0;
542    public static final int REASON_BOOT = 1;
543    public static final int REASON_INSTALL = 2;
544    public static final int REASON_BACKGROUND_DEXOPT = 3;
545    public static final int REASON_AB_OTA = 4;
546    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
547    public static final int REASON_SHARED_APK = 6;
548    public static final int REASON_FORCED_DEXOPT = 7;
549    public static final int REASON_CORE_APP = 8;
550
551    public static final int REASON_LAST = REASON_CORE_APP;
552
553    /** All dangerous permission names in the same order as the events in MetricsEvent */
554    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
555            Manifest.permission.READ_CALENDAR,
556            Manifest.permission.WRITE_CALENDAR,
557            Manifest.permission.CAMERA,
558            Manifest.permission.READ_CONTACTS,
559            Manifest.permission.WRITE_CONTACTS,
560            Manifest.permission.GET_ACCOUNTS,
561            Manifest.permission.ACCESS_FINE_LOCATION,
562            Manifest.permission.ACCESS_COARSE_LOCATION,
563            Manifest.permission.RECORD_AUDIO,
564            Manifest.permission.READ_PHONE_STATE,
565            Manifest.permission.CALL_PHONE,
566            Manifest.permission.READ_CALL_LOG,
567            Manifest.permission.WRITE_CALL_LOG,
568            Manifest.permission.ADD_VOICEMAIL,
569            Manifest.permission.USE_SIP,
570            Manifest.permission.PROCESS_OUTGOING_CALLS,
571            Manifest.permission.READ_CELL_BROADCASTS,
572            Manifest.permission.BODY_SENSORS,
573            Manifest.permission.SEND_SMS,
574            Manifest.permission.RECEIVE_SMS,
575            Manifest.permission.READ_SMS,
576            Manifest.permission.RECEIVE_WAP_PUSH,
577            Manifest.permission.RECEIVE_MMS,
578            Manifest.permission.READ_EXTERNAL_STORAGE,
579            Manifest.permission.WRITE_EXTERNAL_STORAGE,
580            Manifest.permission.READ_PHONE_NUMBER);
581
582
583    /**
584     * Version number for the package parser cache. Increment this whenever the format or
585     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
586     */
587    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
588
589    /**
590     * Whether the package parser cache is enabled.
591     */
592    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
593
594    final ServiceThread mHandlerThread;
595
596    final PackageHandler mHandler;
597
598    private final ProcessLoggingHandler mProcessLoggingHandler;
599
600    /**
601     * Messages for {@link #mHandler} that need to wait for system ready before
602     * being dispatched.
603     */
604    private ArrayList<Message> mPostSystemReadyMessages;
605
606    final int mSdkVersion = Build.VERSION.SDK_INT;
607
608    final Context mContext;
609    final boolean mFactoryTest;
610    final boolean mOnlyCore;
611    final DisplayMetrics mMetrics;
612    final int mDefParseFlags;
613    final String[] mSeparateProcesses;
614    final boolean mIsUpgrade;
615    final boolean mIsPreNUpgrade;
616    final boolean mIsPreNMR1Upgrade;
617
618    @GuardedBy("mPackages")
619    private boolean mDexOptDialogShown;
620
621    /** The location for ASEC container files on internal storage. */
622    final String mAsecInternalPath;
623
624    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
625    // LOCK HELD.  Can be called with mInstallLock held.
626    @GuardedBy("mInstallLock")
627    final Installer mInstaller;
628
629    /** Directory where installed third-party apps stored */
630    final File mAppInstallDir;
631
632    /**
633     * Directory to which applications installed internally have their
634     * 32 bit native libraries copied.
635     */
636    private File mAppLib32InstallDir;
637
638    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
639    // apps.
640    final File mDrmAppPrivateInstallDir;
641
642    // ----------------------------------------------------------------
643
644    // Lock for state used when installing and doing other long running
645    // operations.  Methods that must be called with this lock held have
646    // the suffix "LI".
647    final Object mInstallLock = new Object();
648
649    // ----------------------------------------------------------------
650
651    // Keys are String (package name), values are Package.  This also serves
652    // as the lock for the global state.  Methods that must be called with
653    // this lock held have the prefix "LP".
654    @GuardedBy("mPackages")
655    final ArrayMap<String, PackageParser.Package> mPackages =
656            new ArrayMap<String, PackageParser.Package>();
657
658    final ArrayMap<String, Set<String>> mKnownCodebase =
659            new ArrayMap<String, Set<String>>();
660
661    // Tracks available target package names -> overlay package paths.
662    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
663        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
664
665    /**
666     * Tracks new system packages [received in an OTA] that we expect to
667     * find updated user-installed versions. Keys are package name, values
668     * are package location.
669     */
670    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
671    /**
672     * Tracks high priority intent filters for protected actions. During boot, certain
673     * filter actions are protected and should never be allowed to have a high priority
674     * intent filter for them. However, there is one, and only one exception -- the
675     * setup wizard. It must be able to define a high priority intent filter for these
676     * actions to ensure there are no escapes from the wizard. We need to delay processing
677     * of these during boot as we need to look at all of the system packages in order
678     * to know which component is the setup wizard.
679     */
680    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
681    /**
682     * Whether or not processing protected filters should be deferred.
683     */
684    private boolean mDeferProtectedFilters = true;
685
686    /**
687     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
688     */
689    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
690    /**
691     * Whether or not system app permissions should be promoted from install to runtime.
692     */
693    boolean mPromoteSystemApps;
694
695    @GuardedBy("mPackages")
696    final Settings mSettings;
697
698    /**
699     * Set of package names that are currently "frozen", which means active
700     * surgery is being done on the code/data for that package. The platform
701     * will refuse to launch frozen packages to avoid race conditions.
702     *
703     * @see PackageFreezer
704     */
705    @GuardedBy("mPackages")
706    final ArraySet<String> mFrozenPackages = new ArraySet<>();
707
708    final ProtectedPackages mProtectedPackages;
709
710    boolean mFirstBoot;
711
712    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
713
714    // System configuration read by SystemConfig.
715    final int[] mGlobalGids;
716    final SparseArray<ArraySet<String>> mSystemPermissions;
717    @GuardedBy("mAvailableFeatures")
718    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
719
720    // If mac_permissions.xml was found for seinfo labeling.
721    boolean mFoundPolicyFile;
722
723    private final InstantAppRegistry mInstantAppRegistry;
724
725    @GuardedBy("mPackages")
726    int mChangedPackagesSequenceNumber;
727    /**
728     * List of changed [installed, removed or updated] packages.
729     * mapping from user id -> sequence number -> package name
730     */
731    @GuardedBy("mPackages")
732    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
733    /**
734     * The sequence number of the last change to a package.
735     * mapping from user id -> package name -> sequence number
736     */
737    @GuardedBy("mPackages")
738    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
739
740    public static final class SharedLibraryEntry {
741        public final String path;
742        public final String apk;
743        public final SharedLibraryInfo info;
744
745        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
746                String declaringPackageName, int declaringPackageVersionCode) {
747            path = _path;
748            apk = _apk;
749            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
750                    declaringPackageName, declaringPackageVersionCode), null);
751        }
752    }
753
754    // Currently known shared libraries.
755    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
756    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
757            new ArrayMap<>();
758
759    // All available activities, for your resolving pleasure.
760    final ActivityIntentResolver mActivities =
761            new ActivityIntentResolver();
762
763    // All available receivers, for your resolving pleasure.
764    final ActivityIntentResolver mReceivers =
765            new ActivityIntentResolver();
766
767    // All available services, for your resolving pleasure.
768    final ServiceIntentResolver mServices = new ServiceIntentResolver();
769
770    // All available providers, for your resolving pleasure.
771    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
772
773    // Mapping from provider base names (first directory in content URI codePath)
774    // to the provider information.
775    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
776            new ArrayMap<String, PackageParser.Provider>();
777
778    // Mapping from instrumentation class names to info about them.
779    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
780            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
781
782    // Mapping from permission names to info about them.
783    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
784            new ArrayMap<String, PackageParser.PermissionGroup>();
785
786    // Packages whose data we have transfered into another package, thus
787    // should no longer exist.
788    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
789
790    // Broadcast actions that are only available to the system.
791    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
792
793    /** List of packages waiting for verification. */
794    final SparseArray<PackageVerificationState> mPendingVerification
795            = new SparseArray<PackageVerificationState>();
796
797    /** Set of packages associated with each app op permission. */
798    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
799
800    final PackageInstallerService mInstallerService;
801
802    private final PackageDexOptimizer mPackageDexOptimizer;
803    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
804    // is used by other apps).
805    private final DexManager mDexManager;
806
807    private AtomicInteger mNextMoveId = new AtomicInteger();
808    private final MoveCallbacks mMoveCallbacks;
809
810    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
811
812    // Cache of users who need badging.
813    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
814
815    /** Token for keys in mPendingVerification. */
816    private int mPendingVerificationToken = 0;
817
818    volatile boolean mSystemReady;
819    volatile boolean mSafeMode;
820    volatile boolean mHasSystemUidErrors;
821
822    ApplicationInfo mAndroidApplication;
823    final ActivityInfo mResolveActivity = new ActivityInfo();
824    final ResolveInfo mResolveInfo = new ResolveInfo();
825    ComponentName mResolveComponentName;
826    PackageParser.Package mPlatformPackage;
827    ComponentName mCustomResolverComponentName;
828
829    boolean mResolverReplaced = false;
830
831    private final @Nullable ComponentName mIntentFilterVerifierComponent;
832    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
833
834    private int mIntentFilterVerificationToken = 0;
835
836    /** The service connection to the ephemeral resolver */
837    final EphemeralResolverConnection mEphemeralResolverConnection;
838
839    /** Component used to install ephemeral applications */
840    ComponentName mEphemeralInstallerComponent;
841    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
842    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
843
844    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
845            = new SparseArray<IntentFilterVerificationState>();
846
847    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
848
849    // List of packages names to keep cached, even if they are uninstalled for all users
850    private List<String> mKeepUninstalledPackages;
851
852    private UserManagerInternal mUserManagerInternal;
853
854    private DeviceIdleController.LocalService mDeviceIdleController;
855
856    private File mCacheDir;
857
858    private ArraySet<String> mPrivappPermissionsViolations;
859
860    private static class IFVerificationParams {
861        PackageParser.Package pkg;
862        boolean replacing;
863        int userId;
864        int verifierUid;
865
866        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
867                int _userId, int _verifierUid) {
868            pkg = _pkg;
869            replacing = _replacing;
870            userId = _userId;
871            replacing = _replacing;
872            verifierUid = _verifierUid;
873        }
874    }
875
876    private interface IntentFilterVerifier<T extends IntentFilter> {
877        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
878                                               T filter, String packageName);
879        void startVerifications(int userId);
880        void receiveVerificationResponse(int verificationId);
881    }
882
883    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
884        private Context mContext;
885        private ComponentName mIntentFilterVerifierComponent;
886        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
887
888        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
889            mContext = context;
890            mIntentFilterVerifierComponent = verifierComponent;
891        }
892
893        private String getDefaultScheme() {
894            return IntentFilter.SCHEME_HTTPS;
895        }
896
897        @Override
898        public void startVerifications(int userId) {
899            // Launch verifications requests
900            int count = mCurrentIntentFilterVerifications.size();
901            for (int n=0; n<count; n++) {
902                int verificationId = mCurrentIntentFilterVerifications.get(n);
903                final IntentFilterVerificationState ivs =
904                        mIntentFilterVerificationStates.get(verificationId);
905
906                String packageName = ivs.getPackageName();
907
908                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
909                final int filterCount = filters.size();
910                ArraySet<String> domainsSet = new ArraySet<>();
911                for (int m=0; m<filterCount; m++) {
912                    PackageParser.ActivityIntentInfo filter = filters.get(m);
913                    domainsSet.addAll(filter.getHostsList());
914                }
915                synchronized (mPackages) {
916                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
917                            packageName, domainsSet) != null) {
918                        scheduleWriteSettingsLocked();
919                    }
920                }
921                sendVerificationRequest(userId, verificationId, ivs);
922            }
923            mCurrentIntentFilterVerifications.clear();
924        }
925
926        private void sendVerificationRequest(int userId, int verificationId,
927                IntentFilterVerificationState ivs) {
928
929            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
930            verificationIntent.putExtra(
931                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
932                    verificationId);
933            verificationIntent.putExtra(
934                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
935                    getDefaultScheme());
936            verificationIntent.putExtra(
937                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
938                    ivs.getHostsString());
939            verificationIntent.putExtra(
940                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
941                    ivs.getPackageName());
942            verificationIntent.setComponent(mIntentFilterVerifierComponent);
943            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
944
945            UserHandle user = new UserHandle(userId);
946            mContext.sendBroadcastAsUser(verificationIntent, user);
947            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
948                    "Sending IntentFilter verification broadcast");
949        }
950
951        public void receiveVerificationResponse(int verificationId) {
952            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
953
954            final boolean verified = ivs.isVerified();
955
956            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
957            final int count = filters.size();
958            if (DEBUG_DOMAIN_VERIFICATION) {
959                Slog.i(TAG, "Received verification response " + verificationId
960                        + " for " + count + " filters, verified=" + verified);
961            }
962            for (int n=0; n<count; n++) {
963                PackageParser.ActivityIntentInfo filter = filters.get(n);
964                filter.setVerified(verified);
965
966                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
967                        + " verified with result:" + verified + " and hosts:"
968                        + ivs.getHostsString());
969            }
970
971            mIntentFilterVerificationStates.remove(verificationId);
972
973            final String packageName = ivs.getPackageName();
974            IntentFilterVerificationInfo ivi = null;
975
976            synchronized (mPackages) {
977                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
978            }
979            if (ivi == null) {
980                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
981                        + verificationId + " packageName:" + packageName);
982                return;
983            }
984            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
985                    "Updating IntentFilterVerificationInfo for package " + packageName
986                            +" verificationId:" + verificationId);
987
988            synchronized (mPackages) {
989                if (verified) {
990                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
991                } else {
992                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
993                }
994                scheduleWriteSettingsLocked();
995
996                final int userId = ivs.getUserId();
997                if (userId != UserHandle.USER_ALL) {
998                    final int userStatus =
999                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1000
1001                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1002                    boolean needUpdate = false;
1003
1004                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1005                    // already been set by the User thru the Disambiguation dialog
1006                    switch (userStatus) {
1007                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1008                            if (verified) {
1009                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1010                            } else {
1011                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1012                            }
1013                            needUpdate = true;
1014                            break;
1015
1016                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1017                            if (verified) {
1018                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1019                                needUpdate = true;
1020                            }
1021                            break;
1022
1023                        default:
1024                            // Nothing to do
1025                    }
1026
1027                    if (needUpdate) {
1028                        mSettings.updateIntentFilterVerificationStatusLPw(
1029                                packageName, updatedStatus, userId);
1030                        scheduleWritePackageRestrictionsLocked(userId);
1031                    }
1032                }
1033            }
1034        }
1035
1036        @Override
1037        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1038                    ActivityIntentInfo filter, String packageName) {
1039            if (!hasValidDomains(filter)) {
1040                return false;
1041            }
1042            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1043            if (ivs == null) {
1044                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1045                        packageName);
1046            }
1047            if (DEBUG_DOMAIN_VERIFICATION) {
1048                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1049            }
1050            ivs.addFilter(filter);
1051            return true;
1052        }
1053
1054        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1055                int userId, int verificationId, String packageName) {
1056            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1057                    verifierUid, userId, packageName);
1058            ivs.setPendingState();
1059            synchronized (mPackages) {
1060                mIntentFilterVerificationStates.append(verificationId, ivs);
1061                mCurrentIntentFilterVerifications.add(verificationId);
1062            }
1063            return ivs;
1064        }
1065    }
1066
1067    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1068        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1069                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1070                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1071    }
1072
1073    // Set of pending broadcasts for aggregating enable/disable of components.
1074    static class PendingPackageBroadcasts {
1075        // for each user id, a map of <package name -> components within that package>
1076        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1077
1078        public PendingPackageBroadcasts() {
1079            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1080        }
1081
1082        public ArrayList<String> get(int userId, String packageName) {
1083            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1084            return packages.get(packageName);
1085        }
1086
1087        public void put(int userId, String packageName, ArrayList<String> components) {
1088            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1089            packages.put(packageName, components);
1090        }
1091
1092        public void remove(int userId, String packageName) {
1093            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1094            if (packages != null) {
1095                packages.remove(packageName);
1096            }
1097        }
1098
1099        public void remove(int userId) {
1100            mUidMap.remove(userId);
1101        }
1102
1103        public int userIdCount() {
1104            return mUidMap.size();
1105        }
1106
1107        public int userIdAt(int n) {
1108            return mUidMap.keyAt(n);
1109        }
1110
1111        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1112            return mUidMap.get(userId);
1113        }
1114
1115        public int size() {
1116            // total number of pending broadcast entries across all userIds
1117            int num = 0;
1118            for (int i = 0; i< mUidMap.size(); i++) {
1119                num += mUidMap.valueAt(i).size();
1120            }
1121            return num;
1122        }
1123
1124        public void clear() {
1125            mUidMap.clear();
1126        }
1127
1128        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1129            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1130            if (map == null) {
1131                map = new ArrayMap<String, ArrayList<String>>();
1132                mUidMap.put(userId, map);
1133            }
1134            return map;
1135        }
1136    }
1137    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1138
1139    // Service Connection to remote media container service to copy
1140    // package uri's from external media onto secure containers
1141    // or internal storage.
1142    private IMediaContainerService mContainerService = null;
1143
1144    static final int SEND_PENDING_BROADCAST = 1;
1145    static final int MCS_BOUND = 3;
1146    static final int END_COPY = 4;
1147    static final int INIT_COPY = 5;
1148    static final int MCS_UNBIND = 6;
1149    static final int START_CLEANING_PACKAGE = 7;
1150    static final int FIND_INSTALL_LOC = 8;
1151    static final int POST_INSTALL = 9;
1152    static final int MCS_RECONNECT = 10;
1153    static final int MCS_GIVE_UP = 11;
1154    static final int UPDATED_MEDIA_STATUS = 12;
1155    static final int WRITE_SETTINGS = 13;
1156    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1157    static final int PACKAGE_VERIFIED = 15;
1158    static final int CHECK_PENDING_VERIFICATION = 16;
1159    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1160    static final int INTENT_FILTER_VERIFIED = 18;
1161    static final int WRITE_PACKAGE_LIST = 19;
1162    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1163
1164    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1165
1166    // Delay time in millisecs
1167    static final int BROADCAST_DELAY = 10 * 1000;
1168
1169    static UserManagerService sUserManager;
1170
1171    // Stores a list of users whose package restrictions file needs to be updated
1172    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1173
1174    final private DefaultContainerConnection mDefContainerConn =
1175            new DefaultContainerConnection();
1176    class DefaultContainerConnection implements ServiceConnection {
1177        public void onServiceConnected(ComponentName name, IBinder service) {
1178            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1179            final IMediaContainerService imcs = IMediaContainerService.Stub
1180                    .asInterface(Binder.allowBlocking(service));
1181            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1182        }
1183
1184        public void onServiceDisconnected(ComponentName name) {
1185            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1186        }
1187    }
1188
1189    // Recordkeeping of restore-after-install operations that are currently in flight
1190    // between the Package Manager and the Backup Manager
1191    static class PostInstallData {
1192        public InstallArgs args;
1193        public PackageInstalledInfo res;
1194
1195        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1196            args = _a;
1197            res = _r;
1198        }
1199    }
1200
1201    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1202    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1203
1204    // XML tags for backup/restore of various bits of state
1205    private static final String TAG_PREFERRED_BACKUP = "pa";
1206    private static final String TAG_DEFAULT_APPS = "da";
1207    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1208
1209    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1210    private static final String TAG_ALL_GRANTS = "rt-grants";
1211    private static final String TAG_GRANT = "grant";
1212    private static final String ATTR_PACKAGE_NAME = "pkg";
1213
1214    private static final String TAG_PERMISSION = "perm";
1215    private static final String ATTR_PERMISSION_NAME = "name";
1216    private static final String ATTR_IS_GRANTED = "g";
1217    private static final String ATTR_USER_SET = "set";
1218    private static final String ATTR_USER_FIXED = "fixed";
1219    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1220
1221    // System/policy permission grants are not backed up
1222    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1223            FLAG_PERMISSION_POLICY_FIXED
1224            | FLAG_PERMISSION_SYSTEM_FIXED
1225            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1226
1227    // And we back up these user-adjusted states
1228    private static final int USER_RUNTIME_GRANT_MASK =
1229            FLAG_PERMISSION_USER_SET
1230            | FLAG_PERMISSION_USER_FIXED
1231            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1232
1233    final @Nullable String mRequiredVerifierPackage;
1234    final @NonNull String mRequiredInstallerPackage;
1235    final @NonNull String mRequiredUninstallerPackage;
1236    final @Nullable String mSetupWizardPackage;
1237    final @Nullable String mStorageManagerPackage;
1238    final @NonNull String mServicesSystemSharedLibraryPackageName;
1239    final @NonNull String mSharedSystemSharedLibraryPackageName;
1240
1241    final boolean mPermissionReviewRequired;
1242
1243    private final PackageUsage mPackageUsage = new PackageUsage();
1244    private final CompilerStats mCompilerStats = new CompilerStats();
1245
1246    class PackageHandler extends Handler {
1247        private boolean mBound = false;
1248        final ArrayList<HandlerParams> mPendingInstalls =
1249            new ArrayList<HandlerParams>();
1250
1251        private boolean connectToService() {
1252            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1253                    " DefaultContainerService");
1254            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1255            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1256            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1257                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1258                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1259                mBound = true;
1260                return true;
1261            }
1262            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1263            return false;
1264        }
1265
1266        private void disconnectService() {
1267            mContainerService = null;
1268            mBound = false;
1269            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1270            mContext.unbindService(mDefContainerConn);
1271            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1272        }
1273
1274        PackageHandler(Looper looper) {
1275            super(looper);
1276        }
1277
1278        public void handleMessage(Message msg) {
1279            try {
1280                doHandleMessage(msg);
1281            } finally {
1282                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1283            }
1284        }
1285
1286        void doHandleMessage(Message msg) {
1287            switch (msg.what) {
1288                case INIT_COPY: {
1289                    HandlerParams params = (HandlerParams) msg.obj;
1290                    int idx = mPendingInstalls.size();
1291                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1292                    // If a bind was already initiated we dont really
1293                    // need to do anything. The pending install
1294                    // will be processed later on.
1295                    if (!mBound) {
1296                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1297                                System.identityHashCode(mHandler));
1298                        // If this is the only one pending we might
1299                        // have to bind to the service again.
1300                        if (!connectToService()) {
1301                            Slog.e(TAG, "Failed to bind to media container service");
1302                            params.serviceError();
1303                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1304                                    System.identityHashCode(mHandler));
1305                            if (params.traceMethod != null) {
1306                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1307                                        params.traceCookie);
1308                            }
1309                            return;
1310                        } else {
1311                            // Once we bind to the service, the first
1312                            // pending request will be processed.
1313                            mPendingInstalls.add(idx, params);
1314                        }
1315                    } else {
1316                        mPendingInstalls.add(idx, params);
1317                        // Already bound to the service. Just make
1318                        // sure we trigger off processing the first request.
1319                        if (idx == 0) {
1320                            mHandler.sendEmptyMessage(MCS_BOUND);
1321                        }
1322                    }
1323                    break;
1324                }
1325                case MCS_BOUND: {
1326                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1327                    if (msg.obj != null) {
1328                        mContainerService = (IMediaContainerService) msg.obj;
1329                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1330                                System.identityHashCode(mHandler));
1331                    }
1332                    if (mContainerService == null) {
1333                        if (!mBound) {
1334                            // Something seriously wrong since we are not bound and we are not
1335                            // waiting for connection. Bail out.
1336                            Slog.e(TAG, "Cannot bind to media container service");
1337                            for (HandlerParams params : mPendingInstalls) {
1338                                // Indicate service bind error
1339                                params.serviceError();
1340                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1341                                        System.identityHashCode(params));
1342                                if (params.traceMethod != null) {
1343                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1344                                            params.traceMethod, params.traceCookie);
1345                                }
1346                                return;
1347                            }
1348                            mPendingInstalls.clear();
1349                        } else {
1350                            Slog.w(TAG, "Waiting to connect to media container service");
1351                        }
1352                    } else if (mPendingInstalls.size() > 0) {
1353                        HandlerParams params = mPendingInstalls.get(0);
1354                        if (params != null) {
1355                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1356                                    System.identityHashCode(params));
1357                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1358                            if (params.startCopy()) {
1359                                // We are done...  look for more work or to
1360                                // go idle.
1361                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1362                                        "Checking for more work or unbind...");
1363                                // Delete pending install
1364                                if (mPendingInstalls.size() > 0) {
1365                                    mPendingInstalls.remove(0);
1366                                }
1367                                if (mPendingInstalls.size() == 0) {
1368                                    if (mBound) {
1369                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1370                                                "Posting delayed MCS_UNBIND");
1371                                        removeMessages(MCS_UNBIND);
1372                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1373                                        // Unbind after a little delay, to avoid
1374                                        // continual thrashing.
1375                                        sendMessageDelayed(ubmsg, 10000);
1376                                    }
1377                                } else {
1378                                    // There are more pending requests in queue.
1379                                    // Just post MCS_BOUND message to trigger processing
1380                                    // of next pending install.
1381                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1382                                            "Posting MCS_BOUND for next work");
1383                                    mHandler.sendEmptyMessage(MCS_BOUND);
1384                                }
1385                            }
1386                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1387                        }
1388                    } else {
1389                        // Should never happen ideally.
1390                        Slog.w(TAG, "Empty queue");
1391                    }
1392                    break;
1393                }
1394                case MCS_RECONNECT: {
1395                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1396                    if (mPendingInstalls.size() > 0) {
1397                        if (mBound) {
1398                            disconnectService();
1399                        }
1400                        if (!connectToService()) {
1401                            Slog.e(TAG, "Failed to bind to media container service");
1402                            for (HandlerParams params : mPendingInstalls) {
1403                                // Indicate service bind error
1404                                params.serviceError();
1405                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1406                                        System.identityHashCode(params));
1407                            }
1408                            mPendingInstalls.clear();
1409                        }
1410                    }
1411                    break;
1412                }
1413                case MCS_UNBIND: {
1414                    // If there is no actual work left, then time to unbind.
1415                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1416
1417                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1418                        if (mBound) {
1419                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1420
1421                            disconnectService();
1422                        }
1423                    } else if (mPendingInstalls.size() > 0) {
1424                        // There are more pending requests in queue.
1425                        // Just post MCS_BOUND message to trigger processing
1426                        // of next pending install.
1427                        mHandler.sendEmptyMessage(MCS_BOUND);
1428                    }
1429
1430                    break;
1431                }
1432                case MCS_GIVE_UP: {
1433                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1434                    HandlerParams params = mPendingInstalls.remove(0);
1435                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1436                            System.identityHashCode(params));
1437                    break;
1438                }
1439                case SEND_PENDING_BROADCAST: {
1440                    String packages[];
1441                    ArrayList<String> components[];
1442                    int size = 0;
1443                    int uids[];
1444                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1445                    synchronized (mPackages) {
1446                        if (mPendingBroadcasts == null) {
1447                            return;
1448                        }
1449                        size = mPendingBroadcasts.size();
1450                        if (size <= 0) {
1451                            // Nothing to be done. Just return
1452                            return;
1453                        }
1454                        packages = new String[size];
1455                        components = new ArrayList[size];
1456                        uids = new int[size];
1457                        int i = 0;  // filling out the above arrays
1458
1459                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1460                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1461                            Iterator<Map.Entry<String, ArrayList<String>>> it
1462                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1463                                            .entrySet().iterator();
1464                            while (it.hasNext() && i < size) {
1465                                Map.Entry<String, ArrayList<String>> ent = it.next();
1466                                packages[i] = ent.getKey();
1467                                components[i] = ent.getValue();
1468                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1469                                uids[i] = (ps != null)
1470                                        ? UserHandle.getUid(packageUserId, ps.appId)
1471                                        : -1;
1472                                i++;
1473                            }
1474                        }
1475                        size = i;
1476                        mPendingBroadcasts.clear();
1477                    }
1478                    // Send broadcasts
1479                    for (int i = 0; i < size; i++) {
1480                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1481                    }
1482                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1483                    break;
1484                }
1485                case START_CLEANING_PACKAGE: {
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                    final String packageName = (String)msg.obj;
1488                    final int userId = msg.arg1;
1489                    final boolean andCode = msg.arg2 != 0;
1490                    synchronized (mPackages) {
1491                        if (userId == UserHandle.USER_ALL) {
1492                            int[] users = sUserManager.getUserIds();
1493                            for (int user : users) {
1494                                mSettings.addPackageToCleanLPw(
1495                                        new PackageCleanItem(user, packageName, andCode));
1496                            }
1497                        } else {
1498                            mSettings.addPackageToCleanLPw(
1499                                    new PackageCleanItem(userId, packageName, andCode));
1500                        }
1501                    }
1502                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1503                    startCleaningPackages();
1504                } break;
1505                case POST_INSTALL: {
1506                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1507
1508                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1509                    final boolean didRestore = (msg.arg2 != 0);
1510                    mRunningInstalls.delete(msg.arg1);
1511
1512                    if (data != null) {
1513                        InstallArgs args = data.args;
1514                        PackageInstalledInfo parentRes = data.res;
1515
1516                        final boolean grantPermissions = (args.installFlags
1517                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1518                        final boolean killApp = (args.installFlags
1519                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1520                        final String[] grantedPermissions = args.installGrantPermissions;
1521
1522                        // Handle the parent package
1523                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1524                                grantedPermissions, didRestore, args.installerPackageName,
1525                                args.observer);
1526
1527                        // Handle the child packages
1528                        final int childCount = (parentRes.addedChildPackages != null)
1529                                ? parentRes.addedChildPackages.size() : 0;
1530                        for (int i = 0; i < childCount; i++) {
1531                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1532                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1533                                    grantedPermissions, false, args.installerPackageName,
1534                                    args.observer);
1535                        }
1536
1537                        // Log tracing if needed
1538                        if (args.traceMethod != null) {
1539                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1540                                    args.traceCookie);
1541                        }
1542                    } else {
1543                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1544                    }
1545
1546                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1547                } break;
1548                case UPDATED_MEDIA_STATUS: {
1549                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1550                    boolean reportStatus = msg.arg1 == 1;
1551                    boolean doGc = msg.arg2 == 1;
1552                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1553                    if (doGc) {
1554                        // Force a gc to clear up stale containers.
1555                        Runtime.getRuntime().gc();
1556                    }
1557                    if (msg.obj != null) {
1558                        @SuppressWarnings("unchecked")
1559                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1560                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1561                        // Unload containers
1562                        unloadAllContainers(args);
1563                    }
1564                    if (reportStatus) {
1565                        try {
1566                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1567                                    "Invoking StorageManagerService call back");
1568                            PackageHelper.getStorageManager().finishMediaUpdate();
1569                        } catch (RemoteException e) {
1570                            Log.e(TAG, "StorageManagerService not running?");
1571                        }
1572                    }
1573                } break;
1574                case WRITE_SETTINGS: {
1575                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1576                    synchronized (mPackages) {
1577                        removeMessages(WRITE_SETTINGS);
1578                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1579                        mSettings.writeLPr();
1580                        mDirtyUsers.clear();
1581                    }
1582                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1583                } break;
1584                case WRITE_PACKAGE_RESTRICTIONS: {
1585                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1586                    synchronized (mPackages) {
1587                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1588                        for (int userId : mDirtyUsers) {
1589                            mSettings.writePackageRestrictionsLPr(userId);
1590                        }
1591                        mDirtyUsers.clear();
1592                    }
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1594                } break;
1595                case WRITE_PACKAGE_LIST: {
1596                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1597                    synchronized (mPackages) {
1598                        removeMessages(WRITE_PACKAGE_LIST);
1599                        mSettings.writePackageListLPr(msg.arg1);
1600                    }
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1602                } break;
1603                case CHECK_PENDING_VERIFICATION: {
1604                    final int verificationId = msg.arg1;
1605                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1606
1607                    if ((state != null) && !state.timeoutExtended()) {
1608                        final InstallArgs args = state.getInstallArgs();
1609                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1610
1611                        Slog.i(TAG, "Verification timed out for " + originUri);
1612                        mPendingVerification.remove(verificationId);
1613
1614                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1615
1616                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1617                            Slog.i(TAG, "Continuing with installation of " + originUri);
1618                            state.setVerifierResponse(Binder.getCallingUid(),
1619                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1620                            broadcastPackageVerified(verificationId, originUri,
1621                                    PackageManager.VERIFICATION_ALLOW,
1622                                    state.getInstallArgs().getUser());
1623                            try {
1624                                ret = args.copyApk(mContainerService, true);
1625                            } catch (RemoteException e) {
1626                                Slog.e(TAG, "Could not contact the ContainerService");
1627                            }
1628                        } else {
1629                            broadcastPackageVerified(verificationId, originUri,
1630                                    PackageManager.VERIFICATION_REJECT,
1631                                    state.getInstallArgs().getUser());
1632                        }
1633
1634                        Trace.asyncTraceEnd(
1635                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1636
1637                        processPendingInstall(args, ret);
1638                        mHandler.sendEmptyMessage(MCS_UNBIND);
1639                    }
1640                    break;
1641                }
1642                case PACKAGE_VERIFIED: {
1643                    final int verificationId = msg.arg1;
1644
1645                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1646                    if (state == null) {
1647                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1648                        break;
1649                    }
1650
1651                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1652
1653                    state.setVerifierResponse(response.callerUid, response.code);
1654
1655                    if (state.isVerificationComplete()) {
1656                        mPendingVerification.remove(verificationId);
1657
1658                        final InstallArgs args = state.getInstallArgs();
1659                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1660
1661                        int ret;
1662                        if (state.isInstallAllowed()) {
1663                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1664                            broadcastPackageVerified(verificationId, originUri,
1665                                    response.code, state.getInstallArgs().getUser());
1666                            try {
1667                                ret = args.copyApk(mContainerService, true);
1668                            } catch (RemoteException e) {
1669                                Slog.e(TAG, "Could not contact the ContainerService");
1670                            }
1671                        } else {
1672                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1673                        }
1674
1675                        Trace.asyncTraceEnd(
1676                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1677
1678                        processPendingInstall(args, ret);
1679                        mHandler.sendEmptyMessage(MCS_UNBIND);
1680                    }
1681
1682                    break;
1683                }
1684                case START_INTENT_FILTER_VERIFICATIONS: {
1685                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1686                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1687                            params.replacing, params.pkg);
1688                    break;
1689                }
1690                case INTENT_FILTER_VERIFIED: {
1691                    final int verificationId = msg.arg1;
1692
1693                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1694                            verificationId);
1695                    if (state == null) {
1696                        Slog.w(TAG, "Invalid IntentFilter verification token "
1697                                + verificationId + " received");
1698                        break;
1699                    }
1700
1701                    final int userId = state.getUserId();
1702
1703                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1704                            "Processing IntentFilter verification with token:"
1705                            + verificationId + " and userId:" + userId);
1706
1707                    final IntentFilterVerificationResponse response =
1708                            (IntentFilterVerificationResponse) msg.obj;
1709
1710                    state.setVerifierResponse(response.callerUid, response.code);
1711
1712                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1713                            "IntentFilter verification with token:" + verificationId
1714                            + " and userId:" + userId
1715                            + " is settings verifier response with response code:"
1716                            + response.code);
1717
1718                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1719                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1720                                + response.getFailedDomainsString());
1721                    }
1722
1723                    if (state.isVerificationComplete()) {
1724                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1725                    } else {
1726                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1727                                "IntentFilter verification with token:" + verificationId
1728                                + " was not said to be complete");
1729                    }
1730
1731                    break;
1732                }
1733                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1734                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1735                            mEphemeralResolverConnection,
1736                            (EphemeralRequest) msg.obj,
1737                            mEphemeralInstallerActivity,
1738                            mHandler);
1739                }
1740            }
1741        }
1742    }
1743
1744    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1745            boolean killApp, String[] grantedPermissions,
1746            boolean launchedForRestore, String installerPackage,
1747            IPackageInstallObserver2 installObserver) {
1748        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1749            // Send the removed broadcasts
1750            if (res.removedInfo != null) {
1751                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1752            }
1753
1754            // Now that we successfully installed the package, grant runtime
1755            // permissions if requested before broadcasting the install. Also
1756            // for legacy apps in permission review mode we clear the permission
1757            // review flag which is used to emulate runtime permissions for
1758            // legacy apps.
1759            if (grantPermissions) {
1760                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1761            }
1762
1763            final boolean update = res.removedInfo != null
1764                    && res.removedInfo.removedPackage != null;
1765
1766            // If this is the first time we have child packages for a disabled privileged
1767            // app that had no children, we grant requested runtime permissions to the new
1768            // children if the parent on the system image had them already granted.
1769            if (res.pkg.parentPackage != null) {
1770                synchronized (mPackages) {
1771                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1772                }
1773            }
1774
1775            synchronized (mPackages) {
1776                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1777            }
1778
1779            final String packageName = res.pkg.applicationInfo.packageName;
1780
1781            // Determine the set of users who are adding this package for
1782            // the first time vs. those who are seeing an update.
1783            int[] firstUsers = EMPTY_INT_ARRAY;
1784            int[] updateUsers = EMPTY_INT_ARRAY;
1785            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1786            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1787            for (int newUser : res.newUsers) {
1788                if (ps.getInstantApp(newUser)) {
1789                    continue;
1790                }
1791                if (allNewUsers) {
1792                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1793                    continue;
1794                }
1795                boolean isNew = true;
1796                for (int origUser : res.origUsers) {
1797                    if (origUser == newUser) {
1798                        isNew = false;
1799                        break;
1800                    }
1801                }
1802                if (isNew) {
1803                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1804                } else {
1805                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1806                }
1807            }
1808
1809            // Send installed broadcasts if the package is not a static shared lib.
1810            if (res.pkg.staticSharedLibName == null) {
1811                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1812
1813                // Send added for users that see the package for the first time
1814                // sendPackageAddedForNewUsers also deals with system apps
1815                int appId = UserHandle.getAppId(res.uid);
1816                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1817                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1818
1819                // Send added for users that don't see the package for the first time
1820                Bundle extras = new Bundle(1);
1821                extras.putInt(Intent.EXTRA_UID, res.uid);
1822                if (update) {
1823                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1824                }
1825                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1826                        extras, 0 /*flags*/, null /*targetPackage*/,
1827                        null /*finishedReceiver*/, updateUsers);
1828
1829                // Send replaced for users that don't see the package for the first time
1830                if (update) {
1831                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1832                            packageName, extras, 0 /*flags*/,
1833                            null /*targetPackage*/, null /*finishedReceiver*/,
1834                            updateUsers);
1835                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1836                            null /*package*/, null /*extras*/, 0 /*flags*/,
1837                            packageName /*targetPackage*/,
1838                            null /*finishedReceiver*/, updateUsers);
1839                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1840                    // First-install and we did a restore, so we're responsible for the
1841                    // first-launch broadcast.
1842                    if (DEBUG_BACKUP) {
1843                        Slog.i(TAG, "Post-restore of " + packageName
1844                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1845                    }
1846                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1847                }
1848
1849                // Send broadcast package appeared if forward locked/external for all users
1850                // treat asec-hosted packages like removable media on upgrade
1851                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1852                    if (DEBUG_INSTALL) {
1853                        Slog.i(TAG, "upgrading pkg " + res.pkg
1854                                + " is ASEC-hosted -> AVAILABLE");
1855                    }
1856                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1857                    ArrayList<String> pkgList = new ArrayList<>(1);
1858                    pkgList.add(packageName);
1859                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1860                }
1861            }
1862
1863            // Work that needs to happen on first install within each user
1864            if (firstUsers != null && firstUsers.length > 0) {
1865                synchronized (mPackages) {
1866                    for (int userId : firstUsers) {
1867                        // If this app is a browser and it's newly-installed for some
1868                        // users, clear any default-browser state in those users. The
1869                        // app's nature doesn't depend on the user, so we can just check
1870                        // its browser nature in any user and generalize.
1871                        if (packageIsBrowser(packageName, userId)) {
1872                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1873                        }
1874
1875                        // We may also need to apply pending (restored) runtime
1876                        // permission grants within these users.
1877                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1878                    }
1879                }
1880            }
1881
1882            // Log current value of "unknown sources" setting
1883            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1884                    getUnknownSourcesSettings());
1885
1886            // Force a gc to clear up things
1887            Runtime.getRuntime().gc();
1888
1889            // Remove the replaced package's older resources safely now
1890            // We delete after a gc for applications  on sdcard.
1891            if (res.removedInfo != null && res.removedInfo.args != null) {
1892                synchronized (mInstallLock) {
1893                    res.removedInfo.args.doPostDeleteLI(true);
1894                }
1895            }
1896
1897            // Notify DexManager that the package was installed for new users.
1898            // The updated users should already be indexed and the package code paths
1899            // should not change.
1900            // Don't notify the manager for ephemeral apps as they are not expected to
1901            // survive long enough to benefit of background optimizations.
1902            for (int userId : firstUsers) {
1903                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1904                mDexManager.notifyPackageInstalled(info, userId);
1905            }
1906        }
1907
1908        // If someone is watching installs - notify them
1909        if (installObserver != null) {
1910            try {
1911                Bundle extras = extrasForInstallResult(res);
1912                installObserver.onPackageInstalled(res.name, res.returnCode,
1913                        res.returnMsg, extras);
1914            } catch (RemoteException e) {
1915                Slog.i(TAG, "Observer no longer exists.");
1916            }
1917        }
1918    }
1919
1920    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1921            PackageParser.Package pkg) {
1922        if (pkg.parentPackage == null) {
1923            return;
1924        }
1925        if (pkg.requestedPermissions == null) {
1926            return;
1927        }
1928        final PackageSetting disabledSysParentPs = mSettings
1929                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1930        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1931                || !disabledSysParentPs.isPrivileged()
1932                || (disabledSysParentPs.childPackageNames != null
1933                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1934            return;
1935        }
1936        final int[] allUserIds = sUserManager.getUserIds();
1937        final int permCount = pkg.requestedPermissions.size();
1938        for (int i = 0; i < permCount; i++) {
1939            String permission = pkg.requestedPermissions.get(i);
1940            BasePermission bp = mSettings.mPermissions.get(permission);
1941            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1942                continue;
1943            }
1944            for (int userId : allUserIds) {
1945                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1946                        permission, userId)) {
1947                    grantRuntimePermission(pkg.packageName, permission, userId);
1948                }
1949            }
1950        }
1951    }
1952
1953    private StorageEventListener mStorageListener = new StorageEventListener() {
1954        @Override
1955        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1956            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1957                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1958                    final String volumeUuid = vol.getFsUuid();
1959
1960                    // Clean up any users or apps that were removed or recreated
1961                    // while this volume was missing
1962                    sUserManager.reconcileUsers(volumeUuid);
1963                    reconcileApps(volumeUuid);
1964
1965                    // Clean up any install sessions that expired or were
1966                    // cancelled while this volume was missing
1967                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1968
1969                    loadPrivatePackages(vol);
1970
1971                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1972                    unloadPrivatePackages(vol);
1973                }
1974            }
1975
1976            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1977                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1978                    updateExternalMediaStatus(true, false);
1979                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1980                    updateExternalMediaStatus(false, false);
1981                }
1982            }
1983        }
1984
1985        @Override
1986        public void onVolumeForgotten(String fsUuid) {
1987            if (TextUtils.isEmpty(fsUuid)) {
1988                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1989                return;
1990            }
1991
1992            // Remove any apps installed on the forgotten volume
1993            synchronized (mPackages) {
1994                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1995                for (PackageSetting ps : packages) {
1996                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1997                    deletePackageVersioned(new VersionedPackage(ps.name,
1998                            PackageManager.VERSION_CODE_HIGHEST),
1999                            new LegacyPackageDeleteObserver(null).getBinder(),
2000                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2001                    // Try very hard to release any references to this package
2002                    // so we don't risk the system server being killed due to
2003                    // open FDs
2004                    AttributeCache.instance().removePackage(ps.name);
2005                }
2006
2007                mSettings.onVolumeForgotten(fsUuid);
2008                mSettings.writeLPr();
2009            }
2010        }
2011    };
2012
2013    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2014            String[] grantedPermissions) {
2015        for (int userId : userIds) {
2016            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2017        }
2018    }
2019
2020    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2021            String[] grantedPermissions) {
2022        SettingBase sb = (SettingBase) pkg.mExtras;
2023        if (sb == null) {
2024            return;
2025        }
2026
2027        PermissionsState permissionsState = sb.getPermissionsState();
2028
2029        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2030                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2031
2032        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2033                >= Build.VERSION_CODES.M;
2034
2035        for (String permission : pkg.requestedPermissions) {
2036            final BasePermission bp;
2037            synchronized (mPackages) {
2038                bp = mSettings.mPermissions.get(permission);
2039            }
2040            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2041                    && (grantedPermissions == null
2042                           || ArrayUtils.contains(grantedPermissions, permission))) {
2043                final int flags = permissionsState.getPermissionFlags(permission, userId);
2044                if (supportsRuntimePermissions) {
2045                    // Installer cannot change immutable permissions.
2046                    if ((flags & immutableFlags) == 0) {
2047                        grantRuntimePermission(pkg.packageName, permission, userId);
2048                    }
2049                } else if (mPermissionReviewRequired) {
2050                    // In permission review mode we clear the review flag when we
2051                    // are asked to install the app with all permissions granted.
2052                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2053                        updatePermissionFlags(permission, pkg.packageName,
2054                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2055                    }
2056                }
2057            }
2058        }
2059    }
2060
2061    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2062        Bundle extras = null;
2063        switch (res.returnCode) {
2064            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2065                extras = new Bundle();
2066                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2067                        res.origPermission);
2068                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2069                        res.origPackage);
2070                break;
2071            }
2072            case PackageManager.INSTALL_SUCCEEDED: {
2073                extras = new Bundle();
2074                extras.putBoolean(Intent.EXTRA_REPLACING,
2075                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2076                break;
2077            }
2078        }
2079        return extras;
2080    }
2081
2082    void scheduleWriteSettingsLocked() {
2083        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2084            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2085        }
2086    }
2087
2088    void scheduleWritePackageListLocked(int userId) {
2089        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2090            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2091            msg.arg1 = userId;
2092            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2093        }
2094    }
2095
2096    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2097        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2098        scheduleWritePackageRestrictionsLocked(userId);
2099    }
2100
2101    void scheduleWritePackageRestrictionsLocked(int userId) {
2102        final int[] userIds = (userId == UserHandle.USER_ALL)
2103                ? sUserManager.getUserIds() : new int[]{userId};
2104        for (int nextUserId : userIds) {
2105            if (!sUserManager.exists(nextUserId)) return;
2106            mDirtyUsers.add(nextUserId);
2107            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2108                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2109            }
2110        }
2111    }
2112
2113    public static PackageManagerService main(Context context, Installer installer,
2114            boolean factoryTest, boolean onlyCore) {
2115        // Self-check for initial settings.
2116        PackageManagerServiceCompilerMapping.checkProperties();
2117
2118        PackageManagerService m = new PackageManagerService(context, installer,
2119                factoryTest, onlyCore);
2120        m.enableSystemUserPackages();
2121        ServiceManager.addService("package", m);
2122        return m;
2123    }
2124
2125    private void enableSystemUserPackages() {
2126        if (!UserManager.isSplitSystemUser()) {
2127            return;
2128        }
2129        // For system user, enable apps based on the following conditions:
2130        // - app is whitelisted or belong to one of these groups:
2131        //   -- system app which has no launcher icons
2132        //   -- system app which has INTERACT_ACROSS_USERS permission
2133        //   -- system IME app
2134        // - app is not in the blacklist
2135        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2136        Set<String> enableApps = new ArraySet<>();
2137        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2138                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2139                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2140        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2141        enableApps.addAll(wlApps);
2142        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2143                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2144        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2145        enableApps.removeAll(blApps);
2146        Log.i(TAG, "Applications installed for system user: " + enableApps);
2147        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2148                UserHandle.SYSTEM);
2149        final int allAppsSize = allAps.size();
2150        synchronized (mPackages) {
2151            for (int i = 0; i < allAppsSize; i++) {
2152                String pName = allAps.get(i);
2153                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2154                // Should not happen, but we shouldn't be failing if it does
2155                if (pkgSetting == null) {
2156                    continue;
2157                }
2158                boolean install = enableApps.contains(pName);
2159                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2160                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2161                            + " for system user");
2162                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2163                }
2164            }
2165            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2166        }
2167    }
2168
2169    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2170        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2171                Context.DISPLAY_SERVICE);
2172        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2173    }
2174
2175    /**
2176     * Requests that files preopted on a secondary system partition be copied to the data partition
2177     * if possible.  Note that the actual copying of the files is accomplished by init for security
2178     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2179     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2180     */
2181    private static void requestCopyPreoptedFiles() {
2182        final int WAIT_TIME_MS = 100;
2183        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2184        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2185            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2186            // We will wait for up to 100 seconds.
2187            final long timeStart = SystemClock.uptimeMillis();
2188            final long timeEnd = timeStart + 100 * 1000;
2189            long timeNow = timeStart;
2190            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2191                try {
2192                    Thread.sleep(WAIT_TIME_MS);
2193                } catch (InterruptedException e) {
2194                    // Do nothing
2195                }
2196                timeNow = SystemClock.uptimeMillis();
2197                if (timeNow > timeEnd) {
2198                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2199                    Slog.wtf(TAG, "cppreopt did not finish!");
2200                    break;
2201                }
2202            }
2203
2204            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2205        }
2206    }
2207
2208    public PackageManagerService(Context context, Installer installer,
2209            boolean factoryTest, boolean onlyCore) {
2210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2211        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2212                SystemClock.uptimeMillis());
2213
2214        if (mSdkVersion <= 0) {
2215            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2216        }
2217
2218        mContext = context;
2219
2220        mPermissionReviewRequired = context.getResources().getBoolean(
2221                R.bool.config_permissionReviewRequired);
2222
2223        mFactoryTest = factoryTest;
2224        mOnlyCore = onlyCore;
2225        mMetrics = new DisplayMetrics();
2226        mSettings = new Settings(mPackages);
2227        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2228                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2229        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2230                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2231        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2232                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2233        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2234                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2235        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2236                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2237        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239
2240        String separateProcesses = SystemProperties.get("debug.separate_processes");
2241        if (separateProcesses != null && separateProcesses.length() > 0) {
2242            if ("*".equals(separateProcesses)) {
2243                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2244                mSeparateProcesses = null;
2245                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2246            } else {
2247                mDefParseFlags = 0;
2248                mSeparateProcesses = separateProcesses.split(",");
2249                Slog.w(TAG, "Running with debug.separate_processes: "
2250                        + separateProcesses);
2251            }
2252        } else {
2253            mDefParseFlags = 0;
2254            mSeparateProcesses = null;
2255        }
2256
2257        mInstaller = installer;
2258        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2259                "*dexopt*");
2260        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2261        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2262
2263        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2264                FgThread.get().getLooper());
2265
2266        getDefaultDisplayMetrics(context, mMetrics);
2267
2268        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2269        SystemConfig systemConfig = SystemConfig.getInstance();
2270        mGlobalGids = systemConfig.getGlobalGids();
2271        mSystemPermissions = systemConfig.getSystemPermissions();
2272        mAvailableFeatures = systemConfig.getAvailableFeatures();
2273        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2274
2275        mProtectedPackages = new ProtectedPackages(mContext);
2276
2277        synchronized (mInstallLock) {
2278        // writer
2279        synchronized (mPackages) {
2280            mHandlerThread = new ServiceThread(TAG,
2281                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2282            mHandlerThread.start();
2283            mHandler = new PackageHandler(mHandlerThread.getLooper());
2284            mProcessLoggingHandler = new ProcessLoggingHandler();
2285            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2286
2287            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2288            mInstantAppRegistry = new InstantAppRegistry(this);
2289
2290            File dataDir = Environment.getDataDirectory();
2291            mAppInstallDir = new File(dataDir, "app");
2292            mAppLib32InstallDir = new File(dataDir, "app-lib");
2293            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2294            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2295            sUserManager = new UserManagerService(context, this,
2296                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2297
2298            // Propagate permission configuration in to package manager.
2299            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2300                    = systemConfig.getPermissions();
2301            for (int i=0; i<permConfig.size(); i++) {
2302                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2303                BasePermission bp = mSettings.mPermissions.get(perm.name);
2304                if (bp == null) {
2305                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2306                    mSettings.mPermissions.put(perm.name, bp);
2307                }
2308                if (perm.gids != null) {
2309                    bp.setGids(perm.gids, perm.perUser);
2310                }
2311            }
2312
2313            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2314            final int builtInLibCount = libConfig.size();
2315            for (int i = 0; i < builtInLibCount; i++) {
2316                String name = libConfig.keyAt(i);
2317                String path = libConfig.valueAt(i);
2318                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2319                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2320            }
2321
2322            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2323
2324            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2325            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2326            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2327
2328            // Clean up orphaned packages for which the code path doesn't exist
2329            // and they are an update to a system app - caused by bug/32321269
2330            final int packageSettingCount = mSettings.mPackages.size();
2331            for (int i = packageSettingCount - 1; i >= 0; i--) {
2332                PackageSetting ps = mSettings.mPackages.valueAt(i);
2333                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2334                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2335                    mSettings.mPackages.removeAt(i);
2336                    mSettings.enableSystemPackageLPw(ps.name);
2337                }
2338            }
2339
2340            if (mFirstBoot) {
2341                requestCopyPreoptedFiles();
2342            }
2343
2344            String customResolverActivity = Resources.getSystem().getString(
2345                    R.string.config_customResolverActivity);
2346            if (TextUtils.isEmpty(customResolverActivity)) {
2347                customResolverActivity = null;
2348            } else {
2349                mCustomResolverComponentName = ComponentName.unflattenFromString(
2350                        customResolverActivity);
2351            }
2352
2353            long startTime = SystemClock.uptimeMillis();
2354
2355            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2356                    startTime);
2357
2358            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2359            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2360
2361            if (bootClassPath == null) {
2362                Slog.w(TAG, "No BOOTCLASSPATH found!");
2363            }
2364
2365            if (systemServerClassPath == null) {
2366                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2367            }
2368
2369            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2370            final String[] dexCodeInstructionSets =
2371                    getDexCodeInstructionSets(
2372                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2373
2374            /**
2375             * Ensure all external libraries have had dexopt run on them.
2376             */
2377            if (mSharedLibraries.size() > 0) {
2378                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2379                // NOTE: For now, we're compiling these system "shared libraries"
2380                // (and framework jars) into all available architectures. It's possible
2381                // to compile them only when we come across an app that uses them (there's
2382                // already logic for that in scanPackageLI) but that adds some complexity.
2383                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2384                    final int libCount = mSharedLibraries.size();
2385                    for (int i = 0; i < libCount; i++) {
2386                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2387                        final int versionCount = versionedLib.size();
2388                        for (int j = 0; j < versionCount; j++) {
2389                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2390                            final String libPath = libEntry.path != null
2391                                    ? libEntry.path : libEntry.apk;
2392                            if (libPath == null) {
2393                                continue;
2394                            }
2395                            try {
2396                                // Shared libraries do not have profiles so we perform a full
2397                                // AOT compilation (if needed).
2398                                int dexoptNeeded = DexFile.getDexOptNeeded(
2399                                        libPath, dexCodeInstructionSet,
2400                                        getCompilerFilterForReason(REASON_SHARED_APK),
2401                                        false /* newProfile */);
2402                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2403                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2404                                            dexCodeInstructionSet, dexoptNeeded, null,
2405                                            DEXOPT_PUBLIC,
2406                                            getCompilerFilterForReason(REASON_SHARED_APK),
2407                                            StorageManager.UUID_PRIVATE_INTERNAL,
2408                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2409                                }
2410                            } catch (FileNotFoundException e) {
2411                                Slog.w(TAG, "Library not found: " + libPath);
2412                            } catch (IOException | InstallerException e) {
2413                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2414                                        + e.getMessage());
2415                            }
2416                        }
2417                    }
2418                }
2419                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2420            }
2421
2422            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2423
2424            final VersionInfo ver = mSettings.getInternalVersion();
2425            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2426
2427            // when upgrading from pre-M, promote system app permissions from install to runtime
2428            mPromoteSystemApps =
2429                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2430
2431            // When upgrading from pre-N, we need to handle package extraction like first boot,
2432            // as there is no profiling data available.
2433            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2434
2435            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2436
2437            // save off the names of pre-existing system packages prior to scanning; we don't
2438            // want to automatically grant runtime permissions for new system apps
2439            if (mPromoteSystemApps) {
2440                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2441                while (pkgSettingIter.hasNext()) {
2442                    PackageSetting ps = pkgSettingIter.next();
2443                    if (isSystemApp(ps)) {
2444                        mExistingSystemPackages.add(ps.name);
2445                    }
2446                }
2447            }
2448
2449            mCacheDir = preparePackageParserCache(mIsUpgrade);
2450
2451            // Set flag to monitor and not change apk file paths when
2452            // scanning install directories.
2453            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2454
2455            if (mIsUpgrade || mFirstBoot) {
2456                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2457            }
2458
2459            // Collect vendor overlay packages. (Do this before scanning any apps.)
2460            // For security and version matching reason, only consider
2461            // overlay packages if they reside in the right directory.
2462            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2463            if (overlayThemeDir.isEmpty()) {
2464                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2465            }
2466            if (!overlayThemeDir.isEmpty()) {
2467                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2468                        | PackageParser.PARSE_IS_SYSTEM
2469                        | PackageParser.PARSE_IS_SYSTEM_DIR
2470                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2471            }
2472            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2473                    | PackageParser.PARSE_IS_SYSTEM
2474                    | PackageParser.PARSE_IS_SYSTEM_DIR
2475                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2476
2477            // Find base frameworks (resource packages without code).
2478            scanDirTracedLI(frameworkDir, mDefParseFlags
2479                    | PackageParser.PARSE_IS_SYSTEM
2480                    | PackageParser.PARSE_IS_SYSTEM_DIR
2481                    | PackageParser.PARSE_IS_PRIVILEGED,
2482                    scanFlags | SCAN_NO_DEX, 0);
2483
2484            // Collected privileged system packages.
2485            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2486            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR
2489                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2490
2491            // Collect ordinary system packages.
2492            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2493            scanDirTracedLI(systemAppDir, mDefParseFlags
2494                    | PackageParser.PARSE_IS_SYSTEM
2495                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2496
2497            // Collect all vendor packages.
2498            File vendorAppDir = new File("/vendor/app");
2499            try {
2500                vendorAppDir = vendorAppDir.getCanonicalFile();
2501            } catch (IOException e) {
2502                // failed to look up canonical path, continue with original one
2503            }
2504            scanDirTracedLI(vendorAppDir, mDefParseFlags
2505                    | PackageParser.PARSE_IS_SYSTEM
2506                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2507
2508            // Collect all OEM packages.
2509            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2510            scanDirTracedLI(oemAppDir, mDefParseFlags
2511                    | PackageParser.PARSE_IS_SYSTEM
2512                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2513
2514            // Prune any system packages that no longer exist.
2515            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2516            if (!mOnlyCore) {
2517                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2518                while (psit.hasNext()) {
2519                    PackageSetting ps = psit.next();
2520
2521                    /*
2522                     * If this is not a system app, it can't be a
2523                     * disable system app.
2524                     */
2525                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2526                        continue;
2527                    }
2528
2529                    /*
2530                     * If the package is scanned, it's not erased.
2531                     */
2532                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2533                    if (scannedPkg != null) {
2534                        /*
2535                         * If the system app is both scanned and in the
2536                         * disabled packages list, then it must have been
2537                         * added via OTA. Remove it from the currently
2538                         * scanned package so the previously user-installed
2539                         * application can be scanned.
2540                         */
2541                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2542                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2543                                    + ps.name + "; removing system app.  Last known codePath="
2544                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2545                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2546                                    + scannedPkg.mVersionCode);
2547                            removePackageLI(scannedPkg, true);
2548                            mExpectingBetter.put(ps.name, ps.codePath);
2549                        }
2550
2551                        continue;
2552                    }
2553
2554                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2555                        psit.remove();
2556                        logCriticalInfo(Log.WARN, "System package " + ps.name
2557                                + " no longer exists; it's data will be wiped");
2558                        // Actual deletion of code and data will be handled by later
2559                        // reconciliation step
2560                    } else {
2561                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2562                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2563                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2564                        }
2565                    }
2566                }
2567            }
2568
2569            //look for any incomplete package installations
2570            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2571            for (int i = 0; i < deletePkgsList.size(); i++) {
2572                // Actual deletion of code and data will be handled by later
2573                // reconciliation step
2574                final String packageName = deletePkgsList.get(i).name;
2575                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2576                synchronized (mPackages) {
2577                    mSettings.removePackageLPw(packageName);
2578                }
2579            }
2580
2581            //delete tmp files
2582            deleteTempPackageFiles();
2583
2584            // Remove any shared userIDs that have no associated packages
2585            mSettings.pruneSharedUsersLPw();
2586
2587            if (!mOnlyCore) {
2588                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2589                        SystemClock.uptimeMillis());
2590                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2591
2592                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2593                        | PackageParser.PARSE_FORWARD_LOCK,
2594                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2595
2596                /**
2597                 * Remove disable package settings for any updated system
2598                 * apps that were removed via an OTA. If they're not a
2599                 * previously-updated app, remove them completely.
2600                 * Otherwise, just revoke their system-level permissions.
2601                 */
2602                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2603                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2604                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2605
2606                    String msg;
2607                    if (deletedPkg == null) {
2608                        msg = "Updated system package " + deletedAppName
2609                                + " no longer exists; it's data will be wiped";
2610                        // Actual deletion of code and data will be handled by later
2611                        // reconciliation step
2612                    } else {
2613                        msg = "Updated system app + " + deletedAppName
2614                                + " no longer present; removing system privileges for "
2615                                + deletedAppName;
2616
2617                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2618
2619                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2620                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2621                    }
2622                    logCriticalInfo(Log.WARN, msg);
2623                }
2624
2625                /**
2626                 * Make sure all system apps that we expected to appear on
2627                 * the userdata partition actually showed up. If they never
2628                 * appeared, crawl back and revive the system version.
2629                 */
2630                for (int i = 0; i < mExpectingBetter.size(); i++) {
2631                    final String packageName = mExpectingBetter.keyAt(i);
2632                    if (!mPackages.containsKey(packageName)) {
2633                        final File scanFile = mExpectingBetter.valueAt(i);
2634
2635                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2636                                + " but never showed up; reverting to system");
2637
2638                        int reparseFlags = mDefParseFlags;
2639                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2640                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2641                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2642                                    | PackageParser.PARSE_IS_PRIVILEGED;
2643                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2644                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2645                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2646                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2650                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2651                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2652                        } else {
2653                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2654                            continue;
2655                        }
2656
2657                        mSettings.enableSystemPackageLPw(packageName);
2658
2659                        try {
2660                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2661                        } catch (PackageManagerException e) {
2662                            Slog.e(TAG, "Failed to parse original system package: "
2663                                    + e.getMessage());
2664                        }
2665                    }
2666                }
2667            }
2668            mExpectingBetter.clear();
2669
2670            // Resolve the storage manager.
2671            mStorageManagerPackage = getStorageManagerPackageName();
2672
2673            // Resolve protected action filters. Only the setup wizard is allowed to
2674            // have a high priority filter for these actions.
2675            mSetupWizardPackage = getSetupWizardPackageName();
2676            if (mProtectedFilters.size() > 0) {
2677                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2678                    Slog.i(TAG, "No setup wizard;"
2679                        + " All protected intents capped to priority 0");
2680                }
2681                for (ActivityIntentInfo filter : mProtectedFilters) {
2682                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2683                        if (DEBUG_FILTERS) {
2684                            Slog.i(TAG, "Found setup wizard;"
2685                                + " allow priority " + filter.getPriority() + ";"
2686                                + " package: " + filter.activity.info.packageName
2687                                + " activity: " + filter.activity.className
2688                                + " priority: " + filter.getPriority());
2689                        }
2690                        // skip setup wizard; allow it to keep the high priority filter
2691                        continue;
2692                    }
2693                    Slog.w(TAG, "Protected action; cap priority to 0;"
2694                            + " package: " + filter.activity.info.packageName
2695                            + " activity: " + filter.activity.className
2696                            + " origPrio: " + filter.getPriority());
2697                    filter.setPriority(0);
2698                }
2699            }
2700            mDeferProtectedFilters = false;
2701            mProtectedFilters.clear();
2702
2703            // Now that we know all of the shared libraries, update all clients to have
2704            // the correct library paths.
2705            updateAllSharedLibrariesLPw(null);
2706
2707            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2708                // NOTE: We ignore potential failures here during a system scan (like
2709                // the rest of the commands above) because there's precious little we
2710                // can do about it. A settings error is reported, though.
2711                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2712            }
2713
2714            // Now that we know all the packages we are keeping,
2715            // read and update their last usage times.
2716            mPackageUsage.read(mPackages);
2717            mCompilerStats.read();
2718
2719            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2720                    SystemClock.uptimeMillis());
2721            Slog.i(TAG, "Time to scan packages: "
2722                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2723                    + " seconds");
2724
2725            // If the platform SDK has changed since the last time we booted,
2726            // we need to re-grant app permission to catch any new ones that
2727            // appear.  This is really a hack, and means that apps can in some
2728            // cases get permissions that the user didn't initially explicitly
2729            // allow...  it would be nice to have some better way to handle
2730            // this situation.
2731            int updateFlags = UPDATE_PERMISSIONS_ALL;
2732            if (ver.sdkVersion != mSdkVersion) {
2733                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2734                        + mSdkVersion + "; regranting permissions for internal storage");
2735                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2736            }
2737            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2738            ver.sdkVersion = mSdkVersion;
2739
2740            // If this is the first boot or an update from pre-M, and it is a normal
2741            // boot, then we need to initialize the default preferred apps across
2742            // all defined users.
2743            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2744                for (UserInfo user : sUserManager.getUsers(true)) {
2745                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2746                    applyFactoryDefaultBrowserLPw(user.id);
2747                    primeDomainVerificationsLPw(user.id);
2748                }
2749            }
2750
2751            // Prepare storage for system user really early during boot,
2752            // since core system apps like SettingsProvider and SystemUI
2753            // can't wait for user to start
2754            final int storageFlags;
2755            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2756                storageFlags = StorageManager.FLAG_STORAGE_DE;
2757            } else {
2758                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2759            }
2760            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2761                    storageFlags, true /* migrateAppData */);
2762
2763            // If this is first boot after an OTA, and a normal boot, then
2764            // we need to clear code cache directories.
2765            // Note that we do *not* clear the application profiles. These remain valid
2766            // across OTAs and are used to drive profile verification (post OTA) and
2767            // profile compilation (without waiting to collect a fresh set of profiles).
2768            if (mIsUpgrade && !onlyCore) {
2769                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2770                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2771                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2772                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2773                        // No apps are running this early, so no need to freeze
2774                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2775                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2776                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2777                    }
2778                }
2779                ver.fingerprint = Build.FINGERPRINT;
2780            }
2781
2782            checkDefaultBrowser();
2783
2784            // clear only after permissions and other defaults have been updated
2785            mExistingSystemPackages.clear();
2786            mPromoteSystemApps = false;
2787
2788            // All the changes are done during package scanning.
2789            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2790
2791            // can downgrade to reader
2792            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2793            mSettings.writeLPr();
2794            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2795
2796            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2797            // early on (before the package manager declares itself as early) because other
2798            // components in the system server might ask for package contexts for these apps.
2799            //
2800            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2801            // (i.e, that the data partition is unavailable).
2802            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2803                long start = System.nanoTime();
2804                List<PackageParser.Package> coreApps = new ArrayList<>();
2805                for (PackageParser.Package pkg : mPackages.values()) {
2806                    if (pkg.coreApp) {
2807                        coreApps.add(pkg);
2808                    }
2809                }
2810
2811                int[] stats = performDexOptUpgrade(coreApps, false,
2812                        getCompilerFilterForReason(REASON_CORE_APP));
2813
2814                final int elapsedTimeSeconds =
2815                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2816                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2817
2818                if (DEBUG_DEXOPT) {
2819                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2820                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2821                }
2822
2823
2824                // TODO: Should we log these stats to tron too ?
2825                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2826                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2827                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2828                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2829            }
2830
2831            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2832                    SystemClock.uptimeMillis());
2833
2834            if (!mOnlyCore) {
2835                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2836                mRequiredInstallerPackage = getRequiredInstallerLPr();
2837                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2838                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2839                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2840                        mIntentFilterVerifierComponent);
2841                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2842                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2843                        SharedLibraryInfo.VERSION_UNDEFINED);
2844                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2845                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2846                        SharedLibraryInfo.VERSION_UNDEFINED);
2847            } else {
2848                mRequiredVerifierPackage = null;
2849                mRequiredInstallerPackage = null;
2850                mRequiredUninstallerPackage = null;
2851                mIntentFilterVerifierComponent = null;
2852                mIntentFilterVerifier = null;
2853                mServicesSystemSharedLibraryPackageName = null;
2854                mSharedSystemSharedLibraryPackageName = null;
2855            }
2856
2857            mInstallerService = new PackageInstallerService(context, this);
2858
2859            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2860            if (ephemeralResolverComponent != null) {
2861                if (DEBUG_EPHEMERAL) {
2862                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2863                }
2864                mEphemeralResolverConnection =
2865                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2866            } else {
2867                mEphemeralResolverConnection = null;
2868            }
2869            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2870            if (mEphemeralInstallerComponent != null) {
2871                if (DEBUG_EPHEMERAL) {
2872                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2873                }
2874                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2875            }
2876
2877            // Read and update the usage of dex files.
2878            // Do this at the end of PM init so that all the packages have their
2879            // data directory reconciled.
2880            // At this point we know the code paths of the packages, so we can validate
2881            // the disk file and build the internal cache.
2882            // The usage file is expected to be small so loading and verifying it
2883            // should take a fairly small time compare to the other activities (e.g. package
2884            // scanning).
2885            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2886            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2887            for (int userId : currentUserIds) {
2888                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2889            }
2890            mDexManager.load(userPackages);
2891        } // synchronized (mPackages)
2892        } // synchronized (mInstallLock)
2893
2894        // Now after opening every single application zip, make sure they
2895        // are all flushed.  Not really needed, but keeps things nice and
2896        // tidy.
2897        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2898        Runtime.getRuntime().gc();
2899        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2900
2901        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2902        FallbackCategoryProvider.loadFallbacks();
2903        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2904
2905        // The initial scanning above does many calls into installd while
2906        // holding the mPackages lock, but we're mostly interested in yelling
2907        // once we have a booted system.
2908        mInstaller.setWarnIfHeld(mPackages);
2909
2910        // Expose private service for system components to use.
2911        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2912        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2913    }
2914
2915    private static File preparePackageParserCache(boolean isUpgrade) {
2916        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2917            return null;
2918        }
2919
2920        // Disable package parsing on eng builds to allow for faster incremental development.
2921        if ("eng".equals(Build.TYPE)) {
2922            return null;
2923        }
2924
2925        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2926            Slog.i(TAG, "Disabling package parser cache due to system property.");
2927            return null;
2928        }
2929
2930        // The base directory for the package parser cache lives under /data/system/.
2931        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2932                "package_cache");
2933        if (cacheBaseDir == null) {
2934            return null;
2935        }
2936
2937        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2938        // This also serves to "GC" unused entries when the package cache version changes (which
2939        // can only happen during upgrades).
2940        if (isUpgrade) {
2941            FileUtils.deleteContents(cacheBaseDir);
2942        }
2943
2944
2945        // Return the versioned package cache directory. This is something like
2946        // "/data/system/package_cache/1"
2947        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2948
2949        // The following is a workaround to aid development on non-numbered userdebug
2950        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2951        // the system partition is newer.
2952        //
2953        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2954        // that starts with "eng." to signify that this is an engineering build and not
2955        // destined for release.
2956        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2957            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2958
2959            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2960            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2961            // in general and should not be used for production changes. In this specific case,
2962            // we know that they will work.
2963            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2964            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2965                FileUtils.deleteContents(cacheBaseDir);
2966                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2967            }
2968        }
2969
2970        return cacheDir;
2971    }
2972
2973    @Override
2974    public boolean isFirstBoot() {
2975        return mFirstBoot;
2976    }
2977
2978    @Override
2979    public boolean isOnlyCoreApps() {
2980        return mOnlyCore;
2981    }
2982
2983    @Override
2984    public boolean isUpgrade() {
2985        return mIsUpgrade;
2986    }
2987
2988    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2989        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2990
2991        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2992                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2993                UserHandle.USER_SYSTEM);
2994        if (matches.size() == 1) {
2995            return matches.get(0).getComponentInfo().packageName;
2996        } else if (matches.size() == 0) {
2997            Log.e(TAG, "There should probably be a verifier, but, none were found");
2998            return null;
2999        }
3000        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3001    }
3002
3003    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3004        synchronized (mPackages) {
3005            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3006            if (libraryEntry == null) {
3007                throw new IllegalStateException("Missing required shared library:" + name);
3008            }
3009            return libraryEntry.apk;
3010        }
3011    }
3012
3013    private @NonNull String getRequiredInstallerLPr() {
3014        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3015        intent.addCategory(Intent.CATEGORY_DEFAULT);
3016        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3017
3018        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3019                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3020                UserHandle.USER_SYSTEM);
3021        if (matches.size() == 1) {
3022            ResolveInfo resolveInfo = matches.get(0);
3023            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3024                throw new RuntimeException("The installer must be a privileged app");
3025            }
3026            return matches.get(0).getComponentInfo().packageName;
3027        } else {
3028            throw new RuntimeException("There must be exactly one installer; found " + matches);
3029        }
3030    }
3031
3032    private @NonNull String getRequiredUninstallerLPr() {
3033        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3034        intent.addCategory(Intent.CATEGORY_DEFAULT);
3035        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3036
3037        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3038                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3039                UserHandle.USER_SYSTEM);
3040        if (resolveInfo == null ||
3041                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3042            throw new RuntimeException("There must be exactly one uninstaller; found "
3043                    + resolveInfo);
3044        }
3045        return resolveInfo.getComponentInfo().packageName;
3046    }
3047
3048    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3049        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3050
3051        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3052                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3053                UserHandle.USER_SYSTEM);
3054        ResolveInfo best = null;
3055        final int N = matches.size();
3056        for (int i = 0; i < N; i++) {
3057            final ResolveInfo cur = matches.get(i);
3058            final String packageName = cur.getComponentInfo().packageName;
3059            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3060                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3061                continue;
3062            }
3063
3064            if (best == null || cur.priority > best.priority) {
3065                best = cur;
3066            }
3067        }
3068
3069        if (best != null) {
3070            return best.getComponentInfo().getComponentName();
3071        } else {
3072            throw new RuntimeException("There must be at least one intent filter verifier");
3073        }
3074    }
3075
3076    private @Nullable ComponentName getEphemeralResolverLPr() {
3077        final String[] packageArray =
3078                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3079        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3080            if (DEBUG_EPHEMERAL) {
3081                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3082            }
3083            return null;
3084        }
3085
3086        final int resolveFlags =
3087                MATCH_DIRECT_BOOT_AWARE
3088                | MATCH_DIRECT_BOOT_UNAWARE
3089                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3090        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3091        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3092                resolveFlags, UserHandle.USER_SYSTEM);
3093
3094        final int N = resolvers.size();
3095        if (N == 0) {
3096            if (DEBUG_EPHEMERAL) {
3097                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3098            }
3099            return null;
3100        }
3101
3102        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3103        for (int i = 0; i < N; i++) {
3104            final ResolveInfo info = resolvers.get(i);
3105
3106            if (info.serviceInfo == null) {
3107                continue;
3108            }
3109
3110            final String packageName = info.serviceInfo.packageName;
3111            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3112                if (DEBUG_EPHEMERAL) {
3113                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3114                            + " pkg: " + packageName + ", info:" + info);
3115                }
3116                continue;
3117            }
3118
3119            if (DEBUG_EPHEMERAL) {
3120                Slog.v(TAG, "Ephemeral resolver found;"
3121                        + " pkg: " + packageName + ", info:" + info);
3122            }
3123            return new ComponentName(packageName, info.serviceInfo.name);
3124        }
3125        if (DEBUG_EPHEMERAL) {
3126            Slog.v(TAG, "Ephemeral resolver NOT found");
3127        }
3128        return null;
3129    }
3130
3131    private @Nullable ComponentName getEphemeralInstallerLPr() {
3132        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3133        intent.addCategory(Intent.CATEGORY_DEFAULT);
3134        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3135
3136        final int resolveFlags =
3137                MATCH_DIRECT_BOOT_AWARE
3138                | MATCH_DIRECT_BOOT_UNAWARE
3139                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3140        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3141                resolveFlags, UserHandle.USER_SYSTEM);
3142        Iterator<ResolveInfo> iter = matches.iterator();
3143        while (iter.hasNext()) {
3144            final ResolveInfo rInfo = iter.next();
3145            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3146            if (ps != null) {
3147                final PermissionsState permissionsState = ps.getPermissionsState();
3148                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3149                    continue;
3150                }
3151            }
3152            iter.remove();
3153        }
3154        if (matches.size() == 0) {
3155            return null;
3156        } else if (matches.size() == 1) {
3157            return matches.get(0).getComponentInfo().getComponentName();
3158        } else {
3159            throw new RuntimeException(
3160                    "There must be at most one ephemeral installer; found " + matches);
3161        }
3162    }
3163
3164    private void primeDomainVerificationsLPw(int userId) {
3165        if (DEBUG_DOMAIN_VERIFICATION) {
3166            Slog.d(TAG, "Priming domain verifications in user " + userId);
3167        }
3168
3169        SystemConfig systemConfig = SystemConfig.getInstance();
3170        ArraySet<String> packages = systemConfig.getLinkedApps();
3171
3172        for (String packageName : packages) {
3173            PackageParser.Package pkg = mPackages.get(packageName);
3174            if (pkg != null) {
3175                if (!pkg.isSystemApp()) {
3176                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3177                    continue;
3178                }
3179
3180                ArraySet<String> domains = null;
3181                for (PackageParser.Activity a : pkg.activities) {
3182                    for (ActivityIntentInfo filter : a.intents) {
3183                        if (hasValidDomains(filter)) {
3184                            if (domains == null) {
3185                                domains = new ArraySet<String>();
3186                            }
3187                            domains.addAll(filter.getHostsList());
3188                        }
3189                    }
3190                }
3191
3192                if (domains != null && domains.size() > 0) {
3193                    if (DEBUG_DOMAIN_VERIFICATION) {
3194                        Slog.v(TAG, "      + " + packageName);
3195                    }
3196                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3197                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3198                    // and then 'always' in the per-user state actually used for intent resolution.
3199                    final IntentFilterVerificationInfo ivi;
3200                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3201                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3202                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3203                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3204                } else {
3205                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3206                            + "' does not handle web links");
3207                }
3208            } else {
3209                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3210            }
3211        }
3212
3213        scheduleWritePackageRestrictionsLocked(userId);
3214        scheduleWriteSettingsLocked();
3215    }
3216
3217    private void applyFactoryDefaultBrowserLPw(int userId) {
3218        // The default browser app's package name is stored in a string resource,
3219        // with a product-specific overlay used for vendor customization.
3220        String browserPkg = mContext.getResources().getString(
3221                com.android.internal.R.string.default_browser);
3222        if (!TextUtils.isEmpty(browserPkg)) {
3223            // non-empty string => required to be a known package
3224            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3225            if (ps == null) {
3226                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3227                browserPkg = null;
3228            } else {
3229                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3230            }
3231        }
3232
3233        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3234        // default.  If there's more than one, just leave everything alone.
3235        if (browserPkg == null) {
3236            calculateDefaultBrowserLPw(userId);
3237        }
3238    }
3239
3240    private void calculateDefaultBrowserLPw(int userId) {
3241        List<String> allBrowsers = resolveAllBrowserApps(userId);
3242        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3243        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3244    }
3245
3246    private List<String> resolveAllBrowserApps(int userId) {
3247        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3248        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3249                PackageManager.MATCH_ALL, userId);
3250
3251        final int count = list.size();
3252        List<String> result = new ArrayList<String>(count);
3253        for (int i=0; i<count; i++) {
3254            ResolveInfo info = list.get(i);
3255            if (info.activityInfo == null
3256                    || !info.handleAllWebDataURI
3257                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3258                    || result.contains(info.activityInfo.packageName)) {
3259                continue;
3260            }
3261            result.add(info.activityInfo.packageName);
3262        }
3263
3264        return result;
3265    }
3266
3267    private boolean packageIsBrowser(String packageName, int userId) {
3268        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3269                PackageManager.MATCH_ALL, userId);
3270        final int N = list.size();
3271        for (int i = 0; i < N; i++) {
3272            ResolveInfo info = list.get(i);
3273            if (packageName.equals(info.activityInfo.packageName)) {
3274                return true;
3275            }
3276        }
3277        return false;
3278    }
3279
3280    private void checkDefaultBrowser() {
3281        final int myUserId = UserHandle.myUserId();
3282        final String packageName = getDefaultBrowserPackageName(myUserId);
3283        if (packageName != null) {
3284            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3285            if (info == null) {
3286                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3287                synchronized (mPackages) {
3288                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3289                }
3290            }
3291        }
3292    }
3293
3294    @Override
3295    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3296            throws RemoteException {
3297        try {
3298            return super.onTransact(code, data, reply, flags);
3299        } catch (RuntimeException e) {
3300            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3301                Slog.wtf(TAG, "Package Manager Crash", e);
3302            }
3303            throw e;
3304        }
3305    }
3306
3307    static int[] appendInts(int[] cur, int[] add) {
3308        if (add == null) return cur;
3309        if (cur == null) return add;
3310        final int N = add.length;
3311        for (int i=0; i<N; i++) {
3312            cur = appendInt(cur, add[i]);
3313        }
3314        return cur;
3315    }
3316
3317    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3318        if (!sUserManager.exists(userId)) return null;
3319        if (ps == null) {
3320            return null;
3321        }
3322        final PackageParser.Package p = ps.pkg;
3323        if (p == null) {
3324            return null;
3325        }
3326        // Filter out ephemeral app metadata:
3327        //   * The system/shell/root can see metadata for any app
3328        //   * An installed app can see metadata for 1) other installed apps
3329        //     and 2) ephemeral apps that have explicitly interacted with it
3330        //   * Ephemeral apps can only see their own metadata
3331        //   * Holding a signature permission allows seeing instant apps
3332        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3333        if (callingAppId != Process.SYSTEM_UID
3334                && callingAppId != Process.SHELL_UID
3335                && callingAppId != Process.ROOT_UID
3336                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3337                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3338            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3339            if (instantAppPackageName != null) {
3340                // ephemeral apps can only get information on themselves
3341                if (!instantAppPackageName.equals(p.packageName)) {
3342                    return null;
3343                }
3344            } else {
3345                if (ps.getInstantApp(userId)) {
3346                    // only get access to the ephemeral app if we've been granted access
3347                    if (!mInstantAppRegistry.isInstantAccessGranted(
3348                            userId, callingAppId, ps.appId)) {
3349                        return null;
3350                    }
3351                }
3352            }
3353        }
3354
3355        final PermissionsState permissionsState = ps.getPermissionsState();
3356
3357        // Compute GIDs only if requested
3358        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3359                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3360        // Compute granted permissions only if package has requested permissions
3361        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3362                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3363        final PackageUserState state = ps.readUserState(userId);
3364
3365        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3366                && ps.isSystem()) {
3367            flags |= MATCH_ANY_USER;
3368        }
3369
3370        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3371                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3372
3373        if (packageInfo == null) {
3374            return null;
3375        }
3376
3377        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3378                resolveExternalPackageNameLPr(p);
3379
3380        return packageInfo;
3381    }
3382
3383    @Override
3384    public void checkPackageStartable(String packageName, int userId) {
3385        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3386
3387        synchronized (mPackages) {
3388            final PackageSetting ps = mSettings.mPackages.get(packageName);
3389            if (ps == null) {
3390                throw new SecurityException("Package " + packageName + " was not found!");
3391            }
3392
3393            if (!ps.getInstalled(userId)) {
3394                throw new SecurityException(
3395                        "Package " + packageName + " was not installed for user " + userId + "!");
3396            }
3397
3398            if (mSafeMode && !ps.isSystem()) {
3399                throw new SecurityException("Package " + packageName + " not a system app!");
3400            }
3401
3402            if (mFrozenPackages.contains(packageName)) {
3403                throw new SecurityException("Package " + packageName + " is currently frozen!");
3404            }
3405
3406            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3407                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3408                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3409            }
3410        }
3411    }
3412
3413    @Override
3414    public boolean isPackageAvailable(String packageName, int userId) {
3415        if (!sUserManager.exists(userId)) return false;
3416        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3417                false /* requireFullPermission */, false /* checkShell */, "is package available");
3418        synchronized (mPackages) {
3419            PackageParser.Package p = mPackages.get(packageName);
3420            if (p != null) {
3421                final PackageSetting ps = (PackageSetting) p.mExtras;
3422                if (ps != null) {
3423                    final PackageUserState state = ps.readUserState(userId);
3424                    if (state != null) {
3425                        return PackageParser.isAvailable(state);
3426                    }
3427                }
3428            }
3429        }
3430        return false;
3431    }
3432
3433    @Override
3434    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3435        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3436                flags, userId);
3437    }
3438
3439    @Override
3440    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3441            int flags, int userId) {
3442        return getPackageInfoInternal(versionedPackage.getPackageName(),
3443                // TODO: We will change version code to long, so in the new API it is long
3444                (int) versionedPackage.getVersionCode(), flags, userId);
3445    }
3446
3447    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3448            int flags, int userId) {
3449        if (!sUserManager.exists(userId)) return null;
3450        flags = updateFlagsForPackage(flags, userId, packageName);
3451        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3452                false /* requireFullPermission */, false /* checkShell */, "get package info");
3453
3454        // reader
3455        synchronized (mPackages) {
3456            // Normalize package name to handle renamed packages and static libs
3457            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3458
3459            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3460            if (matchFactoryOnly) {
3461                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3462                if (ps != null) {
3463                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3464                        return null;
3465                    }
3466                    return generatePackageInfo(ps, flags, userId);
3467                }
3468            }
3469
3470            PackageParser.Package p = mPackages.get(packageName);
3471            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3472                return null;
3473            }
3474            if (DEBUG_PACKAGE_INFO)
3475                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3476            if (p != null) {
3477                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3478                        Binder.getCallingUid(), userId)) {
3479                    return null;
3480                }
3481                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3482            }
3483            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3484                final PackageSetting ps = mSettings.mPackages.get(packageName);
3485                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3486                    return null;
3487                }
3488                return generatePackageInfo(ps, flags, userId);
3489            }
3490        }
3491        return null;
3492    }
3493
3494
3495    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3496        // System/shell/root get to see all static libs
3497        final int appId = UserHandle.getAppId(uid);
3498        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3499                || appId == Process.ROOT_UID) {
3500            return false;
3501        }
3502
3503        // No package means no static lib as it is always on internal storage
3504        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3505            return false;
3506        }
3507
3508        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3509                ps.pkg.staticSharedLibVersion);
3510        if (libEntry == null) {
3511            return false;
3512        }
3513
3514        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3515        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3516        if (uidPackageNames == null) {
3517            return true;
3518        }
3519
3520        for (String uidPackageName : uidPackageNames) {
3521            if (ps.name.equals(uidPackageName)) {
3522                return false;
3523            }
3524            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3525            if (uidPs != null) {
3526                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3527                        libEntry.info.getName());
3528                if (index < 0) {
3529                    continue;
3530                }
3531                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3532                    return false;
3533                }
3534            }
3535        }
3536        return true;
3537    }
3538
3539    @Override
3540    public String[] currentToCanonicalPackageNames(String[] names) {
3541        String[] out = new String[names.length];
3542        // reader
3543        synchronized (mPackages) {
3544            for (int i=names.length-1; i>=0; i--) {
3545                PackageSetting ps = mSettings.mPackages.get(names[i]);
3546                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3547            }
3548        }
3549        return out;
3550    }
3551
3552    @Override
3553    public String[] canonicalToCurrentPackageNames(String[] names) {
3554        String[] out = new String[names.length];
3555        // reader
3556        synchronized (mPackages) {
3557            for (int i=names.length-1; i>=0; i--) {
3558                String cur = mSettings.getRenamedPackageLPr(names[i]);
3559                out[i] = cur != null ? cur : names[i];
3560            }
3561        }
3562        return out;
3563    }
3564
3565    @Override
3566    public int getPackageUid(String packageName, int flags, int userId) {
3567        if (!sUserManager.exists(userId)) return -1;
3568        flags = updateFlagsForPackage(flags, userId, packageName);
3569        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3570                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3571
3572        // reader
3573        synchronized (mPackages) {
3574            final PackageParser.Package p = mPackages.get(packageName);
3575            if (p != null && p.isMatch(flags)) {
3576                return UserHandle.getUid(userId, p.applicationInfo.uid);
3577            }
3578            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3579                final PackageSetting ps = mSettings.mPackages.get(packageName);
3580                if (ps != null && ps.isMatch(flags)) {
3581                    return UserHandle.getUid(userId, ps.appId);
3582                }
3583            }
3584        }
3585
3586        return -1;
3587    }
3588
3589    @Override
3590    public int[] getPackageGids(String packageName, int flags, int userId) {
3591        if (!sUserManager.exists(userId)) return null;
3592        flags = updateFlagsForPackage(flags, userId, packageName);
3593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3594                false /* requireFullPermission */, false /* checkShell */,
3595                "getPackageGids");
3596
3597        // reader
3598        synchronized (mPackages) {
3599            final PackageParser.Package p = mPackages.get(packageName);
3600            if (p != null && p.isMatch(flags)) {
3601                PackageSetting ps = (PackageSetting) p.mExtras;
3602                // TODO: Shouldn't this be checking for package installed state for userId and
3603                // return null?
3604                return ps.getPermissionsState().computeGids(userId);
3605            }
3606            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3607                final PackageSetting ps = mSettings.mPackages.get(packageName);
3608                if (ps != null && ps.isMatch(flags)) {
3609                    return ps.getPermissionsState().computeGids(userId);
3610                }
3611            }
3612        }
3613
3614        return null;
3615    }
3616
3617    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3618        if (bp.perm != null) {
3619            return PackageParser.generatePermissionInfo(bp.perm, flags);
3620        }
3621        PermissionInfo pi = new PermissionInfo();
3622        pi.name = bp.name;
3623        pi.packageName = bp.sourcePackage;
3624        pi.nonLocalizedLabel = bp.name;
3625        pi.protectionLevel = bp.protectionLevel;
3626        return pi;
3627    }
3628
3629    @Override
3630    public PermissionInfo getPermissionInfo(String name, int flags) {
3631        // reader
3632        synchronized (mPackages) {
3633            final BasePermission p = mSettings.mPermissions.get(name);
3634            if (p != null) {
3635                return generatePermissionInfo(p, flags);
3636            }
3637            return null;
3638        }
3639    }
3640
3641    @Override
3642    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3643            int flags) {
3644        // reader
3645        synchronized (mPackages) {
3646            if (group != null && !mPermissionGroups.containsKey(group)) {
3647                // This is thrown as NameNotFoundException
3648                return null;
3649            }
3650
3651            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3652            for (BasePermission p : mSettings.mPermissions.values()) {
3653                if (group == null) {
3654                    if (p.perm == null || p.perm.info.group == null) {
3655                        out.add(generatePermissionInfo(p, flags));
3656                    }
3657                } else {
3658                    if (p.perm != null && group.equals(p.perm.info.group)) {
3659                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3660                    }
3661                }
3662            }
3663            return new ParceledListSlice<>(out);
3664        }
3665    }
3666
3667    @Override
3668    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3669        // reader
3670        synchronized (mPackages) {
3671            return PackageParser.generatePermissionGroupInfo(
3672                    mPermissionGroups.get(name), flags);
3673        }
3674    }
3675
3676    @Override
3677    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3678        // reader
3679        synchronized (mPackages) {
3680            final int N = mPermissionGroups.size();
3681            ArrayList<PermissionGroupInfo> out
3682                    = new ArrayList<PermissionGroupInfo>(N);
3683            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3684                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3685            }
3686            return new ParceledListSlice<>(out);
3687        }
3688    }
3689
3690    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3691            int uid, int userId) {
3692        if (!sUserManager.exists(userId)) return null;
3693        PackageSetting ps = mSettings.mPackages.get(packageName);
3694        if (ps != null) {
3695            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3696                return null;
3697            }
3698            if (ps.pkg == null) {
3699                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3700                if (pInfo != null) {
3701                    return pInfo.applicationInfo;
3702                }
3703                return null;
3704            }
3705            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3706                    ps.readUserState(userId), userId);
3707            if (ai != null) {
3708                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3709            }
3710            return ai;
3711        }
3712        return null;
3713    }
3714
3715    @Override
3716    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3717        if (!sUserManager.exists(userId)) return null;
3718        flags = updateFlagsForApplication(flags, userId, packageName);
3719        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3720                false /* requireFullPermission */, false /* checkShell */, "get application info");
3721
3722        // writer
3723        synchronized (mPackages) {
3724            // Normalize package name to handle renamed packages and static libs
3725            packageName = resolveInternalPackageNameLPr(packageName,
3726                    PackageManager.VERSION_CODE_HIGHEST);
3727
3728            PackageParser.Package p = mPackages.get(packageName);
3729            if (DEBUG_PACKAGE_INFO) Log.v(
3730                    TAG, "getApplicationInfo " + packageName
3731                    + ": " + p);
3732            if (p != null) {
3733                PackageSetting ps = mSettings.mPackages.get(packageName);
3734                if (ps == null) return null;
3735                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3736                    return null;
3737                }
3738                // Note: isEnabledLP() does not apply here - always return info
3739                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3740                        p, flags, ps.readUserState(userId), userId);
3741                if (ai != null) {
3742                    ai.packageName = resolveExternalPackageNameLPr(p);
3743                }
3744                return ai;
3745            }
3746            if ("android".equals(packageName)||"system".equals(packageName)) {
3747                return mAndroidApplication;
3748            }
3749            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3750                // Already generates the external package name
3751                return generateApplicationInfoFromSettingsLPw(packageName,
3752                        Binder.getCallingUid(), flags, userId);
3753            }
3754        }
3755        return null;
3756    }
3757
3758    private String normalizePackageNameLPr(String packageName) {
3759        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3760        return normalizedPackageName != null ? normalizedPackageName : packageName;
3761    }
3762
3763    @Override
3764    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3765            final IPackageDataObserver observer) {
3766        mContext.enforceCallingOrSelfPermission(
3767                android.Manifest.permission.CLEAR_APP_CACHE, null);
3768        // Queue up an async operation since clearing cache may take a little while.
3769        mHandler.post(new Runnable() {
3770            public void run() {
3771                mHandler.removeCallbacks(this);
3772                boolean success = true;
3773                synchronized (mInstallLock) {
3774                    try {
3775                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3776                    } catch (InstallerException e) {
3777                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3778                        success = false;
3779                    }
3780                }
3781                if (observer != null) {
3782                    try {
3783                        observer.onRemoveCompleted(null, success);
3784                    } catch (RemoteException e) {
3785                        Slog.w(TAG, "RemoveException when invoking call back");
3786                    }
3787                }
3788            }
3789        });
3790    }
3791
3792    @Override
3793    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3794            final IntentSender pi) {
3795        mContext.enforceCallingOrSelfPermission(
3796                android.Manifest.permission.CLEAR_APP_CACHE, null);
3797        // Queue up an async operation since clearing cache may take a little while.
3798        mHandler.post(new Runnable() {
3799            public void run() {
3800                mHandler.removeCallbacks(this);
3801                boolean success = true;
3802                synchronized (mInstallLock) {
3803                    try {
3804                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3805                    } catch (InstallerException e) {
3806                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3807                        success = false;
3808                    }
3809                }
3810                if(pi != null) {
3811                    try {
3812                        // Callback via pending intent
3813                        int code = success ? 1 : 0;
3814                        pi.sendIntent(null, code, null,
3815                                null, null);
3816                    } catch (SendIntentException e1) {
3817                        Slog.i(TAG, "Failed to send pending intent");
3818                    }
3819                }
3820            }
3821        });
3822    }
3823
3824    public void freeStorage(String volumeUuid, long freeStorageSize, int storageFlags)
3825            throws IOException {
3826        synchronized (mInstallLock) {
3827            try {
3828                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3829            } catch (InstallerException e) {
3830                throw new IOException("Failed to free enough space", e);
3831            }
3832        }
3833    }
3834
3835    /**
3836     * Update given flags based on encryption status of current user.
3837     */
3838    private int updateFlags(int flags, int userId) {
3839        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3840                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3841            // Caller expressed an explicit opinion about what encryption
3842            // aware/unaware components they want to see, so fall through and
3843            // give them what they want
3844        } else {
3845            // Caller expressed no opinion, so match based on user state
3846            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3847                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3848            } else {
3849                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3850            }
3851        }
3852        return flags;
3853    }
3854
3855    private UserManagerInternal getUserManagerInternal() {
3856        if (mUserManagerInternal == null) {
3857            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3858        }
3859        return mUserManagerInternal;
3860    }
3861
3862    private DeviceIdleController.LocalService getDeviceIdleController() {
3863        if (mDeviceIdleController == null) {
3864            mDeviceIdleController =
3865                    LocalServices.getService(DeviceIdleController.LocalService.class);
3866        }
3867        return mDeviceIdleController;
3868    }
3869
3870    /**
3871     * Update given flags when being used to request {@link PackageInfo}.
3872     */
3873    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3874        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3875        boolean triaged = true;
3876        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3877                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3878            // Caller is asking for component details, so they'd better be
3879            // asking for specific encryption matching behavior, or be triaged
3880            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3881                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3882                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3883                triaged = false;
3884            }
3885        }
3886        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3887                | PackageManager.MATCH_SYSTEM_ONLY
3888                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3889            triaged = false;
3890        }
3891        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3892            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3893                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3894                    + Debug.getCallers(5));
3895        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3896                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3897            // If the caller wants all packages and has a restricted profile associated with it,
3898            // then match all users. This is to make sure that launchers that need to access work
3899            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3900            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3901            flags |= PackageManager.MATCH_ANY_USER;
3902        }
3903        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3904            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3905                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3906        }
3907        return updateFlags(flags, userId);
3908    }
3909
3910    /**
3911     * Update given flags when being used to request {@link ApplicationInfo}.
3912     */
3913    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3914        return updateFlagsForPackage(flags, userId, cookie);
3915    }
3916
3917    /**
3918     * Update given flags when being used to request {@link ComponentInfo}.
3919     */
3920    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3921        if (cookie instanceof Intent) {
3922            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3923                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3924            }
3925        }
3926
3927        boolean triaged = true;
3928        // Caller is asking for component details, so they'd better be
3929        // asking for specific encryption matching behavior, or be triaged
3930        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3931                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3932                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3933            triaged = false;
3934        }
3935        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3936            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3937                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3938        }
3939
3940        return updateFlags(flags, userId);
3941    }
3942
3943    /**
3944     * Update given intent when being used to request {@link ResolveInfo}.
3945     */
3946    private Intent updateIntentForResolve(Intent intent) {
3947        if (intent.getSelector() != null) {
3948            intent = intent.getSelector();
3949        }
3950        if (DEBUG_PREFERRED) {
3951            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3952        }
3953        return intent;
3954    }
3955
3956    /**
3957     * Update given flags when being used to request {@link ResolveInfo}.
3958     */
3959    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3960        // Safe mode means we shouldn't match any third-party components
3961        if (mSafeMode) {
3962            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3963        }
3964        final int callingUid = Binder.getCallingUid();
3965        if (getInstantAppPackageName(callingUid) != null) {
3966            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3967            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
3968            flags |= PackageManager.MATCH_INSTANT;
3969        } else {
3970            // Otherwise, prevent leaking ephemeral components
3971            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
3972            if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3973                // Unless called from the system process
3974                flags &= ~PackageManager.MATCH_INSTANT;
3975            }
3976        }
3977        return updateFlagsForComponent(flags, userId, cookie);
3978    }
3979
3980    @Override
3981    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3982        if (!sUserManager.exists(userId)) return null;
3983        flags = updateFlagsForComponent(flags, userId, component);
3984        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3985                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3986        synchronized (mPackages) {
3987            PackageParser.Activity a = mActivities.mActivities.get(component);
3988
3989            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3990            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3991                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3992                if (ps == null) return null;
3993                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3994                        userId);
3995            }
3996            if (mResolveComponentName.equals(component)) {
3997                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3998                        new PackageUserState(), userId);
3999            }
4000        }
4001        return null;
4002    }
4003
4004    @Override
4005    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4006            String resolvedType) {
4007        synchronized (mPackages) {
4008            if (component.equals(mResolveComponentName)) {
4009                // The resolver supports EVERYTHING!
4010                return true;
4011            }
4012            PackageParser.Activity a = mActivities.mActivities.get(component);
4013            if (a == null) {
4014                return false;
4015            }
4016            for (int i=0; i<a.intents.size(); i++) {
4017                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4018                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4019                    return true;
4020                }
4021            }
4022            return false;
4023        }
4024    }
4025
4026    @Override
4027    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4028        if (!sUserManager.exists(userId)) return null;
4029        flags = updateFlagsForComponent(flags, userId, component);
4030        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4031                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4032        synchronized (mPackages) {
4033            PackageParser.Activity a = mReceivers.mActivities.get(component);
4034            if (DEBUG_PACKAGE_INFO) Log.v(
4035                TAG, "getReceiverInfo " + component + ": " + a);
4036            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4037                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4038                if (ps == null) return null;
4039                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4040                        userId);
4041            }
4042        }
4043        return null;
4044    }
4045
4046    @Override
4047    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4048        if (!sUserManager.exists(userId)) return null;
4049        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4050
4051        flags = updateFlagsForPackage(flags, userId, null);
4052
4053        final boolean canSeeStaticLibraries =
4054                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4055                        == PERMISSION_GRANTED
4056                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4057                        == PERMISSION_GRANTED
4058                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4059                        == PERMISSION_GRANTED
4060                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4061                        == PERMISSION_GRANTED;
4062
4063        synchronized (mPackages) {
4064            List<SharedLibraryInfo> result = null;
4065
4066            final int libCount = mSharedLibraries.size();
4067            for (int i = 0; i < libCount; i++) {
4068                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4069                if (versionedLib == null) {
4070                    continue;
4071                }
4072
4073                final int versionCount = versionedLib.size();
4074                for (int j = 0; j < versionCount; j++) {
4075                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4076                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4077                        break;
4078                    }
4079                    final long identity = Binder.clearCallingIdentity();
4080                    try {
4081                        // TODO: We will change version code to long, so in the new API it is long
4082                        PackageInfo packageInfo = getPackageInfoVersioned(
4083                                libInfo.getDeclaringPackage(), flags, userId);
4084                        if (packageInfo == null) {
4085                            continue;
4086                        }
4087                    } finally {
4088                        Binder.restoreCallingIdentity(identity);
4089                    }
4090
4091                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4092                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4093                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4094
4095                    if (result == null) {
4096                        result = new ArrayList<>();
4097                    }
4098                    result.add(resLibInfo);
4099                }
4100            }
4101
4102            return result != null ? new ParceledListSlice<>(result) : null;
4103        }
4104    }
4105
4106    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4107            SharedLibraryInfo libInfo, int flags, int userId) {
4108        List<VersionedPackage> versionedPackages = null;
4109        final int packageCount = mSettings.mPackages.size();
4110        for (int i = 0; i < packageCount; i++) {
4111            PackageSetting ps = mSettings.mPackages.valueAt(i);
4112
4113            if (ps == null) {
4114                continue;
4115            }
4116
4117            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4118                continue;
4119            }
4120
4121            final String libName = libInfo.getName();
4122            if (libInfo.isStatic()) {
4123                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4124                if (libIdx < 0) {
4125                    continue;
4126                }
4127                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4128                    continue;
4129                }
4130                if (versionedPackages == null) {
4131                    versionedPackages = new ArrayList<>();
4132                }
4133                // If the dependent is a static shared lib, use the public package name
4134                String dependentPackageName = ps.name;
4135                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4136                    dependentPackageName = ps.pkg.manifestPackageName;
4137                }
4138                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4139            } else if (ps.pkg != null) {
4140                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4141                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4142                    if (versionedPackages == null) {
4143                        versionedPackages = new ArrayList<>();
4144                    }
4145                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4146                }
4147            }
4148        }
4149
4150        return versionedPackages;
4151    }
4152
4153    @Override
4154    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4155        if (!sUserManager.exists(userId)) return null;
4156        flags = updateFlagsForComponent(flags, userId, component);
4157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4158                false /* requireFullPermission */, false /* checkShell */, "get service info");
4159        synchronized (mPackages) {
4160            PackageParser.Service s = mServices.mServices.get(component);
4161            if (DEBUG_PACKAGE_INFO) Log.v(
4162                TAG, "getServiceInfo " + component + ": " + s);
4163            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4164                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4165                if (ps == null) return null;
4166                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4167                        userId);
4168            }
4169        }
4170        return null;
4171    }
4172
4173    @Override
4174    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4175        if (!sUserManager.exists(userId)) return null;
4176        flags = updateFlagsForComponent(flags, userId, component);
4177        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4178                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4179        synchronized (mPackages) {
4180            PackageParser.Provider p = mProviders.mProviders.get(component);
4181            if (DEBUG_PACKAGE_INFO) Log.v(
4182                TAG, "getProviderInfo " + component + ": " + p);
4183            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4184                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4185                if (ps == null) return null;
4186                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4187                        userId);
4188            }
4189        }
4190        return null;
4191    }
4192
4193    @Override
4194    public String[] getSystemSharedLibraryNames() {
4195        synchronized (mPackages) {
4196            Set<String> libs = null;
4197            final int libCount = mSharedLibraries.size();
4198            for (int i = 0; i < libCount; i++) {
4199                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4200                if (versionedLib == null) {
4201                    continue;
4202                }
4203                final int versionCount = versionedLib.size();
4204                for (int j = 0; j < versionCount; j++) {
4205                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4206                    if (!libEntry.info.isStatic()) {
4207                        if (libs == null) {
4208                            libs = new ArraySet<>();
4209                        }
4210                        libs.add(libEntry.info.getName());
4211                        break;
4212                    }
4213                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4214                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4215                            UserHandle.getUserId(Binder.getCallingUid()))) {
4216                        if (libs == null) {
4217                            libs = new ArraySet<>();
4218                        }
4219                        libs.add(libEntry.info.getName());
4220                        break;
4221                    }
4222                }
4223            }
4224
4225            if (libs != null) {
4226                String[] libsArray = new String[libs.size()];
4227                libs.toArray(libsArray);
4228                return libsArray;
4229            }
4230
4231            return null;
4232        }
4233    }
4234
4235    @Override
4236    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4237        synchronized (mPackages) {
4238            return mServicesSystemSharedLibraryPackageName;
4239        }
4240    }
4241
4242    @Override
4243    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4244        synchronized (mPackages) {
4245            return mSharedSystemSharedLibraryPackageName;
4246        }
4247    }
4248
4249    private void updateSequenceNumberLP(String packageName, int[] userList) {
4250        for (int i = userList.length - 1; i >= 0; --i) {
4251            final int userId = userList[i];
4252            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4253            if (changedPackages == null) {
4254                changedPackages = new SparseArray<>();
4255                mChangedPackages.put(userId, changedPackages);
4256            }
4257            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4258            if (sequenceNumbers == null) {
4259                sequenceNumbers = new HashMap<>();
4260                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4261            }
4262            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4263            if (sequenceNumber != null) {
4264                changedPackages.remove(sequenceNumber);
4265            }
4266            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4267            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4268        }
4269        mChangedPackagesSequenceNumber++;
4270    }
4271
4272    @Override
4273    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4274        synchronized (mPackages) {
4275            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4276                return null;
4277            }
4278            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4279            if (changedPackages == null) {
4280                return null;
4281            }
4282            final List<String> packageNames =
4283                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4284            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4285                final String packageName = changedPackages.get(i);
4286                if (packageName != null) {
4287                    packageNames.add(packageName);
4288                }
4289            }
4290            return packageNames.isEmpty()
4291                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4292        }
4293    }
4294
4295    @Override
4296    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4297        ArrayList<FeatureInfo> res;
4298        synchronized (mAvailableFeatures) {
4299            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4300            res.addAll(mAvailableFeatures.values());
4301        }
4302        final FeatureInfo fi = new FeatureInfo();
4303        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4304                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4305        res.add(fi);
4306
4307        return new ParceledListSlice<>(res);
4308    }
4309
4310    @Override
4311    public boolean hasSystemFeature(String name, int version) {
4312        synchronized (mAvailableFeatures) {
4313            final FeatureInfo feat = mAvailableFeatures.get(name);
4314            if (feat == null) {
4315                return false;
4316            } else {
4317                return feat.version >= version;
4318            }
4319        }
4320    }
4321
4322    @Override
4323    public int checkPermission(String permName, String pkgName, int userId) {
4324        if (!sUserManager.exists(userId)) {
4325            return PackageManager.PERMISSION_DENIED;
4326        }
4327
4328        synchronized (mPackages) {
4329            final PackageParser.Package p = mPackages.get(pkgName);
4330            if (p != null && p.mExtras != null) {
4331                final PackageSetting ps = (PackageSetting) p.mExtras;
4332                final PermissionsState permissionsState = ps.getPermissionsState();
4333                if (permissionsState.hasPermission(permName, userId)) {
4334                    return PackageManager.PERMISSION_GRANTED;
4335                }
4336                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4337                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4338                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4339                    return PackageManager.PERMISSION_GRANTED;
4340                }
4341            }
4342        }
4343
4344        return PackageManager.PERMISSION_DENIED;
4345    }
4346
4347    @Override
4348    public int checkUidPermission(String permName, int uid) {
4349        final int userId = UserHandle.getUserId(uid);
4350
4351        if (!sUserManager.exists(userId)) {
4352            return PackageManager.PERMISSION_DENIED;
4353        }
4354
4355        synchronized (mPackages) {
4356            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4357            if (obj != null) {
4358                final SettingBase ps = (SettingBase) obj;
4359                final PermissionsState permissionsState = ps.getPermissionsState();
4360                if (permissionsState.hasPermission(permName, userId)) {
4361                    return PackageManager.PERMISSION_GRANTED;
4362                }
4363                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4364                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4365                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4366                    return PackageManager.PERMISSION_GRANTED;
4367                }
4368            } else {
4369                ArraySet<String> perms = mSystemPermissions.get(uid);
4370                if (perms != null) {
4371                    if (perms.contains(permName)) {
4372                        return PackageManager.PERMISSION_GRANTED;
4373                    }
4374                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4375                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4376                        return PackageManager.PERMISSION_GRANTED;
4377                    }
4378                }
4379            }
4380        }
4381
4382        return PackageManager.PERMISSION_DENIED;
4383    }
4384
4385    @Override
4386    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4387        if (UserHandle.getCallingUserId() != userId) {
4388            mContext.enforceCallingPermission(
4389                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4390                    "isPermissionRevokedByPolicy for user " + userId);
4391        }
4392
4393        if (checkPermission(permission, packageName, userId)
4394                == PackageManager.PERMISSION_GRANTED) {
4395            return false;
4396        }
4397
4398        final long identity = Binder.clearCallingIdentity();
4399        try {
4400            final int flags = getPermissionFlags(permission, packageName, userId);
4401            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4402        } finally {
4403            Binder.restoreCallingIdentity(identity);
4404        }
4405    }
4406
4407    @Override
4408    public String getPermissionControllerPackageName() {
4409        synchronized (mPackages) {
4410            return mRequiredInstallerPackage;
4411        }
4412    }
4413
4414    /**
4415     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4416     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4417     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4418     * @param message the message to log on security exception
4419     */
4420    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4421            boolean checkShell, String message) {
4422        if (userId < 0) {
4423            throw new IllegalArgumentException("Invalid userId " + userId);
4424        }
4425        if (checkShell) {
4426            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4427        }
4428        if (userId == UserHandle.getUserId(callingUid)) return;
4429        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4430            if (requireFullPermission) {
4431                mContext.enforceCallingOrSelfPermission(
4432                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4433            } else {
4434                try {
4435                    mContext.enforceCallingOrSelfPermission(
4436                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4437                } catch (SecurityException se) {
4438                    mContext.enforceCallingOrSelfPermission(
4439                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4440                }
4441            }
4442        }
4443    }
4444
4445    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4446        if (callingUid == Process.SHELL_UID) {
4447            if (userHandle >= 0
4448                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4449                throw new SecurityException("Shell does not have permission to access user "
4450                        + userHandle);
4451            } else if (userHandle < 0) {
4452                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4453                        + Debug.getCallers(3));
4454            }
4455        }
4456    }
4457
4458    private BasePermission findPermissionTreeLP(String permName) {
4459        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4460            if (permName.startsWith(bp.name) &&
4461                    permName.length() > bp.name.length() &&
4462                    permName.charAt(bp.name.length()) == '.') {
4463                return bp;
4464            }
4465        }
4466        return null;
4467    }
4468
4469    private BasePermission checkPermissionTreeLP(String permName) {
4470        if (permName != null) {
4471            BasePermission bp = findPermissionTreeLP(permName);
4472            if (bp != null) {
4473                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4474                    return bp;
4475                }
4476                throw new SecurityException("Calling uid "
4477                        + Binder.getCallingUid()
4478                        + " is not allowed to add to permission tree "
4479                        + bp.name + " owned by uid " + bp.uid);
4480            }
4481        }
4482        throw new SecurityException("No permission tree found for " + permName);
4483    }
4484
4485    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4486        if (s1 == null) {
4487            return s2 == null;
4488        }
4489        if (s2 == null) {
4490            return false;
4491        }
4492        if (s1.getClass() != s2.getClass()) {
4493            return false;
4494        }
4495        return s1.equals(s2);
4496    }
4497
4498    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4499        if (pi1.icon != pi2.icon) return false;
4500        if (pi1.logo != pi2.logo) return false;
4501        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4502        if (!compareStrings(pi1.name, pi2.name)) return false;
4503        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4504        // We'll take care of setting this one.
4505        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4506        // These are not currently stored in settings.
4507        //if (!compareStrings(pi1.group, pi2.group)) return false;
4508        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4509        //if (pi1.labelRes != pi2.labelRes) return false;
4510        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4511        return true;
4512    }
4513
4514    int permissionInfoFootprint(PermissionInfo info) {
4515        int size = info.name.length();
4516        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4517        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4518        return size;
4519    }
4520
4521    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4522        int size = 0;
4523        for (BasePermission perm : mSettings.mPermissions.values()) {
4524            if (perm.uid == tree.uid) {
4525                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4526            }
4527        }
4528        return size;
4529    }
4530
4531    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4532        // We calculate the max size of permissions defined by this uid and throw
4533        // if that plus the size of 'info' would exceed our stated maximum.
4534        if (tree.uid != Process.SYSTEM_UID) {
4535            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4536            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4537                throw new SecurityException("Permission tree size cap exceeded");
4538            }
4539        }
4540    }
4541
4542    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4543        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4544            throw new SecurityException("Label must be specified in permission");
4545        }
4546        BasePermission tree = checkPermissionTreeLP(info.name);
4547        BasePermission bp = mSettings.mPermissions.get(info.name);
4548        boolean added = bp == null;
4549        boolean changed = true;
4550        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4551        if (added) {
4552            enforcePermissionCapLocked(info, tree);
4553            bp = new BasePermission(info.name, tree.sourcePackage,
4554                    BasePermission.TYPE_DYNAMIC);
4555        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4556            throw new SecurityException(
4557                    "Not allowed to modify non-dynamic permission "
4558                    + info.name);
4559        } else {
4560            if (bp.protectionLevel == fixedLevel
4561                    && bp.perm.owner.equals(tree.perm.owner)
4562                    && bp.uid == tree.uid
4563                    && comparePermissionInfos(bp.perm.info, info)) {
4564                changed = false;
4565            }
4566        }
4567        bp.protectionLevel = fixedLevel;
4568        info = new PermissionInfo(info);
4569        info.protectionLevel = fixedLevel;
4570        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4571        bp.perm.info.packageName = tree.perm.info.packageName;
4572        bp.uid = tree.uid;
4573        if (added) {
4574            mSettings.mPermissions.put(info.name, bp);
4575        }
4576        if (changed) {
4577            if (!async) {
4578                mSettings.writeLPr();
4579            } else {
4580                scheduleWriteSettingsLocked();
4581            }
4582        }
4583        return added;
4584    }
4585
4586    @Override
4587    public boolean addPermission(PermissionInfo info) {
4588        synchronized (mPackages) {
4589            return addPermissionLocked(info, false);
4590        }
4591    }
4592
4593    @Override
4594    public boolean addPermissionAsync(PermissionInfo info) {
4595        synchronized (mPackages) {
4596            return addPermissionLocked(info, true);
4597        }
4598    }
4599
4600    @Override
4601    public void removePermission(String name) {
4602        synchronized (mPackages) {
4603            checkPermissionTreeLP(name);
4604            BasePermission bp = mSettings.mPermissions.get(name);
4605            if (bp != null) {
4606                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4607                    throw new SecurityException(
4608                            "Not allowed to modify non-dynamic permission "
4609                            + name);
4610                }
4611                mSettings.mPermissions.remove(name);
4612                mSettings.writeLPr();
4613            }
4614        }
4615    }
4616
4617    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4618            BasePermission bp) {
4619        int index = pkg.requestedPermissions.indexOf(bp.name);
4620        if (index == -1) {
4621            throw new SecurityException("Package " + pkg.packageName
4622                    + " has not requested permission " + bp.name);
4623        }
4624        if (!bp.isRuntime() && !bp.isDevelopment()) {
4625            throw new SecurityException("Permission " + bp.name
4626                    + " is not a changeable permission type");
4627        }
4628    }
4629
4630    @Override
4631    public void grantRuntimePermission(String packageName, String name, final int userId) {
4632        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4633    }
4634
4635    private void grantRuntimePermission(String packageName, String name, final int userId,
4636            boolean overridePolicy) {
4637        if (!sUserManager.exists(userId)) {
4638            Log.e(TAG, "No such user:" + userId);
4639            return;
4640        }
4641
4642        mContext.enforceCallingOrSelfPermission(
4643                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4644                "grantRuntimePermission");
4645
4646        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4647                true /* requireFullPermission */, true /* checkShell */,
4648                "grantRuntimePermission");
4649
4650        final int uid;
4651        final SettingBase sb;
4652
4653        synchronized (mPackages) {
4654            final PackageParser.Package pkg = mPackages.get(packageName);
4655            if (pkg == null) {
4656                throw new IllegalArgumentException("Unknown package: " + packageName);
4657            }
4658
4659            final BasePermission bp = mSettings.mPermissions.get(name);
4660            if (bp == null) {
4661                throw new IllegalArgumentException("Unknown permission: " + name);
4662            }
4663
4664            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4665
4666            // If a permission review is required for legacy apps we represent
4667            // their permissions as always granted runtime ones since we need
4668            // to keep the review required permission flag per user while an
4669            // install permission's state is shared across all users.
4670            if (mPermissionReviewRequired
4671                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4672                    && bp.isRuntime()) {
4673                return;
4674            }
4675
4676            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4677            sb = (SettingBase) pkg.mExtras;
4678            if (sb == null) {
4679                throw new IllegalArgumentException("Unknown package: " + packageName);
4680            }
4681
4682            final PermissionsState permissionsState = sb.getPermissionsState();
4683
4684            final int flags = permissionsState.getPermissionFlags(name, userId);
4685            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4686                throw new SecurityException("Cannot grant system fixed permission "
4687                        + name + " for package " + packageName);
4688            }
4689            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4690                throw new SecurityException("Cannot grant policy fixed permission "
4691                        + name + " for package " + packageName);
4692            }
4693
4694            if (bp.isDevelopment()) {
4695                // Development permissions must be handled specially, since they are not
4696                // normal runtime permissions.  For now they apply to all users.
4697                if (permissionsState.grantInstallPermission(bp) !=
4698                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4699                    scheduleWriteSettingsLocked();
4700                }
4701                return;
4702            }
4703
4704            final PackageSetting ps = mSettings.mPackages.get(packageName);
4705            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4706                throw new SecurityException("Cannot grant non-ephemeral permission"
4707                        + name + " for package " + packageName);
4708            }
4709
4710            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4711                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4712                return;
4713            }
4714
4715            final int result = permissionsState.grantRuntimePermission(bp, userId);
4716            switch (result) {
4717                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4718                    return;
4719                }
4720
4721                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4722                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4723                    mHandler.post(new Runnable() {
4724                        @Override
4725                        public void run() {
4726                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4727                        }
4728                    });
4729                }
4730                break;
4731            }
4732
4733            if (bp.isRuntime()) {
4734                logPermissionGranted(mContext, name, packageName);
4735            }
4736
4737            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4738
4739            // Not critical if that is lost - app has to request again.
4740            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4741        }
4742
4743        // Only need to do this if user is initialized. Otherwise it's a new user
4744        // and there are no processes running as the user yet and there's no need
4745        // to make an expensive call to remount processes for the changed permissions.
4746        if (READ_EXTERNAL_STORAGE.equals(name)
4747                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4748            final long token = Binder.clearCallingIdentity();
4749            try {
4750                if (sUserManager.isInitialized(userId)) {
4751                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4752                            StorageManagerInternal.class);
4753                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4754                }
4755            } finally {
4756                Binder.restoreCallingIdentity(token);
4757            }
4758        }
4759    }
4760
4761    @Override
4762    public void revokeRuntimePermission(String packageName, String name, int userId) {
4763        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4764    }
4765
4766    private void revokeRuntimePermission(String packageName, String name, int userId,
4767            boolean overridePolicy) {
4768        if (!sUserManager.exists(userId)) {
4769            Log.e(TAG, "No such user:" + userId);
4770            return;
4771        }
4772
4773        mContext.enforceCallingOrSelfPermission(
4774                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4775                "revokeRuntimePermission");
4776
4777        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4778                true /* requireFullPermission */, true /* checkShell */,
4779                "revokeRuntimePermission");
4780
4781        final int appId;
4782
4783        synchronized (mPackages) {
4784            final PackageParser.Package pkg = mPackages.get(packageName);
4785            if (pkg == null) {
4786                throw new IllegalArgumentException("Unknown package: " + packageName);
4787            }
4788
4789            final BasePermission bp = mSettings.mPermissions.get(name);
4790            if (bp == null) {
4791                throw new IllegalArgumentException("Unknown permission: " + name);
4792            }
4793
4794            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4795
4796            // If a permission review is required for legacy apps we represent
4797            // their permissions as always granted runtime ones since we need
4798            // to keep the review required permission flag per user while an
4799            // install permission's state is shared across all users.
4800            if (mPermissionReviewRequired
4801                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4802                    && bp.isRuntime()) {
4803                return;
4804            }
4805
4806            SettingBase sb = (SettingBase) pkg.mExtras;
4807            if (sb == null) {
4808                throw new IllegalArgumentException("Unknown package: " + packageName);
4809            }
4810
4811            final PermissionsState permissionsState = sb.getPermissionsState();
4812
4813            final int flags = permissionsState.getPermissionFlags(name, userId);
4814            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4815                throw new SecurityException("Cannot revoke system fixed permission "
4816                        + name + " for package " + packageName);
4817            }
4818            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4819                throw new SecurityException("Cannot revoke policy fixed permission "
4820                        + name + " for package " + packageName);
4821            }
4822
4823            if (bp.isDevelopment()) {
4824                // Development permissions must be handled specially, since they are not
4825                // normal runtime permissions.  For now they apply to all users.
4826                if (permissionsState.revokeInstallPermission(bp) !=
4827                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4828                    scheduleWriteSettingsLocked();
4829                }
4830                return;
4831            }
4832
4833            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4834                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4835                return;
4836            }
4837
4838            if (bp.isRuntime()) {
4839                logPermissionRevoked(mContext, name, packageName);
4840            }
4841
4842            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4843
4844            // Critical, after this call app should never have the permission.
4845            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4846
4847            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4848        }
4849
4850        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4851    }
4852
4853    /**
4854     * Get the first event id for the permission.
4855     *
4856     * <p>There are four events for each permission: <ul>
4857     *     <li>Request permission: first id + 0</li>
4858     *     <li>Grant permission: first id + 1</li>
4859     *     <li>Request for permission denied: first id + 2</li>
4860     *     <li>Revoke permission: first id + 3</li>
4861     * </ul></p>
4862     *
4863     * @param name name of the permission
4864     *
4865     * @return The first event id for the permission
4866     */
4867    private static int getBaseEventId(@NonNull String name) {
4868        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4869
4870        if (eventIdIndex == -1) {
4871            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4872                    || "user".equals(Build.TYPE)) {
4873                Log.i(TAG, "Unknown permission " + name);
4874
4875                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4876            } else {
4877                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4878                //
4879                // Also update
4880                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4881                // - metrics_constants.proto
4882                throw new IllegalStateException("Unknown permission " + name);
4883            }
4884        }
4885
4886        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4887    }
4888
4889    /**
4890     * Log that a permission was revoked.
4891     *
4892     * @param context Context of the caller
4893     * @param name name of the permission
4894     * @param packageName package permission if for
4895     */
4896    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4897            @NonNull String packageName) {
4898        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4899    }
4900
4901    /**
4902     * Log that a permission request was granted.
4903     *
4904     * @param context Context of the caller
4905     * @param name name of the permission
4906     * @param packageName package permission if for
4907     */
4908    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4909            @NonNull String packageName) {
4910        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4911    }
4912
4913    @Override
4914    public void resetRuntimePermissions() {
4915        mContext.enforceCallingOrSelfPermission(
4916                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4917                "revokeRuntimePermission");
4918
4919        int callingUid = Binder.getCallingUid();
4920        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4921            mContext.enforceCallingOrSelfPermission(
4922                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4923                    "resetRuntimePermissions");
4924        }
4925
4926        synchronized (mPackages) {
4927            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4928            for (int userId : UserManagerService.getInstance().getUserIds()) {
4929                final int packageCount = mPackages.size();
4930                for (int i = 0; i < packageCount; i++) {
4931                    PackageParser.Package pkg = mPackages.valueAt(i);
4932                    if (!(pkg.mExtras instanceof PackageSetting)) {
4933                        continue;
4934                    }
4935                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4936                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4937                }
4938            }
4939        }
4940    }
4941
4942    @Override
4943    public int getPermissionFlags(String name, String packageName, int userId) {
4944        if (!sUserManager.exists(userId)) {
4945            return 0;
4946        }
4947
4948        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4949
4950        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4951                true /* requireFullPermission */, false /* checkShell */,
4952                "getPermissionFlags");
4953
4954        synchronized (mPackages) {
4955            final PackageParser.Package pkg = mPackages.get(packageName);
4956            if (pkg == null) {
4957                return 0;
4958            }
4959
4960            final BasePermission bp = mSettings.mPermissions.get(name);
4961            if (bp == null) {
4962                return 0;
4963            }
4964
4965            SettingBase sb = (SettingBase) pkg.mExtras;
4966            if (sb == null) {
4967                return 0;
4968            }
4969
4970            PermissionsState permissionsState = sb.getPermissionsState();
4971            return permissionsState.getPermissionFlags(name, userId);
4972        }
4973    }
4974
4975    @Override
4976    public void updatePermissionFlags(String name, String packageName, int flagMask,
4977            int flagValues, int userId) {
4978        if (!sUserManager.exists(userId)) {
4979            return;
4980        }
4981
4982        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4983
4984        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4985                true /* requireFullPermission */, true /* checkShell */,
4986                "updatePermissionFlags");
4987
4988        // Only the system can change these flags and nothing else.
4989        if (getCallingUid() != Process.SYSTEM_UID) {
4990            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4991            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4992            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4993            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4994            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4995        }
4996
4997        synchronized (mPackages) {
4998            final PackageParser.Package pkg = mPackages.get(packageName);
4999            if (pkg == null) {
5000                throw new IllegalArgumentException("Unknown package: " + packageName);
5001            }
5002
5003            final BasePermission bp = mSettings.mPermissions.get(name);
5004            if (bp == null) {
5005                throw new IllegalArgumentException("Unknown permission: " + name);
5006            }
5007
5008            SettingBase sb = (SettingBase) pkg.mExtras;
5009            if (sb == null) {
5010                throw new IllegalArgumentException("Unknown package: " + packageName);
5011            }
5012
5013            PermissionsState permissionsState = sb.getPermissionsState();
5014
5015            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5016
5017            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5018                // Install and runtime permissions are stored in different places,
5019                // so figure out what permission changed and persist the change.
5020                if (permissionsState.getInstallPermissionState(name) != null) {
5021                    scheduleWriteSettingsLocked();
5022                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5023                        || hadState) {
5024                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5025                }
5026            }
5027        }
5028    }
5029
5030    /**
5031     * Update the permission flags for all packages and runtime permissions of a user in order
5032     * to allow device or profile owner to remove POLICY_FIXED.
5033     */
5034    @Override
5035    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5036        if (!sUserManager.exists(userId)) {
5037            return;
5038        }
5039
5040        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5041
5042        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5043                true /* requireFullPermission */, true /* checkShell */,
5044                "updatePermissionFlagsForAllApps");
5045
5046        // Only the system can change system fixed flags.
5047        if (getCallingUid() != Process.SYSTEM_UID) {
5048            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5049            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5050        }
5051
5052        synchronized (mPackages) {
5053            boolean changed = false;
5054            final int packageCount = mPackages.size();
5055            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5056                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5057                SettingBase sb = (SettingBase) pkg.mExtras;
5058                if (sb == null) {
5059                    continue;
5060                }
5061                PermissionsState permissionsState = sb.getPermissionsState();
5062                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5063                        userId, flagMask, flagValues);
5064            }
5065            if (changed) {
5066                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5067            }
5068        }
5069    }
5070
5071    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5072        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5073                != PackageManager.PERMISSION_GRANTED
5074            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5075                != PackageManager.PERMISSION_GRANTED) {
5076            throw new SecurityException(message + " requires "
5077                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5078                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5079        }
5080    }
5081
5082    @Override
5083    public boolean shouldShowRequestPermissionRationale(String permissionName,
5084            String packageName, int userId) {
5085        if (UserHandle.getCallingUserId() != userId) {
5086            mContext.enforceCallingPermission(
5087                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5088                    "canShowRequestPermissionRationale for user " + userId);
5089        }
5090
5091        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5092        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5093            return false;
5094        }
5095
5096        if (checkPermission(permissionName, packageName, userId)
5097                == PackageManager.PERMISSION_GRANTED) {
5098            return false;
5099        }
5100
5101        final int flags;
5102
5103        final long identity = Binder.clearCallingIdentity();
5104        try {
5105            flags = getPermissionFlags(permissionName,
5106                    packageName, userId);
5107        } finally {
5108            Binder.restoreCallingIdentity(identity);
5109        }
5110
5111        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5112                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5113                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5114
5115        if ((flags & fixedFlags) != 0) {
5116            return false;
5117        }
5118
5119        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5120    }
5121
5122    @Override
5123    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5124        mContext.enforceCallingOrSelfPermission(
5125                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5126                "addOnPermissionsChangeListener");
5127
5128        synchronized (mPackages) {
5129            mOnPermissionChangeListeners.addListenerLocked(listener);
5130        }
5131    }
5132
5133    @Override
5134    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5135        synchronized (mPackages) {
5136            mOnPermissionChangeListeners.removeListenerLocked(listener);
5137        }
5138    }
5139
5140    @Override
5141    public boolean isProtectedBroadcast(String actionName) {
5142        synchronized (mPackages) {
5143            if (mProtectedBroadcasts.contains(actionName)) {
5144                return true;
5145            } else if (actionName != null) {
5146                // TODO: remove these terrible hacks
5147                if (actionName.startsWith("android.net.netmon.lingerExpired")
5148                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5149                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5150                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5151                    return true;
5152                }
5153            }
5154        }
5155        return false;
5156    }
5157
5158    @Override
5159    public int checkSignatures(String pkg1, String pkg2) {
5160        synchronized (mPackages) {
5161            final PackageParser.Package p1 = mPackages.get(pkg1);
5162            final PackageParser.Package p2 = mPackages.get(pkg2);
5163            if (p1 == null || p1.mExtras == null
5164                    || p2 == null || p2.mExtras == null) {
5165                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5166            }
5167            return compareSignatures(p1.mSignatures, p2.mSignatures);
5168        }
5169    }
5170
5171    @Override
5172    public int checkUidSignatures(int uid1, int uid2) {
5173        // Map to base uids.
5174        uid1 = UserHandle.getAppId(uid1);
5175        uid2 = UserHandle.getAppId(uid2);
5176        // reader
5177        synchronized (mPackages) {
5178            Signature[] s1;
5179            Signature[] s2;
5180            Object obj = mSettings.getUserIdLPr(uid1);
5181            if (obj != null) {
5182                if (obj instanceof SharedUserSetting) {
5183                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5184                } else if (obj instanceof PackageSetting) {
5185                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5186                } else {
5187                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5188                }
5189            } else {
5190                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5191            }
5192            obj = mSettings.getUserIdLPr(uid2);
5193            if (obj != null) {
5194                if (obj instanceof SharedUserSetting) {
5195                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5196                } else if (obj instanceof PackageSetting) {
5197                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5198                } else {
5199                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5200                }
5201            } else {
5202                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5203            }
5204            return compareSignatures(s1, s2);
5205        }
5206    }
5207
5208    /**
5209     * This method should typically only be used when granting or revoking
5210     * permissions, since the app may immediately restart after this call.
5211     * <p>
5212     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5213     * guard your work against the app being relaunched.
5214     */
5215    private void killUid(int appId, int userId, String reason) {
5216        final long identity = Binder.clearCallingIdentity();
5217        try {
5218            IActivityManager am = ActivityManager.getService();
5219            if (am != null) {
5220                try {
5221                    am.killUid(appId, userId, reason);
5222                } catch (RemoteException e) {
5223                    /* ignore - same process */
5224                }
5225            }
5226        } finally {
5227            Binder.restoreCallingIdentity(identity);
5228        }
5229    }
5230
5231    /**
5232     * Compares two sets of signatures. Returns:
5233     * <br />
5234     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5235     * <br />
5236     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5237     * <br />
5238     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5239     * <br />
5240     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5241     * <br />
5242     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5243     */
5244    static int compareSignatures(Signature[] s1, Signature[] s2) {
5245        if (s1 == null) {
5246            return s2 == null
5247                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5248                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5249        }
5250
5251        if (s2 == null) {
5252            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5253        }
5254
5255        if (s1.length != s2.length) {
5256            return PackageManager.SIGNATURE_NO_MATCH;
5257        }
5258
5259        // Since both signature sets are of size 1, we can compare without HashSets.
5260        if (s1.length == 1) {
5261            return s1[0].equals(s2[0]) ?
5262                    PackageManager.SIGNATURE_MATCH :
5263                    PackageManager.SIGNATURE_NO_MATCH;
5264        }
5265
5266        ArraySet<Signature> set1 = new ArraySet<Signature>();
5267        for (Signature sig : s1) {
5268            set1.add(sig);
5269        }
5270        ArraySet<Signature> set2 = new ArraySet<Signature>();
5271        for (Signature sig : s2) {
5272            set2.add(sig);
5273        }
5274        // Make sure s2 contains all signatures in s1.
5275        if (set1.equals(set2)) {
5276            return PackageManager.SIGNATURE_MATCH;
5277        }
5278        return PackageManager.SIGNATURE_NO_MATCH;
5279    }
5280
5281    /**
5282     * If the database version for this type of package (internal storage or
5283     * external storage) is less than the version where package signatures
5284     * were updated, return true.
5285     */
5286    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5287        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5288        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5289    }
5290
5291    /**
5292     * Used for backward compatibility to make sure any packages with
5293     * certificate chains get upgraded to the new style. {@code existingSigs}
5294     * will be in the old format (since they were stored on disk from before the
5295     * system upgrade) and {@code scannedSigs} will be in the newer format.
5296     */
5297    private int compareSignaturesCompat(PackageSignatures existingSigs,
5298            PackageParser.Package scannedPkg) {
5299        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5300            return PackageManager.SIGNATURE_NO_MATCH;
5301        }
5302
5303        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5304        for (Signature sig : existingSigs.mSignatures) {
5305            existingSet.add(sig);
5306        }
5307        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5308        for (Signature sig : scannedPkg.mSignatures) {
5309            try {
5310                Signature[] chainSignatures = sig.getChainSignatures();
5311                for (Signature chainSig : chainSignatures) {
5312                    scannedCompatSet.add(chainSig);
5313                }
5314            } catch (CertificateEncodingException e) {
5315                scannedCompatSet.add(sig);
5316            }
5317        }
5318        /*
5319         * Make sure the expanded scanned set contains all signatures in the
5320         * existing one.
5321         */
5322        if (scannedCompatSet.equals(existingSet)) {
5323            // Migrate the old signatures to the new scheme.
5324            existingSigs.assignSignatures(scannedPkg.mSignatures);
5325            // The new KeySets will be re-added later in the scanning process.
5326            synchronized (mPackages) {
5327                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5328            }
5329            return PackageManager.SIGNATURE_MATCH;
5330        }
5331        return PackageManager.SIGNATURE_NO_MATCH;
5332    }
5333
5334    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5335        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5336        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5337    }
5338
5339    private int compareSignaturesRecover(PackageSignatures existingSigs,
5340            PackageParser.Package scannedPkg) {
5341        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5342            return PackageManager.SIGNATURE_NO_MATCH;
5343        }
5344
5345        String msg = null;
5346        try {
5347            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5348                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5349                        + scannedPkg.packageName);
5350                return PackageManager.SIGNATURE_MATCH;
5351            }
5352        } catch (CertificateException e) {
5353            msg = e.getMessage();
5354        }
5355
5356        logCriticalInfo(Log.INFO,
5357                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5358        return PackageManager.SIGNATURE_NO_MATCH;
5359    }
5360
5361    @Override
5362    public List<String> getAllPackages() {
5363        synchronized (mPackages) {
5364            return new ArrayList<String>(mPackages.keySet());
5365        }
5366    }
5367
5368    @Override
5369    public String[] getPackagesForUid(int uid) {
5370        final int userId = UserHandle.getUserId(uid);
5371        uid = UserHandle.getAppId(uid);
5372        // reader
5373        synchronized (mPackages) {
5374            Object obj = mSettings.getUserIdLPr(uid);
5375            if (obj instanceof SharedUserSetting) {
5376                final SharedUserSetting sus = (SharedUserSetting) obj;
5377                final int N = sus.packages.size();
5378                String[] res = new String[N];
5379                final Iterator<PackageSetting> it = sus.packages.iterator();
5380                int i = 0;
5381                while (it.hasNext()) {
5382                    PackageSetting ps = it.next();
5383                    if (ps.getInstalled(userId)) {
5384                        res[i++] = ps.name;
5385                    } else {
5386                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5387                    }
5388                }
5389                return res;
5390            } else if (obj instanceof PackageSetting) {
5391                final PackageSetting ps = (PackageSetting) obj;
5392                if (ps.getInstalled(userId)) {
5393                    return new String[]{ps.name};
5394                }
5395            }
5396        }
5397        return null;
5398    }
5399
5400    @Override
5401    public String getNameForUid(int uid) {
5402        // reader
5403        synchronized (mPackages) {
5404            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5405            if (obj instanceof SharedUserSetting) {
5406                final SharedUserSetting sus = (SharedUserSetting) obj;
5407                return sus.name + ":" + sus.userId;
5408            } else if (obj instanceof PackageSetting) {
5409                final PackageSetting ps = (PackageSetting) obj;
5410                return ps.name;
5411            }
5412        }
5413        return null;
5414    }
5415
5416    @Override
5417    public int getUidForSharedUser(String sharedUserName) {
5418        if(sharedUserName == null) {
5419            return -1;
5420        }
5421        // reader
5422        synchronized (mPackages) {
5423            SharedUserSetting suid;
5424            try {
5425                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5426                if (suid != null) {
5427                    return suid.userId;
5428                }
5429            } catch (PackageManagerException ignore) {
5430                // can't happen, but, still need to catch it
5431            }
5432            return -1;
5433        }
5434    }
5435
5436    @Override
5437    public int getFlagsForUid(int uid) {
5438        synchronized (mPackages) {
5439            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5440            if (obj instanceof SharedUserSetting) {
5441                final SharedUserSetting sus = (SharedUserSetting) obj;
5442                return sus.pkgFlags;
5443            } else if (obj instanceof PackageSetting) {
5444                final PackageSetting ps = (PackageSetting) obj;
5445                return ps.pkgFlags;
5446            }
5447        }
5448        return 0;
5449    }
5450
5451    @Override
5452    public int getPrivateFlagsForUid(int uid) {
5453        synchronized (mPackages) {
5454            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5455            if (obj instanceof SharedUserSetting) {
5456                final SharedUserSetting sus = (SharedUserSetting) obj;
5457                return sus.pkgPrivateFlags;
5458            } else if (obj instanceof PackageSetting) {
5459                final PackageSetting ps = (PackageSetting) obj;
5460                return ps.pkgPrivateFlags;
5461            }
5462        }
5463        return 0;
5464    }
5465
5466    @Override
5467    public boolean isUidPrivileged(int uid) {
5468        uid = UserHandle.getAppId(uid);
5469        // reader
5470        synchronized (mPackages) {
5471            Object obj = mSettings.getUserIdLPr(uid);
5472            if (obj instanceof SharedUserSetting) {
5473                final SharedUserSetting sus = (SharedUserSetting) obj;
5474                final Iterator<PackageSetting> it = sus.packages.iterator();
5475                while (it.hasNext()) {
5476                    if (it.next().isPrivileged()) {
5477                        return true;
5478                    }
5479                }
5480            } else if (obj instanceof PackageSetting) {
5481                final PackageSetting ps = (PackageSetting) obj;
5482                return ps.isPrivileged();
5483            }
5484        }
5485        return false;
5486    }
5487
5488    @Override
5489    public String[] getAppOpPermissionPackages(String permissionName) {
5490        synchronized (mPackages) {
5491            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5492            if (pkgs == null) {
5493                return null;
5494            }
5495            return pkgs.toArray(new String[pkgs.size()]);
5496        }
5497    }
5498
5499    @Override
5500    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5501            int flags, int userId) {
5502        try {
5503            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5504
5505            if (!sUserManager.exists(userId)) return null;
5506            flags = updateFlagsForResolve(flags, userId, intent);
5507            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5508                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5509
5510            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5511            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5512                    flags, userId);
5513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5514
5515            final ResolveInfo bestChoice =
5516                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5517            return bestChoice;
5518        } finally {
5519            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5520        }
5521    }
5522
5523    @Override
5524    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5525        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5526            throw new SecurityException(
5527                    "findPersistentPreferredActivity can only be run by the system");
5528        }
5529        if (!sUserManager.exists(userId)) {
5530            return null;
5531        }
5532        intent = updateIntentForResolve(intent);
5533        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5534        final int flags = updateFlagsForResolve(0, userId, intent);
5535        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5536                userId);
5537        synchronized (mPackages) {
5538            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5539                    userId);
5540        }
5541    }
5542
5543    @Override
5544    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5545            IntentFilter filter, int match, ComponentName activity) {
5546        final int userId = UserHandle.getCallingUserId();
5547        if (DEBUG_PREFERRED) {
5548            Log.v(TAG, "setLastChosenActivity intent=" + intent
5549                + " resolvedType=" + resolvedType
5550                + " flags=" + flags
5551                + " filter=" + filter
5552                + " match=" + match
5553                + " activity=" + activity);
5554            filter.dump(new PrintStreamPrinter(System.out), "    ");
5555        }
5556        intent.setComponent(null);
5557        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5558                userId);
5559        // Find any earlier preferred or last chosen entries and nuke them
5560        findPreferredActivity(intent, resolvedType,
5561                flags, query, 0, false, true, false, userId);
5562        // Add the new activity as the last chosen for this filter
5563        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5564                "Setting last chosen");
5565    }
5566
5567    @Override
5568    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5569        final int userId = UserHandle.getCallingUserId();
5570        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5571        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5572                userId);
5573        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5574                false, false, false, userId);
5575    }
5576
5577    private boolean isEphemeralDisabled() {
5578        // ephemeral apps have been disabled across the board
5579        if (DISABLE_EPHEMERAL_APPS) {
5580            return true;
5581        }
5582        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5583        if (!mSystemReady) {
5584            return true;
5585        }
5586        // we can't get a content resolver until the system is ready; these checks must happen last
5587        final ContentResolver resolver = mContext.getContentResolver();
5588        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5589            return true;
5590        }
5591        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5592    }
5593
5594    private boolean isEphemeralAllowed(
5595            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5596            boolean skipPackageCheck) {
5597        // Short circuit and return early if possible.
5598        if (isEphemeralDisabled()) {
5599            return false;
5600        }
5601        final int callingUser = UserHandle.getCallingUserId();
5602        if (callingUser != UserHandle.USER_SYSTEM) {
5603            return false;
5604        }
5605        if (mEphemeralResolverConnection == null) {
5606            return false;
5607        }
5608        if (mEphemeralInstallerComponent == null) {
5609            return false;
5610        }
5611        if (intent.getComponent() != null) {
5612            return false;
5613        }
5614        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5615            return false;
5616        }
5617        if (!skipPackageCheck && intent.getPackage() != null) {
5618            return false;
5619        }
5620        final boolean isWebUri = hasWebURI(intent);
5621        if (!isWebUri || intent.getData().getHost() == null) {
5622            return false;
5623        }
5624        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5625        synchronized (mPackages) {
5626            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5627            for (int n = 0; n < count; n++) {
5628                ResolveInfo info = resolvedActivities.get(n);
5629                String packageName = info.activityInfo.packageName;
5630                PackageSetting ps = mSettings.mPackages.get(packageName);
5631                if (ps != null) {
5632                    // Try to get the status from User settings first
5633                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5634                    int status = (int) (packedStatus >> 32);
5635                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5636                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5637                        if (DEBUG_EPHEMERAL) {
5638                            Slog.v(TAG, "DENY ephemeral apps;"
5639                                + " pkg: " + packageName + ", status: " + status);
5640                        }
5641                        return false;
5642                    }
5643                }
5644            }
5645        }
5646        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5647        return true;
5648    }
5649
5650    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5651            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5652            int userId) {
5653        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5654                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5655                        callingPackage, userId));
5656        mHandler.sendMessage(msg);
5657    }
5658
5659    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5660            int flags, List<ResolveInfo> query, int userId) {
5661        if (query != null) {
5662            final int N = query.size();
5663            if (N == 1) {
5664                return query.get(0);
5665            } else if (N > 1) {
5666                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5667                // If there is more than one activity with the same priority,
5668                // then let the user decide between them.
5669                ResolveInfo r0 = query.get(0);
5670                ResolveInfo r1 = query.get(1);
5671                if (DEBUG_INTENT_MATCHING || debug) {
5672                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5673                            + r1.activityInfo.name + "=" + r1.priority);
5674                }
5675                // If the first activity has a higher priority, or a different
5676                // default, then it is always desirable to pick it.
5677                if (r0.priority != r1.priority
5678                        || r0.preferredOrder != r1.preferredOrder
5679                        || r0.isDefault != r1.isDefault) {
5680                    return query.get(0);
5681                }
5682                // If we have saved a preference for a preferred activity for
5683                // this Intent, use that.
5684                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5685                        flags, query, r0.priority, true, false, debug, userId);
5686                if (ri != null) {
5687                    return ri;
5688                }
5689                ri = new ResolveInfo(mResolveInfo);
5690                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5691                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5692                // If all of the options come from the same package, show the application's
5693                // label and icon instead of the generic resolver's.
5694                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5695                // and then throw away the ResolveInfo itself, meaning that the caller loses
5696                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5697                // a fallback for this case; we only set the target package's resources on
5698                // the ResolveInfo, not the ActivityInfo.
5699                final String intentPackage = intent.getPackage();
5700                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5701                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5702                    ri.resolvePackageName = intentPackage;
5703                    if (userNeedsBadging(userId)) {
5704                        ri.noResourceId = true;
5705                    } else {
5706                        ri.icon = appi.icon;
5707                    }
5708                    ri.iconResourceId = appi.icon;
5709                    ri.labelRes = appi.labelRes;
5710                }
5711                ri.activityInfo.applicationInfo = new ApplicationInfo(
5712                        ri.activityInfo.applicationInfo);
5713                if (userId != 0) {
5714                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5715                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5716                }
5717                // Make sure that the resolver is displayable in car mode
5718                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5719                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5720                return ri;
5721            }
5722        }
5723        return null;
5724    }
5725
5726    /**
5727     * Return true if the given list is not empty and all of its contents have
5728     * an activityInfo with the given package name.
5729     */
5730    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5731        if (ArrayUtils.isEmpty(list)) {
5732            return false;
5733        }
5734        for (int i = 0, N = list.size(); i < N; i++) {
5735            final ResolveInfo ri = list.get(i);
5736            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5737            if (ai == null || !packageName.equals(ai.packageName)) {
5738                return false;
5739            }
5740        }
5741        return true;
5742    }
5743
5744    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5745            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5746        final int N = query.size();
5747        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5748                .get(userId);
5749        // Get the list of persistent preferred activities that handle the intent
5750        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5751        List<PersistentPreferredActivity> pprefs = ppir != null
5752                ? ppir.queryIntent(intent, resolvedType,
5753                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5754                        userId)
5755                : null;
5756        if (pprefs != null && pprefs.size() > 0) {
5757            final int M = pprefs.size();
5758            for (int i=0; i<M; i++) {
5759                final PersistentPreferredActivity ppa = pprefs.get(i);
5760                if (DEBUG_PREFERRED || debug) {
5761                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5762                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5763                            + "\n  component=" + ppa.mComponent);
5764                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5765                }
5766                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5767                        flags | MATCH_DISABLED_COMPONENTS, userId);
5768                if (DEBUG_PREFERRED || debug) {
5769                    Slog.v(TAG, "Found persistent preferred activity:");
5770                    if (ai != null) {
5771                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5772                    } else {
5773                        Slog.v(TAG, "  null");
5774                    }
5775                }
5776                if (ai == null) {
5777                    // This previously registered persistent preferred activity
5778                    // component is no longer known. Ignore it and do NOT remove it.
5779                    continue;
5780                }
5781                for (int j=0; j<N; j++) {
5782                    final ResolveInfo ri = query.get(j);
5783                    if (!ri.activityInfo.applicationInfo.packageName
5784                            .equals(ai.applicationInfo.packageName)) {
5785                        continue;
5786                    }
5787                    if (!ri.activityInfo.name.equals(ai.name)) {
5788                        continue;
5789                    }
5790                    //  Found a persistent preference that can handle the intent.
5791                    if (DEBUG_PREFERRED || debug) {
5792                        Slog.v(TAG, "Returning persistent preferred activity: " +
5793                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5794                    }
5795                    return ri;
5796                }
5797            }
5798        }
5799        return null;
5800    }
5801
5802    // TODO: handle preferred activities missing while user has amnesia
5803    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5804            List<ResolveInfo> query, int priority, boolean always,
5805            boolean removeMatches, boolean debug, int userId) {
5806        if (!sUserManager.exists(userId)) return null;
5807        flags = updateFlagsForResolve(flags, userId, intent);
5808        intent = updateIntentForResolve(intent);
5809        // writer
5810        synchronized (mPackages) {
5811            // Try to find a matching persistent preferred activity.
5812            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5813                    debug, userId);
5814
5815            // If a persistent preferred activity matched, use it.
5816            if (pri != null) {
5817                return pri;
5818            }
5819
5820            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5821            // Get the list of preferred activities that handle the intent
5822            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5823            List<PreferredActivity> prefs = pir != null
5824                    ? pir.queryIntent(intent, resolvedType,
5825                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5826                            userId)
5827                    : null;
5828            if (prefs != null && prefs.size() > 0) {
5829                boolean changed = false;
5830                try {
5831                    // First figure out how good the original match set is.
5832                    // We will only allow preferred activities that came
5833                    // from the same match quality.
5834                    int match = 0;
5835
5836                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5837
5838                    final int N = query.size();
5839                    for (int j=0; j<N; j++) {
5840                        final ResolveInfo ri = query.get(j);
5841                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5842                                + ": 0x" + Integer.toHexString(match));
5843                        if (ri.match > match) {
5844                            match = ri.match;
5845                        }
5846                    }
5847
5848                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5849                            + Integer.toHexString(match));
5850
5851                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5852                    final int M = prefs.size();
5853                    for (int i=0; i<M; i++) {
5854                        final PreferredActivity pa = prefs.get(i);
5855                        if (DEBUG_PREFERRED || debug) {
5856                            Slog.v(TAG, "Checking PreferredActivity ds="
5857                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5858                                    + "\n  component=" + pa.mPref.mComponent);
5859                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5860                        }
5861                        if (pa.mPref.mMatch != match) {
5862                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5863                                    + Integer.toHexString(pa.mPref.mMatch));
5864                            continue;
5865                        }
5866                        // If it's not an "always" type preferred activity and that's what we're
5867                        // looking for, skip it.
5868                        if (always && !pa.mPref.mAlways) {
5869                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5870                            continue;
5871                        }
5872                        final ActivityInfo ai = getActivityInfo(
5873                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5874                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5875                                userId);
5876                        if (DEBUG_PREFERRED || debug) {
5877                            Slog.v(TAG, "Found preferred activity:");
5878                            if (ai != null) {
5879                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5880                            } else {
5881                                Slog.v(TAG, "  null");
5882                            }
5883                        }
5884                        if (ai == null) {
5885                            // This previously registered preferred activity
5886                            // component is no longer known.  Most likely an update
5887                            // to the app was installed and in the new version this
5888                            // component no longer exists.  Clean it up by removing
5889                            // it from the preferred activities list, and skip it.
5890                            Slog.w(TAG, "Removing dangling preferred activity: "
5891                                    + pa.mPref.mComponent);
5892                            pir.removeFilter(pa);
5893                            changed = true;
5894                            continue;
5895                        }
5896                        for (int j=0; j<N; j++) {
5897                            final ResolveInfo ri = query.get(j);
5898                            if (!ri.activityInfo.applicationInfo.packageName
5899                                    .equals(ai.applicationInfo.packageName)) {
5900                                continue;
5901                            }
5902                            if (!ri.activityInfo.name.equals(ai.name)) {
5903                                continue;
5904                            }
5905
5906                            if (removeMatches) {
5907                                pir.removeFilter(pa);
5908                                changed = true;
5909                                if (DEBUG_PREFERRED) {
5910                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5911                                }
5912                                break;
5913                            }
5914
5915                            // Okay we found a previously set preferred or last chosen app.
5916                            // If the result set is different from when this
5917                            // was created, we need to clear it and re-ask the
5918                            // user their preference, if we're looking for an "always" type entry.
5919                            if (always && !pa.mPref.sameSet(query)) {
5920                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5921                                        + intent + " type " + resolvedType);
5922                                if (DEBUG_PREFERRED) {
5923                                    Slog.v(TAG, "Removing preferred activity since set changed "
5924                                            + pa.mPref.mComponent);
5925                                }
5926                                pir.removeFilter(pa);
5927                                // Re-add the filter as a "last chosen" entry (!always)
5928                                PreferredActivity lastChosen = new PreferredActivity(
5929                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5930                                pir.addFilter(lastChosen);
5931                                changed = true;
5932                                return null;
5933                            }
5934
5935                            // Yay! Either the set matched or we're looking for the last chosen
5936                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5937                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5938                            return ri;
5939                        }
5940                    }
5941                } finally {
5942                    if (changed) {
5943                        if (DEBUG_PREFERRED) {
5944                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5945                        }
5946                        scheduleWritePackageRestrictionsLocked(userId);
5947                    }
5948                }
5949            }
5950        }
5951        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5952        return null;
5953    }
5954
5955    /*
5956     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5957     */
5958    @Override
5959    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5960            int targetUserId) {
5961        mContext.enforceCallingOrSelfPermission(
5962                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5963        List<CrossProfileIntentFilter> matches =
5964                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5965        if (matches != null) {
5966            int size = matches.size();
5967            for (int i = 0; i < size; i++) {
5968                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5969            }
5970        }
5971        if (hasWebURI(intent)) {
5972            // cross-profile app linking works only towards the parent.
5973            final UserInfo parent = getProfileParent(sourceUserId);
5974            synchronized(mPackages) {
5975                int flags = updateFlagsForResolve(0, parent.id, intent);
5976                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5977                        intent, resolvedType, flags, sourceUserId, parent.id);
5978                return xpDomainInfo != null;
5979            }
5980        }
5981        return false;
5982    }
5983
5984    private UserInfo getProfileParent(int userId) {
5985        final long identity = Binder.clearCallingIdentity();
5986        try {
5987            return sUserManager.getProfileParent(userId);
5988        } finally {
5989            Binder.restoreCallingIdentity(identity);
5990        }
5991    }
5992
5993    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5994            String resolvedType, int userId) {
5995        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5996        if (resolver != null) {
5997            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
5998        }
5999        return null;
6000    }
6001
6002    @Override
6003    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6004            String resolvedType, int flags, int userId) {
6005        try {
6006            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6007
6008            return new ParceledListSlice<>(
6009                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6010        } finally {
6011            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6012        }
6013    }
6014
6015    /**
6016     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6017     * instant, returns {@code null}.
6018     */
6019    private String getInstantAppPackageName(int callingUid) {
6020        final int appId = UserHandle.getAppId(callingUid);
6021        synchronized (mPackages) {
6022            final Object obj = mSettings.getUserIdLPr(appId);
6023            if (obj instanceof PackageSetting) {
6024                final PackageSetting ps = (PackageSetting) obj;
6025                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6026                return isInstantApp ? ps.pkg.packageName : null;
6027            }
6028        }
6029        return null;
6030    }
6031
6032    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6033            String resolvedType, int flags, int userId) {
6034        if (!sUserManager.exists(userId)) return Collections.emptyList();
6035        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6036        flags = updateFlagsForResolve(flags, userId, intent);
6037        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6038                false /* requireFullPermission */, false /* checkShell */,
6039                "query intent activities");
6040        ComponentName comp = intent.getComponent();
6041        if (comp == null) {
6042            if (intent.getSelector() != null) {
6043                intent = intent.getSelector();
6044                comp = intent.getComponent();
6045            }
6046        }
6047
6048        if (comp != null) {
6049            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6050            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6051            if (ai != null) {
6052                // When specifying an explicit component, we prevent the activity from being
6053                // used when either 1) the calling package is normal and the activity is within
6054                // an ephemeral application or 2) the calling package is ephemeral and the
6055                // activity is not visible to ephemeral applications.
6056                final boolean matchInstantApp =
6057                        (flags & PackageManager.MATCH_INSTANT) != 0;
6058                final boolean matchVisibleToInstantAppOnly =
6059                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6060                final boolean isCallerInstantApp =
6061                        instantAppPkgName != null;
6062                final boolean isTargetSameInstantApp =
6063                        comp.getPackageName().equals(instantAppPkgName);
6064                final boolean isTargetInstantApp =
6065                        (ai.applicationInfo.privateFlags
6066                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6067                final boolean isTargetHiddenFromInstantApp =
6068                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6069                final boolean blockResolution =
6070                        !isTargetSameInstantApp
6071                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6072                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6073                                        && isTargetHiddenFromInstantApp));
6074                if (!blockResolution) {
6075                    final ResolveInfo ri = new ResolveInfo();
6076                    ri.activityInfo = ai;
6077                    list.add(ri);
6078                }
6079            }
6080            return list;
6081        }
6082
6083        // reader
6084        boolean sortResult = false;
6085        boolean addEphemeral = false;
6086        List<ResolveInfo> result;
6087        final String pkgName = intent.getPackage();
6088        synchronized (mPackages) {
6089            if (pkgName == null) {
6090                List<CrossProfileIntentFilter> matchingFilters =
6091                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6092                // Check for results that need to skip the current profile.
6093                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6094                        resolvedType, flags, userId);
6095                if (xpResolveInfo != null) {
6096                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6097                    xpResult.add(xpResolveInfo);
6098                    return filterForEphemeral(
6099                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6100                }
6101
6102                // Check for results in the current profile.
6103                result = filterIfNotSystemUser(mActivities.queryIntent(
6104                        intent, resolvedType, flags, userId), userId);
6105                addEphemeral =
6106                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6107
6108                // Check for cross profile results.
6109                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6110                xpResolveInfo = queryCrossProfileIntents(
6111                        matchingFilters, intent, resolvedType, flags, userId,
6112                        hasNonNegativePriorityResult);
6113                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6114                    boolean isVisibleToUser = filterIfNotSystemUser(
6115                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6116                    if (isVisibleToUser) {
6117                        result.add(xpResolveInfo);
6118                        sortResult = true;
6119                    }
6120                }
6121                if (hasWebURI(intent)) {
6122                    CrossProfileDomainInfo xpDomainInfo = null;
6123                    final UserInfo parent = getProfileParent(userId);
6124                    if (parent != null) {
6125                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6126                                flags, userId, parent.id);
6127                    }
6128                    if (xpDomainInfo != null) {
6129                        if (xpResolveInfo != null) {
6130                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6131                            // in the result.
6132                            result.remove(xpResolveInfo);
6133                        }
6134                        if (result.size() == 0 && !addEphemeral) {
6135                            // No result in current profile, but found candidate in parent user.
6136                            // And we are not going to add emphemeral app, so we can return the
6137                            // result straight away.
6138                            result.add(xpDomainInfo.resolveInfo);
6139                            return filterForEphemeral(result, instantAppPkgName);
6140                        }
6141                    } else if (result.size() <= 1 && !addEphemeral) {
6142                        // No result in parent user and <= 1 result in current profile, and we
6143                        // are not going to add emphemeral app, so we can return the result without
6144                        // further processing.
6145                        return filterForEphemeral(result, instantAppPkgName);
6146                    }
6147                    // We have more than one candidate (combining results from current and parent
6148                    // profile), so we need filtering and sorting.
6149                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6150                            intent, flags, result, xpDomainInfo, userId);
6151                    sortResult = true;
6152                }
6153            } else {
6154                final PackageParser.Package pkg = mPackages.get(pkgName);
6155                if (pkg != null) {
6156                    result = filterForEphemeral(filterIfNotSystemUser(
6157                            mActivities.queryIntentForPackage(
6158                                    intent, resolvedType, flags, pkg.activities, userId),
6159                            userId), instantAppPkgName);
6160                } else {
6161                    // the caller wants to resolve for a particular package; however, there
6162                    // were no installed results, so, try to find an ephemeral result
6163                    addEphemeral = isEphemeralAllowed(
6164                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6165                    result = new ArrayList<ResolveInfo>();
6166                }
6167            }
6168        }
6169        if (addEphemeral) {
6170            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6171            final EphemeralRequest requestObject = new EphemeralRequest(
6172                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6173                    null /*launchIntent*/, null /*callingPackage*/, userId);
6174            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6175                    mContext, mEphemeralResolverConnection, requestObject);
6176            if (intentInfo != null) {
6177                if (DEBUG_EPHEMERAL) {
6178                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6179                }
6180                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6181                ephemeralInstaller.ephemeralResponse = intentInfo;
6182                // make sure this resolver is the default
6183                ephemeralInstaller.isDefault = true;
6184                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6185                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6186                // add a non-generic filter
6187                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6188                ephemeralInstaller.filter.addDataPath(
6189                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6190                result.add(ephemeralInstaller);
6191            }
6192            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6193        }
6194        if (sortResult) {
6195            Collections.sort(result, mResolvePrioritySorter);
6196        }
6197        return filterForEphemeral(result, instantAppPkgName);
6198    }
6199
6200    private static class CrossProfileDomainInfo {
6201        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6202        ResolveInfo resolveInfo;
6203        /* Best domain verification status of the activities found in the other profile */
6204        int bestDomainVerificationStatus;
6205    }
6206
6207    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6208            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6209        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6210                sourceUserId)) {
6211            return null;
6212        }
6213        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6214                resolvedType, flags, parentUserId);
6215
6216        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6217            return null;
6218        }
6219        CrossProfileDomainInfo result = null;
6220        int size = resultTargetUser.size();
6221        for (int i = 0; i < size; i++) {
6222            ResolveInfo riTargetUser = resultTargetUser.get(i);
6223            // Intent filter verification is only for filters that specify a host. So don't return
6224            // those that handle all web uris.
6225            if (riTargetUser.handleAllWebDataURI) {
6226                continue;
6227            }
6228            String packageName = riTargetUser.activityInfo.packageName;
6229            PackageSetting ps = mSettings.mPackages.get(packageName);
6230            if (ps == null) {
6231                continue;
6232            }
6233            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6234            int status = (int)(verificationState >> 32);
6235            if (result == null) {
6236                result = new CrossProfileDomainInfo();
6237                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6238                        sourceUserId, parentUserId);
6239                result.bestDomainVerificationStatus = status;
6240            } else {
6241                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6242                        result.bestDomainVerificationStatus);
6243            }
6244        }
6245        // Don't consider matches with status NEVER across profiles.
6246        if (result != null && result.bestDomainVerificationStatus
6247                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6248            return null;
6249        }
6250        return result;
6251    }
6252
6253    /**
6254     * Verification statuses are ordered from the worse to the best, except for
6255     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6256     */
6257    private int bestDomainVerificationStatus(int status1, int status2) {
6258        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6259            return status2;
6260        }
6261        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6262            return status1;
6263        }
6264        return (int) MathUtils.max(status1, status2);
6265    }
6266
6267    private boolean isUserEnabled(int userId) {
6268        long callingId = Binder.clearCallingIdentity();
6269        try {
6270            UserInfo userInfo = sUserManager.getUserInfo(userId);
6271            return userInfo != null && userInfo.isEnabled();
6272        } finally {
6273            Binder.restoreCallingIdentity(callingId);
6274        }
6275    }
6276
6277    /**
6278     * Filter out activities with systemUserOnly flag set, when current user is not System.
6279     *
6280     * @return filtered list
6281     */
6282    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6283        if (userId == UserHandle.USER_SYSTEM) {
6284            return resolveInfos;
6285        }
6286        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6287            ResolveInfo info = resolveInfos.get(i);
6288            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6289                resolveInfos.remove(i);
6290            }
6291        }
6292        return resolveInfos;
6293    }
6294
6295    /**
6296     * Filters out ephemeral activities.
6297     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6298     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6299     *
6300     * @param resolveInfos The pre-filtered list of resolved activities
6301     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6302     *          is performed.
6303     * @return A filtered list of resolved activities.
6304     */
6305    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6306            String ephemeralPkgName) {
6307        if (ephemeralPkgName == null) {
6308            return resolveInfos;
6309        }
6310        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6311            ResolveInfo info = resolveInfos.get(i);
6312            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6313            // allow activities that are defined in the provided package
6314            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6315                continue;
6316            }
6317            // allow activities that have been explicitly exposed to ephemeral apps
6318            if (!isEphemeralApp
6319                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6320                continue;
6321            }
6322            resolveInfos.remove(i);
6323        }
6324        return resolveInfos;
6325    }
6326
6327    /**
6328     * @param resolveInfos list of resolve infos in descending priority order
6329     * @return if the list contains a resolve info with non-negative priority
6330     */
6331    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6332        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6333    }
6334
6335    private static boolean hasWebURI(Intent intent) {
6336        if (intent.getData() == null) {
6337            return false;
6338        }
6339        final String scheme = intent.getScheme();
6340        if (TextUtils.isEmpty(scheme)) {
6341            return false;
6342        }
6343        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6344    }
6345
6346    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6347            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6348            int userId) {
6349        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6350
6351        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6352            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6353                    candidates.size());
6354        }
6355
6356        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6357        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6358        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6359        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6360        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6361        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6362
6363        synchronized (mPackages) {
6364            final int count = candidates.size();
6365            // First, try to use linked apps. Partition the candidates into four lists:
6366            // one for the final results, one for the "do not use ever", one for "undefined status"
6367            // and finally one for "browser app type".
6368            for (int n=0; n<count; n++) {
6369                ResolveInfo info = candidates.get(n);
6370                String packageName = info.activityInfo.packageName;
6371                PackageSetting ps = mSettings.mPackages.get(packageName);
6372                if (ps != null) {
6373                    // Add to the special match all list (Browser use case)
6374                    if (info.handleAllWebDataURI) {
6375                        matchAllList.add(info);
6376                        continue;
6377                    }
6378                    // Try to get the status from User settings first
6379                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6380                    int status = (int)(packedStatus >> 32);
6381                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6382                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6383                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6384                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6385                                    + " : linkgen=" + linkGeneration);
6386                        }
6387                        // Use link-enabled generation as preferredOrder, i.e.
6388                        // prefer newly-enabled over earlier-enabled.
6389                        info.preferredOrder = linkGeneration;
6390                        alwaysList.add(info);
6391                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6392                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6393                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6394                        }
6395                        neverList.add(info);
6396                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6397                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6398                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6399                        }
6400                        alwaysAskList.add(info);
6401                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6402                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6403                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6404                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6405                        }
6406                        undefinedList.add(info);
6407                    }
6408                }
6409            }
6410
6411            // We'll want to include browser possibilities in a few cases
6412            boolean includeBrowser = false;
6413
6414            // First try to add the "always" resolution(s) for the current user, if any
6415            if (alwaysList.size() > 0) {
6416                result.addAll(alwaysList);
6417            } else {
6418                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6419                result.addAll(undefinedList);
6420                // Maybe add one for the other profile.
6421                if (xpDomainInfo != null && (
6422                        xpDomainInfo.bestDomainVerificationStatus
6423                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6424                    result.add(xpDomainInfo.resolveInfo);
6425                }
6426                includeBrowser = true;
6427            }
6428
6429            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6430            // If there were 'always' entries their preferred order has been set, so we also
6431            // back that off to make the alternatives equivalent
6432            if (alwaysAskList.size() > 0) {
6433                for (ResolveInfo i : result) {
6434                    i.preferredOrder = 0;
6435                }
6436                result.addAll(alwaysAskList);
6437                includeBrowser = true;
6438            }
6439
6440            if (includeBrowser) {
6441                // Also add browsers (all of them or only the default one)
6442                if (DEBUG_DOMAIN_VERIFICATION) {
6443                    Slog.v(TAG, "   ...including browsers in candidate set");
6444                }
6445                if ((matchFlags & MATCH_ALL) != 0) {
6446                    result.addAll(matchAllList);
6447                } else {
6448                    // Browser/generic handling case.  If there's a default browser, go straight
6449                    // to that (but only if there is no other higher-priority match).
6450                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6451                    int maxMatchPrio = 0;
6452                    ResolveInfo defaultBrowserMatch = null;
6453                    final int numCandidates = matchAllList.size();
6454                    for (int n = 0; n < numCandidates; n++) {
6455                        ResolveInfo info = matchAllList.get(n);
6456                        // track the highest overall match priority...
6457                        if (info.priority > maxMatchPrio) {
6458                            maxMatchPrio = info.priority;
6459                        }
6460                        // ...and the highest-priority default browser match
6461                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6462                            if (defaultBrowserMatch == null
6463                                    || (defaultBrowserMatch.priority < info.priority)) {
6464                                if (debug) {
6465                                    Slog.v(TAG, "Considering default browser match " + info);
6466                                }
6467                                defaultBrowserMatch = info;
6468                            }
6469                        }
6470                    }
6471                    if (defaultBrowserMatch != null
6472                            && defaultBrowserMatch.priority >= maxMatchPrio
6473                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6474                    {
6475                        if (debug) {
6476                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6477                        }
6478                        result.add(defaultBrowserMatch);
6479                    } else {
6480                        result.addAll(matchAllList);
6481                    }
6482                }
6483
6484                // If there is nothing selected, add all candidates and remove the ones that the user
6485                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6486                if (result.size() == 0) {
6487                    result.addAll(candidates);
6488                    result.removeAll(neverList);
6489                }
6490            }
6491        }
6492        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6493            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6494                    result.size());
6495            for (ResolveInfo info : result) {
6496                Slog.v(TAG, "  + " + info.activityInfo);
6497            }
6498        }
6499        return result;
6500    }
6501
6502    // Returns a packed value as a long:
6503    //
6504    // high 'int'-sized word: link status: undefined/ask/never/always.
6505    // low 'int'-sized word: relative priority among 'always' results.
6506    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6507        long result = ps.getDomainVerificationStatusForUser(userId);
6508        // if none available, get the master status
6509        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6510            if (ps.getIntentFilterVerificationInfo() != null) {
6511                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6512            }
6513        }
6514        return result;
6515    }
6516
6517    private ResolveInfo querySkipCurrentProfileIntents(
6518            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6519            int flags, int sourceUserId) {
6520        if (matchingFilters != null) {
6521            int size = matchingFilters.size();
6522            for (int i = 0; i < size; i ++) {
6523                CrossProfileIntentFilter filter = matchingFilters.get(i);
6524                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6525                    // Checking if there are activities in the target user that can handle the
6526                    // intent.
6527                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6528                            resolvedType, flags, sourceUserId);
6529                    if (resolveInfo != null) {
6530                        return resolveInfo;
6531                    }
6532                }
6533            }
6534        }
6535        return null;
6536    }
6537
6538    // Return matching ResolveInfo in target user if any.
6539    private ResolveInfo queryCrossProfileIntents(
6540            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6541            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6542        if (matchingFilters != null) {
6543            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6544            // match the same intent. For performance reasons, it is better not to
6545            // run queryIntent twice for the same userId
6546            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6547            int size = matchingFilters.size();
6548            for (int i = 0; i < size; i++) {
6549                CrossProfileIntentFilter filter = matchingFilters.get(i);
6550                int targetUserId = filter.getTargetUserId();
6551                boolean skipCurrentProfile =
6552                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6553                boolean skipCurrentProfileIfNoMatchFound =
6554                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6555                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6556                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6557                    // Checking if there are activities in the target user that can handle the
6558                    // intent.
6559                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6560                            resolvedType, flags, sourceUserId);
6561                    if (resolveInfo != null) return resolveInfo;
6562                    alreadyTriedUserIds.put(targetUserId, true);
6563                }
6564            }
6565        }
6566        return null;
6567    }
6568
6569    /**
6570     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6571     * will forward the intent to the filter's target user.
6572     * Otherwise, returns null.
6573     */
6574    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6575            String resolvedType, int flags, int sourceUserId) {
6576        int targetUserId = filter.getTargetUserId();
6577        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6578                resolvedType, flags, targetUserId);
6579        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6580            // If all the matches in the target profile are suspended, return null.
6581            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6582                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6583                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6584                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6585                            targetUserId);
6586                }
6587            }
6588        }
6589        return null;
6590    }
6591
6592    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6593            int sourceUserId, int targetUserId) {
6594        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6595        long ident = Binder.clearCallingIdentity();
6596        boolean targetIsProfile;
6597        try {
6598            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6599        } finally {
6600            Binder.restoreCallingIdentity(ident);
6601        }
6602        String className;
6603        if (targetIsProfile) {
6604            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6605        } else {
6606            className = FORWARD_INTENT_TO_PARENT;
6607        }
6608        ComponentName forwardingActivityComponentName = new ComponentName(
6609                mAndroidApplication.packageName, className);
6610        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6611                sourceUserId);
6612        if (!targetIsProfile) {
6613            forwardingActivityInfo.showUserIcon = targetUserId;
6614            forwardingResolveInfo.noResourceId = true;
6615        }
6616        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6617        forwardingResolveInfo.priority = 0;
6618        forwardingResolveInfo.preferredOrder = 0;
6619        forwardingResolveInfo.match = 0;
6620        forwardingResolveInfo.isDefault = true;
6621        forwardingResolveInfo.filter = filter;
6622        forwardingResolveInfo.targetUserId = targetUserId;
6623        return forwardingResolveInfo;
6624    }
6625
6626    @Override
6627    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6628            Intent[] specifics, String[] specificTypes, Intent intent,
6629            String resolvedType, int flags, int userId) {
6630        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6631                specificTypes, intent, resolvedType, flags, userId));
6632    }
6633
6634    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6635            Intent[] specifics, String[] specificTypes, Intent intent,
6636            String resolvedType, int flags, int userId) {
6637        if (!sUserManager.exists(userId)) return Collections.emptyList();
6638        flags = updateFlagsForResolve(flags, userId, intent);
6639        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6640                false /* requireFullPermission */, false /* checkShell */,
6641                "query intent activity options");
6642        final String resultsAction = intent.getAction();
6643
6644        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6645                | PackageManager.GET_RESOLVED_FILTER, userId);
6646
6647        if (DEBUG_INTENT_MATCHING) {
6648            Log.v(TAG, "Query " + intent + ": " + results);
6649        }
6650
6651        int specificsPos = 0;
6652        int N;
6653
6654        // todo: note that the algorithm used here is O(N^2).  This
6655        // isn't a problem in our current environment, but if we start running
6656        // into situations where we have more than 5 or 10 matches then this
6657        // should probably be changed to something smarter...
6658
6659        // First we go through and resolve each of the specific items
6660        // that were supplied, taking care of removing any corresponding
6661        // duplicate items in the generic resolve list.
6662        if (specifics != null) {
6663            for (int i=0; i<specifics.length; i++) {
6664                final Intent sintent = specifics[i];
6665                if (sintent == null) {
6666                    continue;
6667                }
6668
6669                if (DEBUG_INTENT_MATCHING) {
6670                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6671                }
6672
6673                String action = sintent.getAction();
6674                if (resultsAction != null && resultsAction.equals(action)) {
6675                    // If this action was explicitly requested, then don't
6676                    // remove things that have it.
6677                    action = null;
6678                }
6679
6680                ResolveInfo ri = null;
6681                ActivityInfo ai = null;
6682
6683                ComponentName comp = sintent.getComponent();
6684                if (comp == null) {
6685                    ri = resolveIntent(
6686                        sintent,
6687                        specificTypes != null ? specificTypes[i] : null,
6688                            flags, userId);
6689                    if (ri == null) {
6690                        continue;
6691                    }
6692                    if (ri == mResolveInfo) {
6693                        // ACK!  Must do something better with this.
6694                    }
6695                    ai = ri.activityInfo;
6696                    comp = new ComponentName(ai.applicationInfo.packageName,
6697                            ai.name);
6698                } else {
6699                    ai = getActivityInfo(comp, flags, userId);
6700                    if (ai == null) {
6701                        continue;
6702                    }
6703                }
6704
6705                // Look for any generic query activities that are duplicates
6706                // of this specific one, and remove them from the results.
6707                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6708                N = results.size();
6709                int j;
6710                for (j=specificsPos; j<N; j++) {
6711                    ResolveInfo sri = results.get(j);
6712                    if ((sri.activityInfo.name.equals(comp.getClassName())
6713                            && sri.activityInfo.applicationInfo.packageName.equals(
6714                                    comp.getPackageName()))
6715                        || (action != null && sri.filter.matchAction(action))) {
6716                        results.remove(j);
6717                        if (DEBUG_INTENT_MATCHING) Log.v(
6718                            TAG, "Removing duplicate item from " + j
6719                            + " due to specific " + specificsPos);
6720                        if (ri == null) {
6721                            ri = sri;
6722                        }
6723                        j--;
6724                        N--;
6725                    }
6726                }
6727
6728                // Add this specific item to its proper place.
6729                if (ri == null) {
6730                    ri = new ResolveInfo();
6731                    ri.activityInfo = ai;
6732                }
6733                results.add(specificsPos, ri);
6734                ri.specificIndex = i;
6735                specificsPos++;
6736            }
6737        }
6738
6739        // Now we go through the remaining generic results and remove any
6740        // duplicate actions that are found here.
6741        N = results.size();
6742        for (int i=specificsPos; i<N-1; i++) {
6743            final ResolveInfo rii = results.get(i);
6744            if (rii.filter == null) {
6745                continue;
6746            }
6747
6748            // Iterate over all of the actions of this result's intent
6749            // filter...  typically this should be just one.
6750            final Iterator<String> it = rii.filter.actionsIterator();
6751            if (it == null) {
6752                continue;
6753            }
6754            while (it.hasNext()) {
6755                final String action = it.next();
6756                if (resultsAction != null && resultsAction.equals(action)) {
6757                    // If this action was explicitly requested, then don't
6758                    // remove things that have it.
6759                    continue;
6760                }
6761                for (int j=i+1; j<N; j++) {
6762                    final ResolveInfo rij = results.get(j);
6763                    if (rij.filter != null && rij.filter.hasAction(action)) {
6764                        results.remove(j);
6765                        if (DEBUG_INTENT_MATCHING) Log.v(
6766                            TAG, "Removing duplicate item from " + j
6767                            + " due to action " + action + " at " + i);
6768                        j--;
6769                        N--;
6770                    }
6771                }
6772            }
6773
6774            // If the caller didn't request filter information, drop it now
6775            // so we don't have to marshall/unmarshall it.
6776            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6777                rii.filter = null;
6778            }
6779        }
6780
6781        // Filter out the caller activity if so requested.
6782        if (caller != null) {
6783            N = results.size();
6784            for (int i=0; i<N; i++) {
6785                ActivityInfo ainfo = results.get(i).activityInfo;
6786                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6787                        && caller.getClassName().equals(ainfo.name)) {
6788                    results.remove(i);
6789                    break;
6790                }
6791            }
6792        }
6793
6794        // If the caller didn't request filter information,
6795        // drop them now so we don't have to
6796        // marshall/unmarshall it.
6797        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6798            N = results.size();
6799            for (int i=0; i<N; i++) {
6800                results.get(i).filter = null;
6801            }
6802        }
6803
6804        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6805        return results;
6806    }
6807
6808    @Override
6809    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6810            String resolvedType, int flags, int userId) {
6811        return new ParceledListSlice<>(
6812                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6813    }
6814
6815    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6816            String resolvedType, int flags, int userId) {
6817        if (!sUserManager.exists(userId)) return Collections.emptyList();
6818        flags = updateFlagsForResolve(flags, userId, intent);
6819        ComponentName comp = intent.getComponent();
6820        if (comp == null) {
6821            if (intent.getSelector() != null) {
6822                intent = intent.getSelector();
6823                comp = intent.getComponent();
6824            }
6825        }
6826        if (comp != null) {
6827            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6828            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6829            if (ai != null) {
6830                ResolveInfo ri = new ResolveInfo();
6831                ri.activityInfo = ai;
6832                list.add(ri);
6833            }
6834            return list;
6835        }
6836
6837        // reader
6838        synchronized (mPackages) {
6839            String pkgName = intent.getPackage();
6840            if (pkgName == null) {
6841                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6842            }
6843            final PackageParser.Package pkg = mPackages.get(pkgName);
6844            if (pkg != null) {
6845                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6846                        userId);
6847            }
6848            return Collections.emptyList();
6849        }
6850    }
6851
6852    @Override
6853    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6854        if (!sUserManager.exists(userId)) return null;
6855        flags = updateFlagsForResolve(flags, userId, intent);
6856        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6857        if (query != null) {
6858            if (query.size() >= 1) {
6859                // If there is more than one service with the same priority,
6860                // just arbitrarily pick the first one.
6861                return query.get(0);
6862            }
6863        }
6864        return null;
6865    }
6866
6867    @Override
6868    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6869            String resolvedType, int flags, int userId) {
6870        return new ParceledListSlice<>(
6871                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6872    }
6873
6874    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6875            String resolvedType, int flags, int userId) {
6876        if (!sUserManager.exists(userId)) return Collections.emptyList();
6877        flags = updateFlagsForResolve(flags, userId, intent);
6878        ComponentName comp = intent.getComponent();
6879        if (comp == null) {
6880            if (intent.getSelector() != null) {
6881                intent = intent.getSelector();
6882                comp = intent.getComponent();
6883            }
6884        }
6885        if (comp != null) {
6886            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6887            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6888            if (si != null) {
6889                final ResolveInfo ri = new ResolveInfo();
6890                ri.serviceInfo = si;
6891                list.add(ri);
6892            }
6893            return list;
6894        }
6895
6896        // reader
6897        synchronized (mPackages) {
6898            String pkgName = intent.getPackage();
6899            if (pkgName == null) {
6900                return mServices.queryIntent(intent, resolvedType, flags, userId);
6901            }
6902            final PackageParser.Package pkg = mPackages.get(pkgName);
6903            if (pkg != null) {
6904                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6905                        userId);
6906            }
6907            return Collections.emptyList();
6908        }
6909    }
6910
6911    @Override
6912    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6913            String resolvedType, int flags, int userId) {
6914        return new ParceledListSlice<>(
6915                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6916    }
6917
6918    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6919            Intent intent, String resolvedType, int flags, int userId) {
6920        if (!sUserManager.exists(userId)) return Collections.emptyList();
6921        flags = updateFlagsForResolve(flags, userId, intent);
6922        ComponentName comp = intent.getComponent();
6923        if (comp == null) {
6924            if (intent.getSelector() != null) {
6925                intent = intent.getSelector();
6926                comp = intent.getComponent();
6927            }
6928        }
6929        if (comp != null) {
6930            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6931            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6932            if (pi != null) {
6933                final ResolveInfo ri = new ResolveInfo();
6934                ri.providerInfo = pi;
6935                list.add(ri);
6936            }
6937            return list;
6938        }
6939
6940        // reader
6941        synchronized (mPackages) {
6942            String pkgName = intent.getPackage();
6943            if (pkgName == null) {
6944                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6945            }
6946            final PackageParser.Package pkg = mPackages.get(pkgName);
6947            if (pkg != null) {
6948                return mProviders.queryIntentForPackage(
6949                        intent, resolvedType, flags, pkg.providers, userId);
6950            }
6951            return Collections.emptyList();
6952        }
6953    }
6954
6955    @Override
6956    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6957        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6958        flags = updateFlagsForPackage(flags, userId, null);
6959        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6960        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6961                true /* requireFullPermission */, false /* checkShell */,
6962                "get installed packages");
6963
6964        // writer
6965        synchronized (mPackages) {
6966            ArrayList<PackageInfo> list;
6967            if (listUninstalled) {
6968                list = new ArrayList<>(mSettings.mPackages.size());
6969                for (PackageSetting ps : mSettings.mPackages.values()) {
6970                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6971                        continue;
6972                    }
6973                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6974                    if (pi != null) {
6975                        list.add(pi);
6976                    }
6977                }
6978            } else {
6979                list = new ArrayList<>(mPackages.size());
6980                for (PackageParser.Package p : mPackages.values()) {
6981                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6982                            Binder.getCallingUid(), userId)) {
6983                        continue;
6984                    }
6985                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6986                            p.mExtras, flags, userId);
6987                    if (pi != null) {
6988                        list.add(pi);
6989                    }
6990                }
6991            }
6992
6993            return new ParceledListSlice<>(list);
6994        }
6995    }
6996
6997    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6998            String[] permissions, boolean[] tmp, int flags, int userId) {
6999        int numMatch = 0;
7000        final PermissionsState permissionsState = ps.getPermissionsState();
7001        for (int i=0; i<permissions.length; i++) {
7002            final String permission = permissions[i];
7003            if (permissionsState.hasPermission(permission, userId)) {
7004                tmp[i] = true;
7005                numMatch++;
7006            } else {
7007                tmp[i] = false;
7008            }
7009        }
7010        if (numMatch == 0) {
7011            return;
7012        }
7013        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7014
7015        // The above might return null in cases of uninstalled apps or install-state
7016        // skew across users/profiles.
7017        if (pi != null) {
7018            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7019                if (numMatch == permissions.length) {
7020                    pi.requestedPermissions = permissions;
7021                } else {
7022                    pi.requestedPermissions = new String[numMatch];
7023                    numMatch = 0;
7024                    for (int i=0; i<permissions.length; i++) {
7025                        if (tmp[i]) {
7026                            pi.requestedPermissions[numMatch] = permissions[i];
7027                            numMatch++;
7028                        }
7029                    }
7030                }
7031            }
7032            list.add(pi);
7033        }
7034    }
7035
7036    @Override
7037    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7038            String[] permissions, int flags, int userId) {
7039        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7040        flags = updateFlagsForPackage(flags, userId, permissions);
7041        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7042                true /* requireFullPermission */, false /* checkShell */,
7043                "get packages holding permissions");
7044        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7045
7046        // writer
7047        synchronized (mPackages) {
7048            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7049            boolean[] tmpBools = new boolean[permissions.length];
7050            if (listUninstalled) {
7051                for (PackageSetting ps : mSettings.mPackages.values()) {
7052                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7053                            userId);
7054                }
7055            } else {
7056                for (PackageParser.Package pkg : mPackages.values()) {
7057                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7058                    if (ps != null) {
7059                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7060                                userId);
7061                    }
7062                }
7063            }
7064
7065            return new ParceledListSlice<PackageInfo>(list);
7066        }
7067    }
7068
7069    @Override
7070    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7071        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7072        flags = updateFlagsForApplication(flags, userId, null);
7073        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7074
7075        // writer
7076        synchronized (mPackages) {
7077            ArrayList<ApplicationInfo> list;
7078            if (listUninstalled) {
7079                list = new ArrayList<>(mSettings.mPackages.size());
7080                for (PackageSetting ps : mSettings.mPackages.values()) {
7081                    ApplicationInfo ai;
7082                    int effectiveFlags = flags;
7083                    if (ps.isSystem()) {
7084                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7085                    }
7086                    if (ps.pkg != null) {
7087                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7088                            continue;
7089                        }
7090                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7091                                ps.readUserState(userId), userId);
7092                        if (ai != null) {
7093                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7094                        }
7095                    } else {
7096                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7097                        // and already converts to externally visible package name
7098                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7099                                Binder.getCallingUid(), effectiveFlags, userId);
7100                    }
7101                    if (ai != null) {
7102                        list.add(ai);
7103                    }
7104                }
7105            } else {
7106                list = new ArrayList<>(mPackages.size());
7107                for (PackageParser.Package p : mPackages.values()) {
7108                    if (p.mExtras != null) {
7109                        PackageSetting ps = (PackageSetting) p.mExtras;
7110                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7111                            continue;
7112                        }
7113                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7114                                ps.readUserState(userId), userId);
7115                        if (ai != null) {
7116                            ai.packageName = resolveExternalPackageNameLPr(p);
7117                            list.add(ai);
7118                        }
7119                    }
7120                }
7121            }
7122
7123            return new ParceledListSlice<>(list);
7124        }
7125    }
7126
7127    @Override
7128    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7129        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7130            return null;
7131        }
7132
7133        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7134                "getEphemeralApplications");
7135        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7136                true /* requireFullPermission */, false /* checkShell */,
7137                "getEphemeralApplications");
7138        synchronized (mPackages) {
7139            List<InstantAppInfo> instantApps = mInstantAppRegistry
7140                    .getInstantAppsLPr(userId);
7141            if (instantApps != null) {
7142                return new ParceledListSlice<>(instantApps);
7143            }
7144        }
7145        return null;
7146    }
7147
7148    @Override
7149    public boolean isInstantApp(String packageName, int userId) {
7150        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7151                true /* requireFullPermission */, false /* checkShell */,
7152                "isInstantApp");
7153        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7154            return false;
7155        }
7156
7157        if (!isCallerSameApp(packageName)) {
7158            return false;
7159        }
7160        synchronized (mPackages) {
7161            final PackageSetting ps = mSettings.mPackages.get(packageName);
7162            if (ps != null) {
7163                return ps.getInstantApp(userId);
7164            }
7165        }
7166        return false;
7167    }
7168
7169    @Override
7170    public byte[] getInstantAppCookie(String packageName, int userId) {
7171        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7172            return null;
7173        }
7174
7175        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7176                true /* requireFullPermission */, false /* checkShell */,
7177                "getInstantAppCookie");
7178        if (!isCallerSameApp(packageName)) {
7179            return null;
7180        }
7181        synchronized (mPackages) {
7182            return mInstantAppRegistry.getInstantAppCookieLPw(
7183                    packageName, userId);
7184        }
7185    }
7186
7187    @Override
7188    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7189        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7190            return true;
7191        }
7192
7193        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7194                true /* requireFullPermission */, true /* checkShell */,
7195                "setInstantAppCookie");
7196        if (!isCallerSameApp(packageName)) {
7197            return false;
7198        }
7199        synchronized (mPackages) {
7200            return mInstantAppRegistry.setInstantAppCookieLPw(
7201                    packageName, cookie, userId);
7202        }
7203    }
7204
7205    @Override
7206    public Bitmap getInstantAppIcon(String packageName, int userId) {
7207        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7208            return null;
7209        }
7210
7211        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7212                "getInstantAppIcon");
7213
7214        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7215                true /* requireFullPermission */, false /* checkShell */,
7216                "getInstantAppIcon");
7217
7218        synchronized (mPackages) {
7219            return mInstantAppRegistry.getInstantAppIconLPw(
7220                    packageName, userId);
7221        }
7222    }
7223
7224    private boolean isCallerSameApp(String packageName) {
7225        PackageParser.Package pkg = mPackages.get(packageName);
7226        return pkg != null
7227                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7228    }
7229
7230    @Override
7231    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7232        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7233    }
7234
7235    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7236        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7237
7238        // reader
7239        synchronized (mPackages) {
7240            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7241            final int userId = UserHandle.getCallingUserId();
7242            while (i.hasNext()) {
7243                final PackageParser.Package p = i.next();
7244                if (p.applicationInfo == null) continue;
7245
7246                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7247                        && !p.applicationInfo.isDirectBootAware();
7248                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7249                        && p.applicationInfo.isDirectBootAware();
7250
7251                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7252                        && (!mSafeMode || isSystemApp(p))
7253                        && (matchesUnaware || matchesAware)) {
7254                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7255                    if (ps != null) {
7256                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7257                                ps.readUserState(userId), userId);
7258                        if (ai != null) {
7259                            finalList.add(ai);
7260                        }
7261                    }
7262                }
7263            }
7264        }
7265
7266        return finalList;
7267    }
7268
7269    @Override
7270    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7271        if (!sUserManager.exists(userId)) return null;
7272        flags = updateFlagsForComponent(flags, userId, name);
7273        // reader
7274        synchronized (mPackages) {
7275            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7276            PackageSetting ps = provider != null
7277                    ? mSettings.mPackages.get(provider.owner.packageName)
7278                    : null;
7279            return ps != null
7280                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7281                    ? PackageParser.generateProviderInfo(provider, flags,
7282                            ps.readUserState(userId), userId)
7283                    : null;
7284        }
7285    }
7286
7287    /**
7288     * @deprecated
7289     */
7290    @Deprecated
7291    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7292        // reader
7293        synchronized (mPackages) {
7294            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7295                    .entrySet().iterator();
7296            final int userId = UserHandle.getCallingUserId();
7297            while (i.hasNext()) {
7298                Map.Entry<String, PackageParser.Provider> entry = i.next();
7299                PackageParser.Provider p = entry.getValue();
7300                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7301
7302                if (ps != null && p.syncable
7303                        && (!mSafeMode || (p.info.applicationInfo.flags
7304                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7305                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7306                            ps.readUserState(userId), userId);
7307                    if (info != null) {
7308                        outNames.add(entry.getKey());
7309                        outInfo.add(info);
7310                    }
7311                }
7312            }
7313        }
7314    }
7315
7316    @Override
7317    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7318            int uid, int flags) {
7319        final int userId = processName != null ? UserHandle.getUserId(uid)
7320                : UserHandle.getCallingUserId();
7321        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7322        flags = updateFlagsForComponent(flags, userId, processName);
7323
7324        ArrayList<ProviderInfo> finalList = null;
7325        // reader
7326        synchronized (mPackages) {
7327            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7328            while (i.hasNext()) {
7329                final PackageParser.Provider p = i.next();
7330                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7331                if (ps != null && p.info.authority != null
7332                        && (processName == null
7333                                || (p.info.processName.equals(processName)
7334                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7335                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7336                    if (finalList == null) {
7337                        finalList = new ArrayList<ProviderInfo>(3);
7338                    }
7339                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7340                            ps.readUserState(userId), userId);
7341                    if (info != null) {
7342                        finalList.add(info);
7343                    }
7344                }
7345            }
7346        }
7347
7348        if (finalList != null) {
7349            Collections.sort(finalList, mProviderInitOrderSorter);
7350            return new ParceledListSlice<ProviderInfo>(finalList);
7351        }
7352
7353        return ParceledListSlice.emptyList();
7354    }
7355
7356    @Override
7357    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7358        // reader
7359        synchronized (mPackages) {
7360            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7361            return PackageParser.generateInstrumentationInfo(i, flags);
7362        }
7363    }
7364
7365    @Override
7366    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7367            String targetPackage, int flags) {
7368        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7369    }
7370
7371    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7372            int flags) {
7373        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7374
7375        // reader
7376        synchronized (mPackages) {
7377            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7378            while (i.hasNext()) {
7379                final PackageParser.Instrumentation p = i.next();
7380                if (targetPackage == null
7381                        || targetPackage.equals(p.info.targetPackage)) {
7382                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7383                            flags);
7384                    if (ii != null) {
7385                        finalList.add(ii);
7386                    }
7387                }
7388            }
7389        }
7390
7391        return finalList;
7392    }
7393
7394    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7395        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7396        if (overlays == null) {
7397            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7398            return;
7399        }
7400        for (PackageParser.Package opkg : overlays.values()) {
7401            // Not much to do if idmap fails: we already logged the error
7402            // and we certainly don't want to abort installation of pkg simply
7403            // because an overlay didn't fit properly. For these reasons,
7404            // ignore the return value of createIdmapForPackagePairLI.
7405            createIdmapForPackagePairLI(pkg, opkg);
7406        }
7407    }
7408
7409    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7410            PackageParser.Package opkg) {
7411        if (!opkg.mTrustedOverlay) {
7412            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7413                    opkg.baseCodePath + ": overlay not trusted");
7414            return false;
7415        }
7416        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7417        if (overlaySet == null) {
7418            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7419                    opkg.baseCodePath + " but target package has no known overlays");
7420            return false;
7421        }
7422        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7423        // TODO: generate idmap for split APKs
7424        try {
7425            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7426        } catch (InstallerException e) {
7427            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7428                    + opkg.baseCodePath);
7429            return false;
7430        }
7431        PackageParser.Package[] overlayArray =
7432            overlaySet.values().toArray(new PackageParser.Package[0]);
7433        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7434            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7435                return p1.mOverlayPriority - p2.mOverlayPriority;
7436            }
7437        };
7438        Arrays.sort(overlayArray, cmp);
7439
7440        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7441        int i = 0;
7442        for (PackageParser.Package p : overlayArray) {
7443            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7444        }
7445        return true;
7446    }
7447
7448    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7449        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7450        try {
7451            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7452        } finally {
7453            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7454        }
7455    }
7456
7457    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7458        final File[] files = dir.listFiles();
7459        if (ArrayUtils.isEmpty(files)) {
7460            Log.d(TAG, "No files in app dir " + dir);
7461            return;
7462        }
7463
7464        if (DEBUG_PACKAGE_SCANNING) {
7465            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7466                    + " flags=0x" + Integer.toHexString(parseFlags));
7467        }
7468        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7469                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7470
7471        // Submit files for parsing in parallel
7472        int fileCount = 0;
7473        for (File file : files) {
7474            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7475                    && !PackageInstallerService.isStageName(file.getName());
7476            if (!isPackage) {
7477                // Ignore entries which are not packages
7478                continue;
7479            }
7480            parallelPackageParser.submit(file, parseFlags);
7481            fileCount++;
7482        }
7483
7484        // Process results one by one
7485        for (; fileCount > 0; fileCount--) {
7486            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7487            Throwable throwable = parseResult.throwable;
7488            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7489
7490            if (throwable == null) {
7491                // Static shared libraries have synthetic package names
7492                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7493                    renameStaticSharedLibraryPackage(parseResult.pkg);
7494                }
7495                try {
7496                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7497                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7498                                currentTime, null);
7499                    }
7500                } catch (PackageManagerException e) {
7501                    errorCode = e.error;
7502                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7503                }
7504            } else if (throwable instanceof PackageParser.PackageParserException) {
7505                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7506                        throwable;
7507                errorCode = e.error;
7508                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7509            } else {
7510                throw new IllegalStateException("Unexpected exception occurred while parsing "
7511                        + parseResult.scanFile, throwable);
7512            }
7513
7514            // Delete invalid userdata apps
7515            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7516                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7517                logCriticalInfo(Log.WARN,
7518                        "Deleting invalid package at " + parseResult.scanFile);
7519                removeCodePathLI(parseResult.scanFile);
7520            }
7521        }
7522        parallelPackageParser.close();
7523    }
7524
7525    private static File getSettingsProblemFile() {
7526        File dataDir = Environment.getDataDirectory();
7527        File systemDir = new File(dataDir, "system");
7528        File fname = new File(systemDir, "uiderrors.txt");
7529        return fname;
7530    }
7531
7532    static void reportSettingsProblem(int priority, String msg) {
7533        logCriticalInfo(priority, msg);
7534    }
7535
7536    static void logCriticalInfo(int priority, String msg) {
7537        Slog.println(priority, TAG, msg);
7538        EventLogTags.writePmCriticalInfo(msg);
7539        try {
7540            File fname = getSettingsProblemFile();
7541            FileOutputStream out = new FileOutputStream(fname, true);
7542            PrintWriter pw = new FastPrintWriter(out);
7543            SimpleDateFormat formatter = new SimpleDateFormat();
7544            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7545            pw.println(dateString + ": " + msg);
7546            pw.close();
7547            FileUtils.setPermissions(
7548                    fname.toString(),
7549                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7550                    -1, -1);
7551        } catch (java.io.IOException e) {
7552        }
7553    }
7554
7555    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7556        if (srcFile.isDirectory()) {
7557            final File baseFile = new File(pkg.baseCodePath);
7558            long maxModifiedTime = baseFile.lastModified();
7559            if (pkg.splitCodePaths != null) {
7560                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7561                    final File splitFile = new File(pkg.splitCodePaths[i]);
7562                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7563                }
7564            }
7565            return maxModifiedTime;
7566        }
7567        return srcFile.lastModified();
7568    }
7569
7570    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7571            final int policyFlags) throws PackageManagerException {
7572        // When upgrading from pre-N MR1, verify the package time stamp using the package
7573        // directory and not the APK file.
7574        final long lastModifiedTime = mIsPreNMR1Upgrade
7575                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7576        if (ps != null
7577                && ps.codePath.equals(srcFile)
7578                && ps.timeStamp == lastModifiedTime
7579                && !isCompatSignatureUpdateNeeded(pkg)
7580                && !isRecoverSignatureUpdateNeeded(pkg)) {
7581            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7582            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7583            ArraySet<PublicKey> signingKs;
7584            synchronized (mPackages) {
7585                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7586            }
7587            if (ps.signatures.mSignatures != null
7588                    && ps.signatures.mSignatures.length != 0
7589                    && signingKs != null) {
7590                // Optimization: reuse the existing cached certificates
7591                // if the package appears to be unchanged.
7592                pkg.mSignatures = ps.signatures.mSignatures;
7593                pkg.mSigningKeys = signingKs;
7594                return;
7595            }
7596
7597            Slog.w(TAG, "PackageSetting for " + ps.name
7598                    + " is missing signatures.  Collecting certs again to recover them.");
7599        } else {
7600            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7601        }
7602
7603        try {
7604            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7605            PackageParser.collectCertificates(pkg, policyFlags);
7606        } catch (PackageParserException e) {
7607            throw PackageManagerException.from(e);
7608        } finally {
7609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7610        }
7611    }
7612
7613    /**
7614     *  Traces a package scan.
7615     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7616     */
7617    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7618            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7619        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7620        try {
7621            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7622        } finally {
7623            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7624        }
7625    }
7626
7627    /**
7628     *  Scans a package and returns the newly parsed package.
7629     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7630     */
7631    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7632            long currentTime, UserHandle user) throws PackageManagerException {
7633        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7634        PackageParser pp = new PackageParser();
7635        pp.setSeparateProcesses(mSeparateProcesses);
7636        pp.setOnlyCoreApps(mOnlyCore);
7637        pp.setDisplayMetrics(mMetrics);
7638
7639        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7640            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7641        }
7642
7643        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7644        final PackageParser.Package pkg;
7645        try {
7646            pkg = pp.parsePackage(scanFile, parseFlags);
7647        } catch (PackageParserException e) {
7648            throw PackageManagerException.from(e);
7649        } finally {
7650            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7651        }
7652
7653        // Static shared libraries have synthetic package names
7654        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7655            renameStaticSharedLibraryPackage(pkg);
7656        }
7657
7658        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7659    }
7660
7661    /**
7662     *  Scans a package and returns the newly parsed package.
7663     *  @throws PackageManagerException on a parse error.
7664     */
7665    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7666            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7667            throws PackageManagerException {
7668        // If the package has children and this is the first dive in the function
7669        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7670        // packages (parent and children) would be successfully scanned before the
7671        // actual scan since scanning mutates internal state and we want to atomically
7672        // install the package and its children.
7673        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7674            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7675                scanFlags |= SCAN_CHECK_ONLY;
7676            }
7677        } else {
7678            scanFlags &= ~SCAN_CHECK_ONLY;
7679        }
7680
7681        // Scan the parent
7682        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7683                scanFlags, currentTime, user);
7684
7685        // Scan the children
7686        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7687        for (int i = 0; i < childCount; i++) {
7688            PackageParser.Package childPackage = pkg.childPackages.get(i);
7689            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7690                    currentTime, user);
7691        }
7692
7693
7694        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7695            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7696        }
7697
7698        return scannedPkg;
7699    }
7700
7701    /**
7702     *  Scans a package and returns the newly parsed package.
7703     *  @throws PackageManagerException on a parse error.
7704     */
7705    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7706            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7707            throws PackageManagerException {
7708        PackageSetting ps = null;
7709        PackageSetting updatedPkg;
7710        // reader
7711        synchronized (mPackages) {
7712            // Look to see if we already know about this package.
7713            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7714            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7715                // This package has been renamed to its original name.  Let's
7716                // use that.
7717                ps = mSettings.getPackageLPr(oldName);
7718            }
7719            // If there was no original package, see one for the real package name.
7720            if (ps == null) {
7721                ps = mSettings.getPackageLPr(pkg.packageName);
7722            }
7723            // Check to see if this package could be hiding/updating a system
7724            // package.  Must look for it either under the original or real
7725            // package name depending on our state.
7726            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7727            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7728
7729            // If this is a package we don't know about on the system partition, we
7730            // may need to remove disabled child packages on the system partition
7731            // or may need to not add child packages if the parent apk is updated
7732            // on the data partition and no longer defines this child package.
7733            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7734                // If this is a parent package for an updated system app and this system
7735                // app got an OTA update which no longer defines some of the child packages
7736                // we have to prune them from the disabled system packages.
7737                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7738                if (disabledPs != null) {
7739                    final int scannedChildCount = (pkg.childPackages != null)
7740                            ? pkg.childPackages.size() : 0;
7741                    final int disabledChildCount = disabledPs.childPackageNames != null
7742                            ? disabledPs.childPackageNames.size() : 0;
7743                    for (int i = 0; i < disabledChildCount; i++) {
7744                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7745                        boolean disabledPackageAvailable = false;
7746                        for (int j = 0; j < scannedChildCount; j++) {
7747                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7748                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7749                                disabledPackageAvailable = true;
7750                                break;
7751                            }
7752                         }
7753                         if (!disabledPackageAvailable) {
7754                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7755                         }
7756                    }
7757                }
7758            }
7759        }
7760
7761        boolean updatedPkgBetter = false;
7762        // First check if this is a system package that may involve an update
7763        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7764            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7765            // it needs to drop FLAG_PRIVILEGED.
7766            if (locationIsPrivileged(scanFile)) {
7767                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7768            } else {
7769                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7770            }
7771
7772            if (ps != null && !ps.codePath.equals(scanFile)) {
7773                // The path has changed from what was last scanned...  check the
7774                // version of the new path against what we have stored to determine
7775                // what to do.
7776                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7777                if (pkg.mVersionCode <= ps.versionCode) {
7778                    // The system package has been updated and the code path does not match
7779                    // Ignore entry. Skip it.
7780                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7781                            + " ignored: updated version " + ps.versionCode
7782                            + " better than this " + pkg.mVersionCode);
7783                    if (!updatedPkg.codePath.equals(scanFile)) {
7784                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7785                                + ps.name + " changing from " + updatedPkg.codePathString
7786                                + " to " + scanFile);
7787                        updatedPkg.codePath = scanFile;
7788                        updatedPkg.codePathString = scanFile.toString();
7789                        updatedPkg.resourcePath = scanFile;
7790                        updatedPkg.resourcePathString = scanFile.toString();
7791                    }
7792                    updatedPkg.pkg = pkg;
7793                    updatedPkg.versionCode = pkg.mVersionCode;
7794
7795                    // Update the disabled system child packages to point to the package too.
7796                    final int childCount = updatedPkg.childPackageNames != null
7797                            ? updatedPkg.childPackageNames.size() : 0;
7798                    for (int i = 0; i < childCount; i++) {
7799                        String childPackageName = updatedPkg.childPackageNames.get(i);
7800                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7801                                childPackageName);
7802                        if (updatedChildPkg != null) {
7803                            updatedChildPkg.pkg = pkg;
7804                            updatedChildPkg.versionCode = pkg.mVersionCode;
7805                        }
7806                    }
7807
7808                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7809                            + scanFile + " ignored: updated version " + ps.versionCode
7810                            + " better than this " + pkg.mVersionCode);
7811                } else {
7812                    // The current app on the system partition is better than
7813                    // what we have updated to on the data partition; switch
7814                    // back to the system partition version.
7815                    // At this point, its safely assumed that package installation for
7816                    // apps in system partition will go through. If not there won't be a working
7817                    // version of the app
7818                    // writer
7819                    synchronized (mPackages) {
7820                        // Just remove the loaded entries from package lists.
7821                        mPackages.remove(ps.name);
7822                    }
7823
7824                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7825                            + " reverting from " + ps.codePathString
7826                            + ": new version " + pkg.mVersionCode
7827                            + " better than installed " + ps.versionCode);
7828
7829                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7830                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7831                    synchronized (mInstallLock) {
7832                        args.cleanUpResourcesLI();
7833                    }
7834                    synchronized (mPackages) {
7835                        mSettings.enableSystemPackageLPw(ps.name);
7836                    }
7837                    updatedPkgBetter = true;
7838                }
7839            }
7840        }
7841
7842        if (updatedPkg != null) {
7843            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7844            // initially
7845            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7846
7847            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7848            // flag set initially
7849            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7850                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7851            }
7852        }
7853
7854        // Verify certificates against what was last scanned
7855        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7856
7857        /*
7858         * A new system app appeared, but we already had a non-system one of the
7859         * same name installed earlier.
7860         */
7861        boolean shouldHideSystemApp = false;
7862        if (updatedPkg == null && ps != null
7863                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7864            /*
7865             * Check to make sure the signatures match first. If they don't,
7866             * wipe the installed application and its data.
7867             */
7868            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7869                    != PackageManager.SIGNATURE_MATCH) {
7870                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7871                        + " signatures don't match existing userdata copy; removing");
7872                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7873                        "scanPackageInternalLI")) {
7874                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7875                }
7876                ps = null;
7877            } else {
7878                /*
7879                 * If the newly-added system app is an older version than the
7880                 * already installed version, hide it. It will be scanned later
7881                 * and re-added like an update.
7882                 */
7883                if (pkg.mVersionCode <= ps.versionCode) {
7884                    shouldHideSystemApp = true;
7885                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7886                            + " but new version " + pkg.mVersionCode + " better than installed "
7887                            + ps.versionCode + "; hiding system");
7888                } else {
7889                    /*
7890                     * The newly found system app is a newer version that the
7891                     * one previously installed. Simply remove the
7892                     * already-installed application and replace it with our own
7893                     * while keeping the application data.
7894                     */
7895                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7896                            + " reverting from " + ps.codePathString + ": new version "
7897                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7898                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7899                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7900                    synchronized (mInstallLock) {
7901                        args.cleanUpResourcesLI();
7902                    }
7903                }
7904            }
7905        }
7906
7907        // The apk is forward locked (not public) if its code and resources
7908        // are kept in different files. (except for app in either system or
7909        // vendor path).
7910        // TODO grab this value from PackageSettings
7911        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7912            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7913                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7914            }
7915        }
7916
7917        // TODO: extend to support forward-locked splits
7918        String resourcePath = null;
7919        String baseResourcePath = null;
7920        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7921            if (ps != null && ps.resourcePathString != null) {
7922                resourcePath = ps.resourcePathString;
7923                baseResourcePath = ps.resourcePathString;
7924            } else {
7925                // Should not happen at all. Just log an error.
7926                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7927            }
7928        } else {
7929            resourcePath = pkg.codePath;
7930            baseResourcePath = pkg.baseCodePath;
7931        }
7932
7933        // Set application objects path explicitly.
7934        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7935        pkg.setApplicationInfoCodePath(pkg.codePath);
7936        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7937        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7938        pkg.setApplicationInfoResourcePath(resourcePath);
7939        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7940        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7941
7942        final int userId = ((user == null) ? 0 : user.getIdentifier());
7943        if (ps != null && ps.getInstantApp(userId)) {
7944            scanFlags |= SCAN_AS_INSTANT_APP;
7945        }
7946
7947        // Note that we invoke the following method only if we are about to unpack an application
7948        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7949                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7950
7951        /*
7952         * If the system app should be overridden by a previously installed
7953         * data, hide the system app now and let the /data/app scan pick it up
7954         * again.
7955         */
7956        if (shouldHideSystemApp) {
7957            synchronized (mPackages) {
7958                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7959            }
7960        }
7961
7962        return scannedPkg;
7963    }
7964
7965    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7966        // Derive the new package synthetic package name
7967        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7968                + pkg.staticSharedLibVersion);
7969    }
7970
7971    private static String fixProcessName(String defProcessName,
7972            String processName) {
7973        if (processName == null) {
7974            return defProcessName;
7975        }
7976        return processName;
7977    }
7978
7979    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7980            throws PackageManagerException {
7981        if (pkgSetting.signatures.mSignatures != null) {
7982            // Already existing package. Make sure signatures match
7983            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7984                    == PackageManager.SIGNATURE_MATCH;
7985            if (!match) {
7986                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7987                        == PackageManager.SIGNATURE_MATCH;
7988            }
7989            if (!match) {
7990                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7991                        == PackageManager.SIGNATURE_MATCH;
7992            }
7993            if (!match) {
7994                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7995                        + pkg.packageName + " signatures do not match the "
7996                        + "previously installed version; ignoring!");
7997            }
7998        }
7999
8000        // Check for shared user signatures
8001        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8002            // Already existing package. Make sure signatures match
8003            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8004                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8005            if (!match) {
8006                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8007                        == PackageManager.SIGNATURE_MATCH;
8008            }
8009            if (!match) {
8010                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8011                        == PackageManager.SIGNATURE_MATCH;
8012            }
8013            if (!match) {
8014                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8015                        "Package " + pkg.packageName
8016                        + " has no signatures that match those in shared user "
8017                        + pkgSetting.sharedUser.name + "; ignoring!");
8018            }
8019        }
8020    }
8021
8022    /**
8023     * Enforces that only the system UID or root's UID can call a method exposed
8024     * via Binder.
8025     *
8026     * @param message used as message if SecurityException is thrown
8027     * @throws SecurityException if the caller is not system or root
8028     */
8029    private static final void enforceSystemOrRoot(String message) {
8030        final int uid = Binder.getCallingUid();
8031        if (uid != Process.SYSTEM_UID && uid != 0) {
8032            throw new SecurityException(message);
8033        }
8034    }
8035
8036    @Override
8037    public void performFstrimIfNeeded() {
8038        enforceSystemOrRoot("Only the system can request fstrim");
8039
8040        // Before everything else, see whether we need to fstrim.
8041        try {
8042            IStorageManager sm = PackageHelper.getStorageManager();
8043            if (sm != null) {
8044                boolean doTrim = false;
8045                final long interval = android.provider.Settings.Global.getLong(
8046                        mContext.getContentResolver(),
8047                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8048                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8049                if (interval > 0) {
8050                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8051                    if (timeSinceLast > interval) {
8052                        doTrim = true;
8053                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8054                                + "; running immediately");
8055                    }
8056                }
8057                if (doTrim) {
8058                    final boolean dexOptDialogShown;
8059                    synchronized (mPackages) {
8060                        dexOptDialogShown = mDexOptDialogShown;
8061                    }
8062                    if (!isFirstBoot() && dexOptDialogShown) {
8063                        try {
8064                            ActivityManager.getService().showBootMessage(
8065                                    mContext.getResources().getString(
8066                                            R.string.android_upgrading_fstrim), true);
8067                        } catch (RemoteException e) {
8068                        }
8069                    }
8070                    sm.runMaintenance();
8071                }
8072            } else {
8073                Slog.e(TAG, "storageManager service unavailable!");
8074            }
8075        } catch (RemoteException e) {
8076            // Can't happen; StorageManagerService is local
8077        }
8078    }
8079
8080    @Override
8081    public void updatePackagesIfNeeded() {
8082        enforceSystemOrRoot("Only the system can request package update");
8083
8084        // We need to re-extract after an OTA.
8085        boolean causeUpgrade = isUpgrade();
8086
8087        // First boot or factory reset.
8088        // Note: we also handle devices that are upgrading to N right now as if it is their
8089        //       first boot, as they do not have profile data.
8090        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8091
8092        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8093        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8094
8095        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8096            return;
8097        }
8098
8099        List<PackageParser.Package> pkgs;
8100        synchronized (mPackages) {
8101            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8102        }
8103
8104        final long startTime = System.nanoTime();
8105        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8106                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8107
8108        final int elapsedTimeSeconds =
8109                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8110
8111        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8112        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8113        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8114        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8115        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8116    }
8117
8118    /**
8119     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8120     * containing statistics about the invocation. The array consists of three elements,
8121     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8122     * and {@code numberOfPackagesFailed}.
8123     */
8124    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8125            String compilerFilter) {
8126
8127        int numberOfPackagesVisited = 0;
8128        int numberOfPackagesOptimized = 0;
8129        int numberOfPackagesSkipped = 0;
8130        int numberOfPackagesFailed = 0;
8131        final int numberOfPackagesToDexopt = pkgs.size();
8132
8133        for (PackageParser.Package pkg : pkgs) {
8134            numberOfPackagesVisited++;
8135
8136            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8137                if (DEBUG_DEXOPT) {
8138                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8139                }
8140                numberOfPackagesSkipped++;
8141                continue;
8142            }
8143
8144            if (DEBUG_DEXOPT) {
8145                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8146                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8147            }
8148
8149            if (showDialog) {
8150                try {
8151                    ActivityManager.getService().showBootMessage(
8152                            mContext.getResources().getString(R.string.android_upgrading_apk,
8153                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8154                } catch (RemoteException e) {
8155                }
8156                synchronized (mPackages) {
8157                    mDexOptDialogShown = true;
8158                }
8159            }
8160
8161            // If the OTA updates a system app which was previously preopted to a non-preopted state
8162            // the app might end up being verified at runtime. That's because by default the apps
8163            // are verify-profile but for preopted apps there's no profile.
8164            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8165            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8166            // filter (by default interpret-only).
8167            // Note that at this stage unused apps are already filtered.
8168            if (isSystemApp(pkg) &&
8169                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8170                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8171                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8172            }
8173
8174            // checkProfiles is false to avoid merging profiles during boot which
8175            // might interfere with background compilation (b/28612421).
8176            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8177            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8178            // trade-off worth doing to save boot time work.
8179            int dexOptStatus = performDexOptTraced(pkg.packageName,
8180                    false /* checkProfiles */,
8181                    compilerFilter,
8182                    false /* force */);
8183            switch (dexOptStatus) {
8184                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8185                    numberOfPackagesOptimized++;
8186                    break;
8187                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8188                    numberOfPackagesSkipped++;
8189                    break;
8190                case PackageDexOptimizer.DEX_OPT_FAILED:
8191                    numberOfPackagesFailed++;
8192                    break;
8193                default:
8194                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8195                    break;
8196            }
8197        }
8198
8199        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8200                numberOfPackagesFailed };
8201    }
8202
8203    @Override
8204    public void notifyPackageUse(String packageName, int reason) {
8205        synchronized (mPackages) {
8206            PackageParser.Package p = mPackages.get(packageName);
8207            if (p == null) {
8208                return;
8209            }
8210            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8211        }
8212    }
8213
8214    @Override
8215    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8216        int userId = UserHandle.getCallingUserId();
8217        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8218        if (ai == null) {
8219            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8220                + loadingPackageName + ", user=" + userId);
8221            return;
8222        }
8223        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8224    }
8225
8226    // TODO: this is not used nor needed. Delete it.
8227    @Override
8228    public boolean performDexOptIfNeeded(String packageName) {
8229        int dexOptStatus = performDexOptTraced(packageName,
8230                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8231        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8232    }
8233
8234    @Override
8235    public boolean performDexOpt(String packageName,
8236            boolean checkProfiles, int compileReason, boolean force) {
8237        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8238                getCompilerFilterForReason(compileReason), force);
8239        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8240    }
8241
8242    @Override
8243    public boolean performDexOptMode(String packageName,
8244            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8245        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8246                targetCompilerFilter, force);
8247        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8248    }
8249
8250    private int performDexOptTraced(String packageName,
8251                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8252        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8253        try {
8254            return performDexOptInternal(packageName, checkProfiles,
8255                    targetCompilerFilter, force);
8256        } finally {
8257            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8258        }
8259    }
8260
8261    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8262    // if the package can now be considered up to date for the given filter.
8263    private int performDexOptInternal(String packageName,
8264                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8265        PackageParser.Package p;
8266        synchronized (mPackages) {
8267            p = mPackages.get(packageName);
8268            if (p == null) {
8269                // Package could not be found. Report failure.
8270                return PackageDexOptimizer.DEX_OPT_FAILED;
8271            }
8272            mPackageUsage.maybeWriteAsync(mPackages);
8273            mCompilerStats.maybeWriteAsync();
8274        }
8275        long callingId = Binder.clearCallingIdentity();
8276        try {
8277            synchronized (mInstallLock) {
8278                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8279                        targetCompilerFilter, force);
8280            }
8281        } finally {
8282            Binder.restoreCallingIdentity(callingId);
8283        }
8284    }
8285
8286    public ArraySet<String> getOptimizablePackages() {
8287        ArraySet<String> pkgs = new ArraySet<String>();
8288        synchronized (mPackages) {
8289            for (PackageParser.Package p : mPackages.values()) {
8290                if (PackageDexOptimizer.canOptimizePackage(p)) {
8291                    pkgs.add(p.packageName);
8292                }
8293            }
8294        }
8295        return pkgs;
8296    }
8297
8298    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8299            boolean checkProfiles, String targetCompilerFilter,
8300            boolean force) {
8301        // Select the dex optimizer based on the force parameter.
8302        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8303        //       allocate an object here.
8304        PackageDexOptimizer pdo = force
8305                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8306                : mPackageDexOptimizer;
8307
8308        // Optimize all dependencies first. Note: we ignore the return value and march on
8309        // on errors.
8310        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8311        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8312        if (!deps.isEmpty()) {
8313            for (PackageParser.Package depPackage : deps) {
8314                // TODO: Analyze and investigate if we (should) profile libraries.
8315                // Currently this will do a full compilation of the library by default.
8316                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8317                        false /* checkProfiles */,
8318                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8319                        getOrCreateCompilerPackageStats(depPackage));
8320            }
8321        }
8322        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8323                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8324    }
8325
8326    // Performs dexopt on the used secondary dex files belonging to the given package.
8327    // Returns true if all dex files were process successfully (which could mean either dexopt or
8328    // skip). Returns false if any of the files caused errors.
8329    @Override
8330    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8331            boolean force) {
8332        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8333    }
8334
8335    /**
8336     * Reconcile the information we have about the secondary dex files belonging to
8337     * {@code packagName} and the actual dex files. For all dex files that were
8338     * deleted, update the internal records and delete the generated oat files.
8339     */
8340    @Override
8341    public void reconcileSecondaryDexFiles(String packageName) {
8342        mDexManager.reconcileSecondaryDexFiles(packageName);
8343    }
8344
8345    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8346    // a reference there.
8347    /*package*/ DexManager getDexManager() {
8348        return mDexManager;
8349    }
8350
8351    /**
8352     * Execute the background dexopt job immediately.
8353     */
8354    @Override
8355    public boolean runBackgroundDexoptJob() {
8356        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8357    }
8358
8359    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8360        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8361                || p.usesStaticLibraries != null) {
8362            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8363            Set<String> collectedNames = new HashSet<>();
8364            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8365
8366            retValue.remove(p);
8367
8368            return retValue;
8369        } else {
8370            return Collections.emptyList();
8371        }
8372    }
8373
8374    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8375            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8376        if (!collectedNames.contains(p.packageName)) {
8377            collectedNames.add(p.packageName);
8378            collected.add(p);
8379
8380            if (p.usesLibraries != null) {
8381                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8382                        null, collected, collectedNames);
8383            }
8384            if (p.usesOptionalLibraries != null) {
8385                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8386                        null, collected, collectedNames);
8387            }
8388            if (p.usesStaticLibraries != null) {
8389                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8390                        p.usesStaticLibrariesVersions, collected, collectedNames);
8391            }
8392        }
8393    }
8394
8395    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8396            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8397        final int libNameCount = libs.size();
8398        for (int i = 0; i < libNameCount; i++) {
8399            String libName = libs.get(i);
8400            int version = (versions != null && versions.length == libNameCount)
8401                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8402            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8403            if (libPkg != null) {
8404                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8405            }
8406        }
8407    }
8408
8409    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8410        synchronized (mPackages) {
8411            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8412            if (libEntry != null) {
8413                return mPackages.get(libEntry.apk);
8414            }
8415            return null;
8416        }
8417    }
8418
8419    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8420        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8421        if (versionedLib == null) {
8422            return null;
8423        }
8424        return versionedLib.get(version);
8425    }
8426
8427    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8428        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8429                pkg.staticSharedLibName);
8430        if (versionedLib == null) {
8431            return null;
8432        }
8433        int previousLibVersion = -1;
8434        final int versionCount = versionedLib.size();
8435        for (int i = 0; i < versionCount; i++) {
8436            final int libVersion = versionedLib.keyAt(i);
8437            if (libVersion < pkg.staticSharedLibVersion) {
8438                previousLibVersion = Math.max(previousLibVersion, libVersion);
8439            }
8440        }
8441        if (previousLibVersion >= 0) {
8442            return versionedLib.get(previousLibVersion);
8443        }
8444        return null;
8445    }
8446
8447    public void shutdown() {
8448        mPackageUsage.writeNow(mPackages);
8449        mCompilerStats.writeNow();
8450    }
8451
8452    @Override
8453    public void dumpProfiles(String packageName) {
8454        PackageParser.Package pkg;
8455        synchronized (mPackages) {
8456            pkg = mPackages.get(packageName);
8457            if (pkg == null) {
8458                throw new IllegalArgumentException("Unknown package: " + packageName);
8459            }
8460        }
8461        /* Only the shell, root, or the app user should be able to dump profiles. */
8462        int callingUid = Binder.getCallingUid();
8463        if (callingUid != Process.SHELL_UID &&
8464            callingUid != Process.ROOT_UID &&
8465            callingUid != pkg.applicationInfo.uid) {
8466            throw new SecurityException("dumpProfiles");
8467        }
8468
8469        synchronized (mInstallLock) {
8470            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8471            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8472            try {
8473                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8474                String codePaths = TextUtils.join(";", allCodePaths);
8475                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8476            } catch (InstallerException e) {
8477                Slog.w(TAG, "Failed to dump profiles", e);
8478            }
8479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8480        }
8481    }
8482
8483    @Override
8484    public void forceDexOpt(String packageName) {
8485        enforceSystemOrRoot("forceDexOpt");
8486
8487        PackageParser.Package pkg;
8488        synchronized (mPackages) {
8489            pkg = mPackages.get(packageName);
8490            if (pkg == null) {
8491                throw new IllegalArgumentException("Unknown package: " + packageName);
8492            }
8493        }
8494
8495        synchronized (mInstallLock) {
8496            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8497
8498            // Whoever is calling forceDexOpt wants a fully compiled package.
8499            // Don't use profiles since that may cause compilation to be skipped.
8500            final int res = performDexOptInternalWithDependenciesLI(pkg,
8501                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8502                    true /* force */);
8503
8504            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8505            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8506                throw new IllegalStateException("Failed to dexopt: " + res);
8507            }
8508        }
8509    }
8510
8511    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8512        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8513            Slog.w(TAG, "Unable to update from " + oldPkg.name
8514                    + " to " + newPkg.packageName
8515                    + ": old package not in system partition");
8516            return false;
8517        } else if (mPackages.get(oldPkg.name) != null) {
8518            Slog.w(TAG, "Unable to update from " + oldPkg.name
8519                    + " to " + newPkg.packageName
8520                    + ": old package still exists");
8521            return false;
8522        }
8523        return true;
8524    }
8525
8526    void removeCodePathLI(File codePath) {
8527        if (codePath.isDirectory()) {
8528            try {
8529                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8530            } catch (InstallerException e) {
8531                Slog.w(TAG, "Failed to remove code path", e);
8532            }
8533        } else {
8534            codePath.delete();
8535        }
8536    }
8537
8538    private int[] resolveUserIds(int userId) {
8539        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8540    }
8541
8542    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8543        if (pkg == null) {
8544            Slog.wtf(TAG, "Package was null!", new Throwable());
8545            return;
8546        }
8547        clearAppDataLeafLIF(pkg, userId, flags);
8548        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8549        for (int i = 0; i < childCount; i++) {
8550            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8551        }
8552    }
8553
8554    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8555        final PackageSetting ps;
8556        synchronized (mPackages) {
8557            ps = mSettings.mPackages.get(pkg.packageName);
8558        }
8559        for (int realUserId : resolveUserIds(userId)) {
8560            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8561            try {
8562                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8563                        ceDataInode);
8564            } catch (InstallerException e) {
8565                Slog.w(TAG, String.valueOf(e));
8566            }
8567        }
8568    }
8569
8570    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8571        if (pkg == null) {
8572            Slog.wtf(TAG, "Package was null!", new Throwable());
8573            return;
8574        }
8575        destroyAppDataLeafLIF(pkg, userId, flags);
8576        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8577        for (int i = 0; i < childCount; i++) {
8578            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8579        }
8580    }
8581
8582    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8583        final PackageSetting ps;
8584        synchronized (mPackages) {
8585            ps = mSettings.mPackages.get(pkg.packageName);
8586        }
8587        for (int realUserId : resolveUserIds(userId)) {
8588            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8589            try {
8590                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8591                        ceDataInode);
8592            } catch (InstallerException e) {
8593                Slog.w(TAG, String.valueOf(e));
8594            }
8595            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8596        }
8597    }
8598
8599    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8600        if (pkg == null) {
8601            Slog.wtf(TAG, "Package was null!", new Throwable());
8602            return;
8603        }
8604        destroyAppProfilesLeafLIF(pkg);
8605        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8606        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8607        for (int i = 0; i < childCount; i++) {
8608            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8609            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8610                    true /* removeBaseMarker */);
8611        }
8612    }
8613
8614    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8615            boolean removeBaseMarker) {
8616        if (pkg.isForwardLocked()) {
8617            return;
8618        }
8619
8620        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8621            try {
8622                path = PackageManagerServiceUtils.realpath(new File(path));
8623            } catch (IOException e) {
8624                // TODO: Should we return early here ?
8625                Slog.w(TAG, "Failed to get canonical path", e);
8626                continue;
8627            }
8628
8629            final String useMarker = path.replace('/', '@');
8630            for (int realUserId : resolveUserIds(userId)) {
8631                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8632                if (removeBaseMarker) {
8633                    File foreignUseMark = new File(profileDir, useMarker);
8634                    if (foreignUseMark.exists()) {
8635                        if (!foreignUseMark.delete()) {
8636                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8637                                    + pkg.packageName);
8638                        }
8639                    }
8640                }
8641
8642                File[] markers = profileDir.listFiles();
8643                if (markers != null) {
8644                    final String searchString = "@" + pkg.packageName + "@";
8645                    // We also delete all markers that contain the package name we're
8646                    // uninstalling. These are associated with secondary dex-files belonging
8647                    // to the package. Reconstructing the path of these dex files is messy
8648                    // in general.
8649                    for (File marker : markers) {
8650                        if (marker.getName().indexOf(searchString) > 0) {
8651                            if (!marker.delete()) {
8652                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8653                                    + pkg.packageName);
8654                            }
8655                        }
8656                    }
8657                }
8658            }
8659        }
8660    }
8661
8662    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8663        try {
8664            mInstaller.destroyAppProfiles(pkg.packageName);
8665        } catch (InstallerException e) {
8666            Slog.w(TAG, String.valueOf(e));
8667        }
8668    }
8669
8670    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8671        if (pkg == null) {
8672            Slog.wtf(TAG, "Package was null!", new Throwable());
8673            return;
8674        }
8675        clearAppProfilesLeafLIF(pkg);
8676        // We don't remove the base foreign use marker when clearing profiles because
8677        // we will rename it when the app is updated. Unlike the actual profile contents,
8678        // the foreign use marker is good across installs.
8679        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8680        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8681        for (int i = 0; i < childCount; i++) {
8682            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8683        }
8684    }
8685
8686    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8687        try {
8688            mInstaller.clearAppProfiles(pkg.packageName);
8689        } catch (InstallerException e) {
8690            Slog.w(TAG, String.valueOf(e));
8691        }
8692    }
8693
8694    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8695            long lastUpdateTime) {
8696        // Set parent install/update time
8697        PackageSetting ps = (PackageSetting) pkg.mExtras;
8698        if (ps != null) {
8699            ps.firstInstallTime = firstInstallTime;
8700            ps.lastUpdateTime = lastUpdateTime;
8701        }
8702        // Set children install/update time
8703        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8704        for (int i = 0; i < childCount; i++) {
8705            PackageParser.Package childPkg = pkg.childPackages.get(i);
8706            ps = (PackageSetting) childPkg.mExtras;
8707            if (ps != null) {
8708                ps.firstInstallTime = firstInstallTime;
8709                ps.lastUpdateTime = lastUpdateTime;
8710            }
8711        }
8712    }
8713
8714    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8715            PackageParser.Package changingLib) {
8716        if (file.path != null) {
8717            usesLibraryFiles.add(file.path);
8718            return;
8719        }
8720        PackageParser.Package p = mPackages.get(file.apk);
8721        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8722            // If we are doing this while in the middle of updating a library apk,
8723            // then we need to make sure to use that new apk for determining the
8724            // dependencies here.  (We haven't yet finished committing the new apk
8725            // to the package manager state.)
8726            if (p == null || p.packageName.equals(changingLib.packageName)) {
8727                p = changingLib;
8728            }
8729        }
8730        if (p != null) {
8731            usesLibraryFiles.addAll(p.getAllCodePaths());
8732        }
8733    }
8734
8735    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8736            PackageParser.Package changingLib) throws PackageManagerException {
8737        if (pkg == null) {
8738            return;
8739        }
8740        ArraySet<String> usesLibraryFiles = null;
8741        if (pkg.usesLibraries != null) {
8742            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8743                    null, null, pkg.packageName, changingLib, true, null);
8744        }
8745        if (pkg.usesStaticLibraries != null) {
8746            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8747                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8748                    pkg.packageName, changingLib, true, usesLibraryFiles);
8749        }
8750        if (pkg.usesOptionalLibraries != null) {
8751            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8752                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8753        }
8754        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8755            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8756        } else {
8757            pkg.usesLibraryFiles = null;
8758        }
8759    }
8760
8761    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8762            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8763            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8764            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8765            throws PackageManagerException {
8766        final int libCount = requestedLibraries.size();
8767        for (int i = 0; i < libCount; i++) {
8768            final String libName = requestedLibraries.get(i);
8769            final int libVersion = requiredVersions != null ? requiredVersions[i]
8770                    : SharedLibraryInfo.VERSION_UNDEFINED;
8771            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8772            if (libEntry == null) {
8773                if (required) {
8774                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8775                            "Package " + packageName + " requires unavailable shared library "
8776                                    + libName + "; failing!");
8777                } else {
8778                    Slog.w(TAG, "Package " + packageName
8779                            + " desires unavailable shared library "
8780                            + libName + "; ignoring!");
8781                }
8782            } else {
8783                if (requiredVersions != null && requiredCertDigests != null) {
8784                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8785                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8786                            "Package " + packageName + " requires unavailable static shared"
8787                                    + " library " + libName + " version "
8788                                    + libEntry.info.getVersion() + "; failing!");
8789                    }
8790
8791                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8792                    if (libPkg == null) {
8793                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8794                                "Package " + packageName + " requires unavailable static shared"
8795                                        + " library; failing!");
8796                    }
8797
8798                    String expectedCertDigest = requiredCertDigests[i];
8799                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8800                                libPkg.mSignatures[0]);
8801                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8802                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8803                                "Package " + packageName + " requires differently signed" +
8804                                        " static shared library; failing!");
8805                    }
8806                }
8807
8808                if (outUsedLibraries == null) {
8809                    outUsedLibraries = new ArraySet<>();
8810                }
8811                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8812            }
8813        }
8814        return outUsedLibraries;
8815    }
8816
8817    private static boolean hasString(List<String> list, List<String> which) {
8818        if (list == null) {
8819            return false;
8820        }
8821        for (int i=list.size()-1; i>=0; i--) {
8822            for (int j=which.size()-1; j>=0; j--) {
8823                if (which.get(j).equals(list.get(i))) {
8824                    return true;
8825                }
8826            }
8827        }
8828        return false;
8829    }
8830
8831    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8832            PackageParser.Package changingPkg) {
8833        ArrayList<PackageParser.Package> res = null;
8834        for (PackageParser.Package pkg : mPackages.values()) {
8835            if (changingPkg != null
8836                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8837                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8838                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8839                            changingPkg.staticSharedLibName)) {
8840                return null;
8841            }
8842            if (res == null) {
8843                res = new ArrayList<>();
8844            }
8845            res.add(pkg);
8846            try {
8847                updateSharedLibrariesLPr(pkg, changingPkg);
8848            } catch (PackageManagerException e) {
8849                // If a system app update or an app and a required lib missing we
8850                // delete the package and for updated system apps keep the data as
8851                // it is better for the user to reinstall than to be in an limbo
8852                // state. Also libs disappearing under an app should never happen
8853                // - just in case.
8854                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8855                    final int flags = pkg.isUpdatedSystemApp()
8856                            ? PackageManager.DELETE_KEEP_DATA : 0;
8857                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8858                            flags , null, true, null);
8859                }
8860                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8861            }
8862        }
8863        return res;
8864    }
8865
8866    /**
8867     * Derive the value of the {@code cpuAbiOverride} based on the provided
8868     * value and an optional stored value from the package settings.
8869     */
8870    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8871        String cpuAbiOverride = null;
8872
8873        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8874            cpuAbiOverride = null;
8875        } else if (abiOverride != null) {
8876            cpuAbiOverride = abiOverride;
8877        } else if (settings != null) {
8878            cpuAbiOverride = settings.cpuAbiOverrideString;
8879        }
8880
8881        return cpuAbiOverride;
8882    }
8883
8884    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8885            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8886                    throws PackageManagerException {
8887        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8888        // If the package has children and this is the first dive in the function
8889        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8890        // whether all packages (parent and children) would be successfully scanned
8891        // before the actual scan since scanning mutates internal state and we want
8892        // to atomically install the package and its children.
8893        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8894            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8895                scanFlags |= SCAN_CHECK_ONLY;
8896            }
8897        } else {
8898            scanFlags &= ~SCAN_CHECK_ONLY;
8899        }
8900
8901        final PackageParser.Package scannedPkg;
8902        try {
8903            // Scan the parent
8904            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8905            // Scan the children
8906            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8907            for (int i = 0; i < childCount; i++) {
8908                PackageParser.Package childPkg = pkg.childPackages.get(i);
8909                scanPackageLI(childPkg, policyFlags,
8910                        scanFlags, currentTime, user);
8911            }
8912        } finally {
8913            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8914        }
8915
8916        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8917            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8918        }
8919
8920        return scannedPkg;
8921    }
8922
8923    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8924            int scanFlags, long currentTime, @Nullable UserHandle user)
8925                    throws PackageManagerException {
8926        boolean success = false;
8927        try {
8928            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8929                    currentTime, user);
8930            success = true;
8931            return res;
8932        } finally {
8933            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8934                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8935                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8936                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8937                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8938            }
8939        }
8940    }
8941
8942    /**
8943     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8944     */
8945    private static boolean apkHasCode(String fileName) {
8946        StrictJarFile jarFile = null;
8947        try {
8948            jarFile = new StrictJarFile(fileName,
8949                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8950            return jarFile.findEntry("classes.dex") != null;
8951        } catch (IOException ignore) {
8952        } finally {
8953            try {
8954                if (jarFile != null) {
8955                    jarFile.close();
8956                }
8957            } catch (IOException ignore) {}
8958        }
8959        return false;
8960    }
8961
8962    /**
8963     * Enforces code policy for the package. This ensures that if an APK has
8964     * declared hasCode="true" in its manifest that the APK actually contains
8965     * code.
8966     *
8967     * @throws PackageManagerException If bytecode could not be found when it should exist
8968     */
8969    private static void assertCodePolicy(PackageParser.Package pkg)
8970            throws PackageManagerException {
8971        final boolean shouldHaveCode =
8972                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8973        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8974            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8975                    "Package " + pkg.baseCodePath + " code is missing");
8976        }
8977
8978        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8979            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8980                final boolean splitShouldHaveCode =
8981                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8982                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8983                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8984                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8985                }
8986            }
8987        }
8988    }
8989
8990    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8991            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
8992                    throws PackageManagerException {
8993        if (DEBUG_PACKAGE_SCANNING) {
8994            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8995                Log.d(TAG, "Scanning package " + pkg.packageName);
8996        }
8997
8998        applyPolicy(pkg, policyFlags);
8999
9000        assertPackageIsValid(pkg, policyFlags, scanFlags);
9001
9002        // Initialize package source and resource directories
9003        final File scanFile = new File(pkg.codePath);
9004        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9005        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9006
9007        SharedUserSetting suid = null;
9008        PackageSetting pkgSetting = null;
9009
9010        // Getting the package setting may have a side-effect, so if we
9011        // are only checking if scan would succeed, stash a copy of the
9012        // old setting to restore at the end.
9013        PackageSetting nonMutatedPs = null;
9014
9015        // We keep references to the derived CPU Abis from settings in oder to reuse
9016        // them in the case where we're not upgrading or booting for the first time.
9017        String primaryCpuAbiFromSettings = null;
9018        String secondaryCpuAbiFromSettings = null;
9019
9020        // writer
9021        synchronized (mPackages) {
9022            if (pkg.mSharedUserId != null) {
9023                // SIDE EFFECTS; may potentially allocate a new shared user
9024                suid = mSettings.getSharedUserLPw(
9025                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9026                if (DEBUG_PACKAGE_SCANNING) {
9027                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9028                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9029                                + "): packages=" + suid.packages);
9030                }
9031            }
9032
9033            // Check if we are renaming from an original package name.
9034            PackageSetting origPackage = null;
9035            String realName = null;
9036            if (pkg.mOriginalPackages != null) {
9037                // This package may need to be renamed to a previously
9038                // installed name.  Let's check on that...
9039                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9040                if (pkg.mOriginalPackages.contains(renamed)) {
9041                    // This package had originally been installed as the
9042                    // original name, and we have already taken care of
9043                    // transitioning to the new one.  Just update the new
9044                    // one to continue using the old name.
9045                    realName = pkg.mRealPackage;
9046                    if (!pkg.packageName.equals(renamed)) {
9047                        // Callers into this function may have already taken
9048                        // care of renaming the package; only do it here if
9049                        // it is not already done.
9050                        pkg.setPackageName(renamed);
9051                    }
9052                } else {
9053                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9054                        if ((origPackage = mSettings.getPackageLPr(
9055                                pkg.mOriginalPackages.get(i))) != null) {
9056                            // We do have the package already installed under its
9057                            // original name...  should we use it?
9058                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9059                                // New package is not compatible with original.
9060                                origPackage = null;
9061                                continue;
9062                            } else if (origPackage.sharedUser != null) {
9063                                // Make sure uid is compatible between packages.
9064                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9065                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9066                                            + " to " + pkg.packageName + ": old uid "
9067                                            + origPackage.sharedUser.name
9068                                            + " differs from " + pkg.mSharedUserId);
9069                                    origPackage = null;
9070                                    continue;
9071                                }
9072                                // TODO: Add case when shared user id is added [b/28144775]
9073                            } else {
9074                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9075                                        + pkg.packageName + " to old name " + origPackage.name);
9076                            }
9077                            break;
9078                        }
9079                    }
9080                }
9081            }
9082
9083            if (mTransferedPackages.contains(pkg.packageName)) {
9084                Slog.w(TAG, "Package " + pkg.packageName
9085                        + " was transferred to another, but its .apk remains");
9086            }
9087
9088            // See comments in nonMutatedPs declaration
9089            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9090                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9091                if (foundPs != null) {
9092                    nonMutatedPs = new PackageSetting(foundPs);
9093                }
9094            }
9095
9096            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9097                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9098                if (foundPs != null) {
9099                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9100                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9101                }
9102            }
9103
9104            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9105            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9106                PackageManagerService.reportSettingsProblem(Log.WARN,
9107                        "Package " + pkg.packageName + " shared user changed from "
9108                                + (pkgSetting.sharedUser != null
9109                                        ? pkgSetting.sharedUser.name : "<nothing>")
9110                                + " to "
9111                                + (suid != null ? suid.name : "<nothing>")
9112                                + "; replacing with new");
9113                pkgSetting = null;
9114            }
9115            final PackageSetting oldPkgSetting =
9116                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9117            final PackageSetting disabledPkgSetting =
9118                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9119
9120            String[] usesStaticLibraries = null;
9121            if (pkg.usesStaticLibraries != null) {
9122                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9123                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9124            }
9125
9126            if (pkgSetting == null) {
9127                final String parentPackageName = (pkg.parentPackage != null)
9128                        ? pkg.parentPackage.packageName : null;
9129                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9130                // REMOVE SharedUserSetting from method; update in a separate call
9131                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9132                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9133                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9134                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9135                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9136                        true /*allowInstall*/, instantApp, parentPackageName,
9137                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9138                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9139                // SIDE EFFECTS; updates system state; move elsewhere
9140                if (origPackage != null) {
9141                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9142                }
9143                mSettings.addUserToSettingLPw(pkgSetting);
9144            } else {
9145                // REMOVE SharedUserSetting from method; update in a separate call.
9146                //
9147                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9148                // secondaryCpuAbi are not known at this point so we always update them
9149                // to null here, only to reset them at a later point.
9150                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9151                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9152                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9153                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9154                        UserManagerService.getInstance(), usesStaticLibraries,
9155                        pkg.usesStaticLibrariesVersions);
9156            }
9157            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9158            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9159
9160            // SIDE EFFECTS; modifies system state; move elsewhere
9161            if (pkgSetting.origPackage != null) {
9162                // If we are first transitioning from an original package,
9163                // fix up the new package's name now.  We need to do this after
9164                // looking up the package under its new name, so getPackageLP
9165                // can take care of fiddling things correctly.
9166                pkg.setPackageName(origPackage.name);
9167
9168                // File a report about this.
9169                String msg = "New package " + pkgSetting.realName
9170                        + " renamed to replace old package " + pkgSetting.name;
9171                reportSettingsProblem(Log.WARN, msg);
9172
9173                // Make a note of it.
9174                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9175                    mTransferedPackages.add(origPackage.name);
9176                }
9177
9178                // No longer need to retain this.
9179                pkgSetting.origPackage = null;
9180            }
9181
9182            // SIDE EFFECTS; modifies system state; move elsewhere
9183            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9184                // Make a note of it.
9185                mTransferedPackages.add(pkg.packageName);
9186            }
9187
9188            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9189                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9190            }
9191
9192            if ((scanFlags & SCAN_BOOTING) == 0
9193                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9194                // Check all shared libraries and map to their actual file path.
9195                // We only do this here for apps not on a system dir, because those
9196                // are the only ones that can fail an install due to this.  We
9197                // will take care of the system apps by updating all of their
9198                // library paths after the scan is done. Also during the initial
9199                // scan don't update any libs as we do this wholesale after all
9200                // apps are scanned to avoid dependency based scanning.
9201                updateSharedLibrariesLPr(pkg, null);
9202            }
9203
9204            if (mFoundPolicyFile) {
9205                SELinuxMMAC.assignSeInfoValue(pkg);
9206            }
9207            pkg.applicationInfo.uid = pkgSetting.appId;
9208            pkg.mExtras = pkgSetting;
9209
9210
9211            // Static shared libs have same package with different versions where
9212            // we internally use a synthetic package name to allow multiple versions
9213            // of the same package, therefore we need to compare signatures against
9214            // the package setting for the latest library version.
9215            PackageSetting signatureCheckPs = pkgSetting;
9216            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9217                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9218                if (libraryEntry != null) {
9219                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9220                }
9221            }
9222
9223            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9224                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9225                    // We just determined the app is signed correctly, so bring
9226                    // over the latest parsed certs.
9227                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9228                } else {
9229                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9230                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9231                                "Package " + pkg.packageName + " upgrade keys do not match the "
9232                                + "previously installed version");
9233                    } else {
9234                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9235                        String msg = "System package " + pkg.packageName
9236                                + " signature changed; retaining data.";
9237                        reportSettingsProblem(Log.WARN, msg);
9238                    }
9239                }
9240            } else {
9241                try {
9242                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9243                    verifySignaturesLP(signatureCheckPs, pkg);
9244                    // We just determined the app is signed correctly, so bring
9245                    // over the latest parsed certs.
9246                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9247                } catch (PackageManagerException e) {
9248                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9249                        throw e;
9250                    }
9251                    // The signature has changed, but this package is in the system
9252                    // image...  let's recover!
9253                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9254                    // However...  if this package is part of a shared user, but it
9255                    // doesn't match the signature of the shared user, let's fail.
9256                    // What this means is that you can't change the signatures
9257                    // associated with an overall shared user, which doesn't seem all
9258                    // that unreasonable.
9259                    if (signatureCheckPs.sharedUser != null) {
9260                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9261                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9262                            throw new PackageManagerException(
9263                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9264                                    "Signature mismatch for shared user: "
9265                                            + pkgSetting.sharedUser);
9266                        }
9267                    }
9268                    // File a report about this.
9269                    String msg = "System package " + pkg.packageName
9270                            + " signature changed; retaining data.";
9271                    reportSettingsProblem(Log.WARN, msg);
9272                }
9273            }
9274
9275            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9276                // This package wants to adopt ownership of permissions from
9277                // another package.
9278                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9279                    final String origName = pkg.mAdoptPermissions.get(i);
9280                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9281                    if (orig != null) {
9282                        if (verifyPackageUpdateLPr(orig, pkg)) {
9283                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9284                                    + pkg.packageName);
9285                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9286                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9287                        }
9288                    }
9289                }
9290            }
9291        }
9292
9293        pkg.applicationInfo.processName = fixProcessName(
9294                pkg.applicationInfo.packageName,
9295                pkg.applicationInfo.processName);
9296
9297        if (pkg != mPlatformPackage) {
9298            // Get all of our default paths setup
9299            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9300        }
9301
9302        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9303
9304        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9305            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9306                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9307                derivePackageAbi(
9308                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9309                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9310
9311                // Some system apps still use directory structure for native libraries
9312                // in which case we might end up not detecting abi solely based on apk
9313                // structure. Try to detect abi based on directory structure.
9314                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9315                        pkg.applicationInfo.primaryCpuAbi == null) {
9316                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9317                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9318                }
9319            } else {
9320                // This is not a first boot or an upgrade, don't bother deriving the
9321                // ABI during the scan. Instead, trust the value that was stored in the
9322                // package setting.
9323                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9324                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9325
9326                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9327
9328                if (DEBUG_ABI_SELECTION) {
9329                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9330                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9331                        pkg.applicationInfo.secondaryCpuAbi);
9332                }
9333            }
9334        } else {
9335            if ((scanFlags & SCAN_MOVE) != 0) {
9336                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9337                // but we already have this packages package info in the PackageSetting. We just
9338                // use that and derive the native library path based on the new codepath.
9339                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9340                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9341            }
9342
9343            // Set native library paths again. For moves, the path will be updated based on the
9344            // ABIs we've determined above. For non-moves, the path will be updated based on the
9345            // ABIs we determined during compilation, but the path will depend on the final
9346            // package path (after the rename away from the stage path).
9347            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9348        }
9349
9350        // This is a special case for the "system" package, where the ABI is
9351        // dictated by the zygote configuration (and init.rc). We should keep track
9352        // of this ABI so that we can deal with "normal" applications that run under
9353        // the same UID correctly.
9354        if (mPlatformPackage == pkg) {
9355            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9356                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9357        }
9358
9359        // If there's a mismatch between the abi-override in the package setting
9360        // and the abiOverride specified for the install. Warn about this because we
9361        // would've already compiled the app without taking the package setting into
9362        // account.
9363        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9364            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9365                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9366                        " for package " + pkg.packageName);
9367            }
9368        }
9369
9370        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9371        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9372        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9373
9374        // Copy the derived override back to the parsed package, so that we can
9375        // update the package settings accordingly.
9376        pkg.cpuAbiOverride = cpuAbiOverride;
9377
9378        if (DEBUG_ABI_SELECTION) {
9379            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9380                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9381                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9382        }
9383
9384        // Push the derived path down into PackageSettings so we know what to
9385        // clean up at uninstall time.
9386        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9387
9388        if (DEBUG_ABI_SELECTION) {
9389            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9390                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9391                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9392        }
9393
9394        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9395        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9396            // We don't do this here during boot because we can do it all
9397            // at once after scanning all existing packages.
9398            //
9399            // We also do this *before* we perform dexopt on this package, so that
9400            // we can avoid redundant dexopts, and also to make sure we've got the
9401            // code and package path correct.
9402            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9403        }
9404
9405        if (mFactoryTest && pkg.requestedPermissions.contains(
9406                android.Manifest.permission.FACTORY_TEST)) {
9407            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9408        }
9409
9410        if (isSystemApp(pkg)) {
9411            pkgSetting.isOrphaned = true;
9412        }
9413
9414        // Take care of first install / last update times.
9415        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9416        if (currentTime != 0) {
9417            if (pkgSetting.firstInstallTime == 0) {
9418                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9419            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9420                pkgSetting.lastUpdateTime = currentTime;
9421            }
9422        } else if (pkgSetting.firstInstallTime == 0) {
9423            // We need *something*.  Take time time stamp of the file.
9424            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9425        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9426            if (scanFileTime != pkgSetting.timeStamp) {
9427                // A package on the system image has changed; consider this
9428                // to be an update.
9429                pkgSetting.lastUpdateTime = scanFileTime;
9430            }
9431        }
9432        pkgSetting.setTimeStamp(scanFileTime);
9433
9434        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9435            if (nonMutatedPs != null) {
9436                synchronized (mPackages) {
9437                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9438                }
9439            }
9440        } else {
9441            final int userId = user == null ? 0 : user.getIdentifier();
9442            // Modify state for the given package setting
9443            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9444                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9445            if (pkgSetting.getInstantApp(userId)) {
9446                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9447            }
9448        }
9449        return pkg;
9450    }
9451
9452    /**
9453     * Applies policy to the parsed package based upon the given policy flags.
9454     * Ensures the package is in a good state.
9455     * <p>
9456     * Implementation detail: This method must NOT have any side effect. It would
9457     * ideally be static, but, it requires locks to read system state.
9458     */
9459    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9460        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9461            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9462            if (pkg.applicationInfo.isDirectBootAware()) {
9463                // we're direct boot aware; set for all components
9464                for (PackageParser.Service s : pkg.services) {
9465                    s.info.encryptionAware = s.info.directBootAware = true;
9466                }
9467                for (PackageParser.Provider p : pkg.providers) {
9468                    p.info.encryptionAware = p.info.directBootAware = true;
9469                }
9470                for (PackageParser.Activity a : pkg.activities) {
9471                    a.info.encryptionAware = a.info.directBootAware = true;
9472                }
9473                for (PackageParser.Activity r : pkg.receivers) {
9474                    r.info.encryptionAware = r.info.directBootAware = true;
9475                }
9476            }
9477        } else {
9478            // Only allow system apps to be flagged as core apps.
9479            pkg.coreApp = false;
9480            // clear flags not applicable to regular apps
9481            pkg.applicationInfo.privateFlags &=
9482                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9483            pkg.applicationInfo.privateFlags &=
9484                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9485        }
9486        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9487
9488        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9489            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9490        }
9491
9492        if (!isSystemApp(pkg)) {
9493            // Only system apps can use these features.
9494            pkg.mOriginalPackages = null;
9495            pkg.mRealPackage = null;
9496            pkg.mAdoptPermissions = null;
9497        }
9498    }
9499
9500    /**
9501     * Asserts the parsed package is valid according to the given policy. If the
9502     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9503     * <p>
9504     * Implementation detail: This method must NOT have any side effects. It would
9505     * ideally be static, but, it requires locks to read system state.
9506     *
9507     * @throws PackageManagerException If the package fails any of the validation checks
9508     */
9509    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9510            throws PackageManagerException {
9511        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9512            assertCodePolicy(pkg);
9513        }
9514
9515        if (pkg.applicationInfo.getCodePath() == null ||
9516                pkg.applicationInfo.getResourcePath() == null) {
9517            // Bail out. The resource and code paths haven't been set.
9518            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9519                    "Code and resource paths haven't been set correctly");
9520        }
9521
9522        // Make sure we're not adding any bogus keyset info
9523        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9524        ksms.assertScannedPackageValid(pkg);
9525
9526        synchronized (mPackages) {
9527            // The special "android" package can only be defined once
9528            if (pkg.packageName.equals("android")) {
9529                if (mAndroidApplication != null) {
9530                    Slog.w(TAG, "*************************************************");
9531                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9532                    Slog.w(TAG, " codePath=" + pkg.codePath);
9533                    Slog.w(TAG, "*************************************************");
9534                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9535                            "Core android package being redefined.  Skipping.");
9536                }
9537            }
9538
9539            // A package name must be unique; don't allow duplicates
9540            if (mPackages.containsKey(pkg.packageName)) {
9541                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9542                        "Application package " + pkg.packageName
9543                        + " already installed.  Skipping duplicate.");
9544            }
9545
9546            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9547                // Static libs have a synthetic package name containing the version
9548                // but we still want the base name to be unique.
9549                if (mPackages.containsKey(pkg.manifestPackageName)) {
9550                    throw new PackageManagerException(
9551                            "Duplicate static shared lib provider package");
9552                }
9553
9554                // Static shared libraries should have at least O target SDK
9555                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9556                    throw new PackageManagerException(
9557                            "Packages declaring static-shared libs must target O SDK or higher");
9558                }
9559
9560                // Package declaring static a shared lib cannot be instant apps
9561                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9562                    throw new PackageManagerException(
9563                            "Packages declaring static-shared libs cannot be instant apps");
9564                }
9565
9566                // Package declaring static a shared lib cannot be renamed since the package
9567                // name is synthetic and apps can't code around package manager internals.
9568                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9569                    throw new PackageManagerException(
9570                            "Packages declaring static-shared libs cannot be renamed");
9571                }
9572
9573                // Package declaring static a shared lib cannot declare child packages
9574                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9575                    throw new PackageManagerException(
9576                            "Packages declaring static-shared libs cannot have child packages");
9577                }
9578
9579                // Package declaring static a shared lib cannot declare dynamic libs
9580                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9581                    throw new PackageManagerException(
9582                            "Packages declaring static-shared libs cannot declare dynamic libs");
9583                }
9584
9585                // Package declaring static a shared lib cannot declare shared users
9586                if (pkg.mSharedUserId != null) {
9587                    throw new PackageManagerException(
9588                            "Packages declaring static-shared libs cannot declare shared users");
9589                }
9590
9591                // Static shared libs cannot declare activities
9592                if (!pkg.activities.isEmpty()) {
9593                    throw new PackageManagerException(
9594                            "Static shared libs cannot declare activities");
9595                }
9596
9597                // Static shared libs cannot declare services
9598                if (!pkg.services.isEmpty()) {
9599                    throw new PackageManagerException(
9600                            "Static shared libs cannot declare services");
9601                }
9602
9603                // Static shared libs cannot declare providers
9604                if (!pkg.providers.isEmpty()) {
9605                    throw new PackageManagerException(
9606                            "Static shared libs cannot declare content providers");
9607                }
9608
9609                // Static shared libs cannot declare receivers
9610                if (!pkg.receivers.isEmpty()) {
9611                    throw new PackageManagerException(
9612                            "Static shared libs cannot declare broadcast receivers");
9613                }
9614
9615                // Static shared libs cannot declare permission groups
9616                if (!pkg.permissionGroups.isEmpty()) {
9617                    throw new PackageManagerException(
9618                            "Static shared libs cannot declare permission groups");
9619                }
9620
9621                // Static shared libs cannot declare permissions
9622                if (!pkg.permissions.isEmpty()) {
9623                    throw new PackageManagerException(
9624                            "Static shared libs cannot declare permissions");
9625                }
9626
9627                // Static shared libs cannot declare protected broadcasts
9628                if (pkg.protectedBroadcasts != null) {
9629                    throw new PackageManagerException(
9630                            "Static shared libs cannot declare protected broadcasts");
9631                }
9632
9633                // Static shared libs cannot be overlay targets
9634                if (pkg.mOverlayTarget != null) {
9635                    throw new PackageManagerException(
9636                            "Static shared libs cannot be overlay targets");
9637                }
9638
9639                // The version codes must be ordered as lib versions
9640                int minVersionCode = Integer.MIN_VALUE;
9641                int maxVersionCode = Integer.MAX_VALUE;
9642
9643                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9644                        pkg.staticSharedLibName);
9645                if (versionedLib != null) {
9646                    final int versionCount = versionedLib.size();
9647                    for (int i = 0; i < versionCount; i++) {
9648                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9649                        // TODO: We will change version code to long, so in the new API it is long
9650                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9651                                .getVersionCode();
9652                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9653                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9654                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9655                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9656                        } else {
9657                            minVersionCode = maxVersionCode = libVersionCode;
9658                            break;
9659                        }
9660                    }
9661                }
9662                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9663                    throw new PackageManagerException("Static shared"
9664                            + " lib version codes must be ordered as lib versions");
9665                }
9666            }
9667
9668            // Only privileged apps and updated privileged apps can add child packages.
9669            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9670                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9671                    throw new PackageManagerException("Only privileged apps can add child "
9672                            + "packages. Ignoring package " + pkg.packageName);
9673                }
9674                final int childCount = pkg.childPackages.size();
9675                for (int i = 0; i < childCount; i++) {
9676                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9677                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9678                            childPkg.packageName)) {
9679                        throw new PackageManagerException("Can't override child of "
9680                                + "another disabled app. Ignoring package " + pkg.packageName);
9681                    }
9682                }
9683            }
9684
9685            // If we're only installing presumed-existing packages, require that the
9686            // scanned APK is both already known and at the path previously established
9687            // for it.  Previously unknown packages we pick up normally, but if we have an
9688            // a priori expectation about this package's install presence, enforce it.
9689            // With a singular exception for new system packages. When an OTA contains
9690            // a new system package, we allow the codepath to change from a system location
9691            // to the user-installed location. If we don't allow this change, any newer,
9692            // user-installed version of the application will be ignored.
9693            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9694                if (mExpectingBetter.containsKey(pkg.packageName)) {
9695                    logCriticalInfo(Log.WARN,
9696                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9697                } else {
9698                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9699                    if (known != null) {
9700                        if (DEBUG_PACKAGE_SCANNING) {
9701                            Log.d(TAG, "Examining " + pkg.codePath
9702                                    + " and requiring known paths " + known.codePathString
9703                                    + " & " + known.resourcePathString);
9704                        }
9705                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9706                                || !pkg.applicationInfo.getResourcePath().equals(
9707                                        known.resourcePathString)) {
9708                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9709                                    "Application package " + pkg.packageName
9710                                    + " found at " + pkg.applicationInfo.getCodePath()
9711                                    + " but expected at " + known.codePathString
9712                                    + "; ignoring.");
9713                        }
9714                    }
9715                }
9716            }
9717
9718            // Verify that this new package doesn't have any content providers
9719            // that conflict with existing packages.  Only do this if the
9720            // package isn't already installed, since we don't want to break
9721            // things that are installed.
9722            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9723                final int N = pkg.providers.size();
9724                int i;
9725                for (i=0; i<N; i++) {
9726                    PackageParser.Provider p = pkg.providers.get(i);
9727                    if (p.info.authority != null) {
9728                        String names[] = p.info.authority.split(";");
9729                        for (int j = 0; j < names.length; j++) {
9730                            if (mProvidersByAuthority.containsKey(names[j])) {
9731                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9732                                final String otherPackageName =
9733                                        ((other != null && other.getComponentName() != null) ?
9734                                                other.getComponentName().getPackageName() : "?");
9735                                throw new PackageManagerException(
9736                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9737                                        "Can't install because provider name " + names[j]
9738                                                + " (in package " + pkg.applicationInfo.packageName
9739                                                + ") is already used by " + otherPackageName);
9740                            }
9741                        }
9742                    }
9743                }
9744            }
9745        }
9746    }
9747
9748    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9749            int type, String declaringPackageName, int declaringVersionCode) {
9750        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9751        if (versionedLib == null) {
9752            versionedLib = new SparseArray<>();
9753            mSharedLibraries.put(name, versionedLib);
9754            if (type == SharedLibraryInfo.TYPE_STATIC) {
9755                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9756            }
9757        } else if (versionedLib.indexOfKey(version) >= 0) {
9758            return false;
9759        }
9760        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9761                version, type, declaringPackageName, declaringVersionCode);
9762        versionedLib.put(version, libEntry);
9763        return true;
9764    }
9765
9766    private boolean removeSharedLibraryLPw(String name, int version) {
9767        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9768        if (versionedLib == null) {
9769            return false;
9770        }
9771        final int libIdx = versionedLib.indexOfKey(version);
9772        if (libIdx < 0) {
9773            return false;
9774        }
9775        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9776        versionedLib.remove(version);
9777        if (versionedLib.size() <= 0) {
9778            mSharedLibraries.remove(name);
9779            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9780                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9781                        .getPackageName());
9782            }
9783        }
9784        return true;
9785    }
9786
9787    /**
9788     * Adds a scanned package to the system. When this method is finished, the package will
9789     * be available for query, resolution, etc...
9790     */
9791    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9792            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9793        final String pkgName = pkg.packageName;
9794        if (mCustomResolverComponentName != null &&
9795                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9796            setUpCustomResolverActivity(pkg);
9797        }
9798
9799        if (pkg.packageName.equals("android")) {
9800            synchronized (mPackages) {
9801                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9802                    // Set up information for our fall-back user intent resolution activity.
9803                    mPlatformPackage = pkg;
9804                    pkg.mVersionCode = mSdkVersion;
9805                    mAndroidApplication = pkg.applicationInfo;
9806                    if (!mResolverReplaced) {
9807                        mResolveActivity.applicationInfo = mAndroidApplication;
9808                        mResolveActivity.name = ResolverActivity.class.getName();
9809                        mResolveActivity.packageName = mAndroidApplication.packageName;
9810                        mResolveActivity.processName = "system:ui";
9811                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9812                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9813                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9814                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9815                        mResolveActivity.exported = true;
9816                        mResolveActivity.enabled = true;
9817                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9818                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9819                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9820                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9821                                | ActivityInfo.CONFIG_ORIENTATION
9822                                | ActivityInfo.CONFIG_KEYBOARD
9823                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9824                        mResolveInfo.activityInfo = mResolveActivity;
9825                        mResolveInfo.priority = 0;
9826                        mResolveInfo.preferredOrder = 0;
9827                        mResolveInfo.match = 0;
9828                        mResolveComponentName = new ComponentName(
9829                                mAndroidApplication.packageName, mResolveActivity.name);
9830                    }
9831                }
9832            }
9833        }
9834
9835        ArrayList<PackageParser.Package> clientLibPkgs = null;
9836        // writer
9837        synchronized (mPackages) {
9838            boolean hasStaticSharedLibs = false;
9839
9840            // Any app can add new static shared libraries
9841            if (pkg.staticSharedLibName != null) {
9842                // Static shared libs don't allow renaming as they have synthetic package
9843                // names to allow install of multiple versions, so use name from manifest.
9844                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9845                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9846                        pkg.manifestPackageName, pkg.mVersionCode)) {
9847                    hasStaticSharedLibs = true;
9848                } else {
9849                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9850                                + pkg.staticSharedLibName + " already exists; skipping");
9851                }
9852                // Static shared libs cannot be updated once installed since they
9853                // use synthetic package name which includes the version code, so
9854                // not need to update other packages's shared lib dependencies.
9855            }
9856
9857            if (!hasStaticSharedLibs
9858                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9859                // Only system apps can add new dynamic shared libraries.
9860                if (pkg.libraryNames != null) {
9861                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9862                        String name = pkg.libraryNames.get(i);
9863                        boolean allowed = false;
9864                        if (pkg.isUpdatedSystemApp()) {
9865                            // New library entries can only be added through the
9866                            // system image.  This is important to get rid of a lot
9867                            // of nasty edge cases: for example if we allowed a non-
9868                            // system update of the app to add a library, then uninstalling
9869                            // the update would make the library go away, and assumptions
9870                            // we made such as through app install filtering would now
9871                            // have allowed apps on the device which aren't compatible
9872                            // with it.  Better to just have the restriction here, be
9873                            // conservative, and create many fewer cases that can negatively
9874                            // impact the user experience.
9875                            final PackageSetting sysPs = mSettings
9876                                    .getDisabledSystemPkgLPr(pkg.packageName);
9877                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9878                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9879                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9880                                        allowed = true;
9881                                        break;
9882                                    }
9883                                }
9884                            }
9885                        } else {
9886                            allowed = true;
9887                        }
9888                        if (allowed) {
9889                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9890                                    SharedLibraryInfo.VERSION_UNDEFINED,
9891                                    SharedLibraryInfo.TYPE_DYNAMIC,
9892                                    pkg.packageName, pkg.mVersionCode)) {
9893                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9894                                        + name + " already exists; skipping");
9895                            }
9896                        } else {
9897                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9898                                    + name + " that is not declared on system image; skipping");
9899                        }
9900                    }
9901
9902                    if ((scanFlags & SCAN_BOOTING) == 0) {
9903                        // If we are not booting, we need to update any applications
9904                        // that are clients of our shared library.  If we are booting,
9905                        // this will all be done once the scan is complete.
9906                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9907                    }
9908                }
9909            }
9910        }
9911
9912        if ((scanFlags & SCAN_BOOTING) != 0) {
9913            // No apps can run during boot scan, so they don't need to be frozen
9914        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9915            // Caller asked to not kill app, so it's probably not frozen
9916        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9917            // Caller asked us to ignore frozen check for some reason; they
9918            // probably didn't know the package name
9919        } else {
9920            // We're doing major surgery on this package, so it better be frozen
9921            // right now to keep it from launching
9922            checkPackageFrozen(pkgName);
9923        }
9924
9925        // Also need to kill any apps that are dependent on the library.
9926        if (clientLibPkgs != null) {
9927            for (int i=0; i<clientLibPkgs.size(); i++) {
9928                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9929                killApplication(clientPkg.applicationInfo.packageName,
9930                        clientPkg.applicationInfo.uid, "update lib");
9931            }
9932        }
9933
9934        // writer
9935        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9936
9937        boolean createIdmapFailed = false;
9938        synchronized (mPackages) {
9939            // We don't expect installation to fail beyond this point
9940
9941            if (pkgSetting.pkg != null) {
9942                // Note that |user| might be null during the initial boot scan. If a codePath
9943                // for an app has changed during a boot scan, it's due to an app update that's
9944                // part of the system partition and marker changes must be applied to all users.
9945                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9946                final int[] userIds = resolveUserIds(userId);
9947                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9948            }
9949
9950            // Add the new setting to mSettings
9951            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9952            // Add the new setting to mPackages
9953            mPackages.put(pkg.applicationInfo.packageName, pkg);
9954            // Make sure we don't accidentally delete its data.
9955            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9956            while (iter.hasNext()) {
9957                PackageCleanItem item = iter.next();
9958                if (pkgName.equals(item.packageName)) {
9959                    iter.remove();
9960                }
9961            }
9962
9963            // Add the package's KeySets to the global KeySetManagerService
9964            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9965            ksms.addScannedPackageLPw(pkg);
9966
9967            int N = pkg.providers.size();
9968            StringBuilder r = null;
9969            int i;
9970            for (i=0; i<N; i++) {
9971                PackageParser.Provider p = pkg.providers.get(i);
9972                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9973                        p.info.processName);
9974                mProviders.addProvider(p);
9975                p.syncable = p.info.isSyncable;
9976                if (p.info.authority != null) {
9977                    String names[] = p.info.authority.split(";");
9978                    p.info.authority = null;
9979                    for (int j = 0; j < names.length; j++) {
9980                        if (j == 1 && p.syncable) {
9981                            // We only want the first authority for a provider to possibly be
9982                            // syncable, so if we already added this provider using a different
9983                            // authority clear the syncable flag. We copy the provider before
9984                            // changing it because the mProviders object contains a reference
9985                            // to a provider that we don't want to change.
9986                            // Only do this for the second authority since the resulting provider
9987                            // object can be the same for all future authorities for this provider.
9988                            p = new PackageParser.Provider(p);
9989                            p.syncable = false;
9990                        }
9991                        if (!mProvidersByAuthority.containsKey(names[j])) {
9992                            mProvidersByAuthority.put(names[j], p);
9993                            if (p.info.authority == null) {
9994                                p.info.authority = names[j];
9995                            } else {
9996                                p.info.authority = p.info.authority + ";" + names[j];
9997                            }
9998                            if (DEBUG_PACKAGE_SCANNING) {
9999                                if (chatty)
10000                                    Log.d(TAG, "Registered content provider: " + names[j]
10001                                            + ", className = " + p.info.name + ", isSyncable = "
10002                                            + p.info.isSyncable);
10003                            }
10004                        } else {
10005                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10006                            Slog.w(TAG, "Skipping provider name " + names[j] +
10007                                    " (in package " + pkg.applicationInfo.packageName +
10008                                    "): name already used by "
10009                                    + ((other != null && other.getComponentName() != null)
10010                                            ? other.getComponentName().getPackageName() : "?"));
10011                        }
10012                    }
10013                }
10014                if (chatty) {
10015                    if (r == null) {
10016                        r = new StringBuilder(256);
10017                    } else {
10018                        r.append(' ');
10019                    }
10020                    r.append(p.info.name);
10021                }
10022            }
10023            if (r != null) {
10024                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10025            }
10026
10027            N = pkg.services.size();
10028            r = null;
10029            for (i=0; i<N; i++) {
10030                PackageParser.Service s = pkg.services.get(i);
10031                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10032                        s.info.processName);
10033                mServices.addService(s);
10034                if (chatty) {
10035                    if (r == null) {
10036                        r = new StringBuilder(256);
10037                    } else {
10038                        r.append(' ');
10039                    }
10040                    r.append(s.info.name);
10041                }
10042            }
10043            if (r != null) {
10044                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10045            }
10046
10047            N = pkg.receivers.size();
10048            r = null;
10049            for (i=0; i<N; i++) {
10050                PackageParser.Activity a = pkg.receivers.get(i);
10051                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10052                        a.info.processName);
10053                mReceivers.addActivity(a, "receiver");
10054                if (chatty) {
10055                    if (r == null) {
10056                        r = new StringBuilder(256);
10057                    } else {
10058                        r.append(' ');
10059                    }
10060                    r.append(a.info.name);
10061                }
10062            }
10063            if (r != null) {
10064                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10065            }
10066
10067            N = pkg.activities.size();
10068            r = null;
10069            for (i=0; i<N; i++) {
10070                PackageParser.Activity a = pkg.activities.get(i);
10071                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10072                        a.info.processName);
10073                mActivities.addActivity(a, "activity");
10074                if (chatty) {
10075                    if (r == null) {
10076                        r = new StringBuilder(256);
10077                    } else {
10078                        r.append(' ');
10079                    }
10080                    r.append(a.info.name);
10081                }
10082            }
10083            if (r != null) {
10084                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10085            }
10086
10087            N = pkg.permissionGroups.size();
10088            r = null;
10089            for (i=0; i<N; i++) {
10090                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10091                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10092                final String curPackageName = cur == null ? null : cur.info.packageName;
10093                // Dont allow ephemeral apps to define new permission groups.
10094                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10095                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10096                            + pg.info.packageName
10097                            + " ignored: instant apps cannot define new permission groups.");
10098                    continue;
10099                }
10100                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10101                if (cur == null || isPackageUpdate) {
10102                    mPermissionGroups.put(pg.info.name, pg);
10103                    if (chatty) {
10104                        if (r == null) {
10105                            r = new StringBuilder(256);
10106                        } else {
10107                            r.append(' ');
10108                        }
10109                        if (isPackageUpdate) {
10110                            r.append("UPD:");
10111                        }
10112                        r.append(pg.info.name);
10113                    }
10114                } else {
10115                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10116                            + pg.info.packageName + " ignored: original from "
10117                            + cur.info.packageName);
10118                    if (chatty) {
10119                        if (r == null) {
10120                            r = new StringBuilder(256);
10121                        } else {
10122                            r.append(' ');
10123                        }
10124                        r.append("DUP:");
10125                        r.append(pg.info.name);
10126                    }
10127                }
10128            }
10129            if (r != null) {
10130                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10131            }
10132
10133            N = pkg.permissions.size();
10134            r = null;
10135            for (i=0; i<N; i++) {
10136                PackageParser.Permission p = pkg.permissions.get(i);
10137
10138                // Dont allow ephemeral apps to define new permissions.
10139                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10140                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10141                            + p.info.packageName
10142                            + " ignored: instant apps cannot define new permissions.");
10143                    continue;
10144                }
10145
10146                // Assume by default that we did not install this permission into the system.
10147                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10148
10149                // Now that permission groups have a special meaning, we ignore permission
10150                // groups for legacy apps to prevent unexpected behavior. In particular,
10151                // permissions for one app being granted to someone just becase they happen
10152                // to be in a group defined by another app (before this had no implications).
10153                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10154                    p.group = mPermissionGroups.get(p.info.group);
10155                    // Warn for a permission in an unknown group.
10156                    if (p.info.group != null && p.group == null) {
10157                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10158                                + p.info.packageName + " in an unknown group " + p.info.group);
10159                    }
10160                }
10161
10162                ArrayMap<String, BasePermission> permissionMap =
10163                        p.tree ? mSettings.mPermissionTrees
10164                                : mSettings.mPermissions;
10165                BasePermission bp = permissionMap.get(p.info.name);
10166
10167                // Allow system apps to redefine non-system permissions
10168                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10169                    final boolean currentOwnerIsSystem = (bp.perm != null
10170                            && isSystemApp(bp.perm.owner));
10171                    if (isSystemApp(p.owner)) {
10172                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10173                            // It's a built-in permission and no owner, take ownership now
10174                            bp.packageSetting = pkgSetting;
10175                            bp.perm = p;
10176                            bp.uid = pkg.applicationInfo.uid;
10177                            bp.sourcePackage = p.info.packageName;
10178                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10179                        } else if (!currentOwnerIsSystem) {
10180                            String msg = "New decl " + p.owner + " of permission  "
10181                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10182                            reportSettingsProblem(Log.WARN, msg);
10183                            bp = null;
10184                        }
10185                    }
10186                }
10187
10188                if (bp == null) {
10189                    bp = new BasePermission(p.info.name, p.info.packageName,
10190                            BasePermission.TYPE_NORMAL);
10191                    permissionMap.put(p.info.name, bp);
10192                }
10193
10194                if (bp.perm == null) {
10195                    if (bp.sourcePackage == null
10196                            || bp.sourcePackage.equals(p.info.packageName)) {
10197                        BasePermission tree = findPermissionTreeLP(p.info.name);
10198                        if (tree == null
10199                                || tree.sourcePackage.equals(p.info.packageName)) {
10200                            bp.packageSetting = pkgSetting;
10201                            bp.perm = p;
10202                            bp.uid = pkg.applicationInfo.uid;
10203                            bp.sourcePackage = p.info.packageName;
10204                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10205                            if (chatty) {
10206                                if (r == null) {
10207                                    r = new StringBuilder(256);
10208                                } else {
10209                                    r.append(' ');
10210                                }
10211                                r.append(p.info.name);
10212                            }
10213                        } else {
10214                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10215                                    + p.info.packageName + " ignored: base tree "
10216                                    + tree.name + " is from package "
10217                                    + tree.sourcePackage);
10218                        }
10219                    } else {
10220                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10221                                + p.info.packageName + " ignored: original from "
10222                                + bp.sourcePackage);
10223                    }
10224                } else if (chatty) {
10225                    if (r == null) {
10226                        r = new StringBuilder(256);
10227                    } else {
10228                        r.append(' ');
10229                    }
10230                    r.append("DUP:");
10231                    r.append(p.info.name);
10232                }
10233                if (bp.perm == p) {
10234                    bp.protectionLevel = p.info.protectionLevel;
10235                }
10236            }
10237
10238            if (r != null) {
10239                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10240            }
10241
10242            N = pkg.instrumentation.size();
10243            r = null;
10244            for (i=0; i<N; i++) {
10245                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10246                a.info.packageName = pkg.applicationInfo.packageName;
10247                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10248                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10249                a.info.splitNames = pkg.splitNames;
10250                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10251                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10252                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10253                a.info.dataDir = pkg.applicationInfo.dataDir;
10254                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10255                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10256                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10257                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10258                mInstrumentation.put(a.getComponentName(), a);
10259                if (chatty) {
10260                    if (r == null) {
10261                        r = new StringBuilder(256);
10262                    } else {
10263                        r.append(' ');
10264                    }
10265                    r.append(a.info.name);
10266                }
10267            }
10268            if (r != null) {
10269                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10270            }
10271
10272            if (pkg.protectedBroadcasts != null) {
10273                N = pkg.protectedBroadcasts.size();
10274                for (i=0; i<N; i++) {
10275                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10276                }
10277            }
10278
10279            // Create idmap files for pairs of (packages, overlay packages).
10280            // Note: "android", ie framework-res.apk, is handled by native layers.
10281            if (pkg.mOverlayTarget != null) {
10282                // This is an overlay package.
10283                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10284                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10285                        mOverlays.put(pkg.mOverlayTarget,
10286                                new ArrayMap<String, PackageParser.Package>());
10287                    }
10288                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10289                    map.put(pkg.packageName, pkg);
10290                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10291                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10292                        createIdmapFailed = true;
10293                    }
10294                }
10295            } else if (mOverlays.containsKey(pkg.packageName) &&
10296                    !pkg.packageName.equals("android")) {
10297                // This is a regular package, with one or more known overlay packages.
10298                createIdmapsForPackageLI(pkg);
10299            }
10300        }
10301
10302        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10303
10304        if (createIdmapFailed) {
10305            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10306                    "scanPackageLI failed to createIdmap");
10307        }
10308    }
10309
10310    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10311            PackageParser.Package update, int[] userIds) {
10312        if (existing.applicationInfo == null || update.applicationInfo == null) {
10313            // This isn't due to an app installation.
10314            return;
10315        }
10316
10317        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10318        final File newCodePath = new File(update.applicationInfo.getCodePath());
10319
10320        // The codePath hasn't changed, so there's nothing for us to do.
10321        if (Objects.equals(oldCodePath, newCodePath)) {
10322            return;
10323        }
10324
10325        File canonicalNewCodePath;
10326        try {
10327            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10328        } catch (IOException e) {
10329            Slog.w(TAG, "Failed to get canonical path.", e);
10330            return;
10331        }
10332
10333        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10334        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10335        // that the last component of the path (i.e, the name) doesn't need canonicalization
10336        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10337        // but may change in the future. Hopefully this function won't exist at that point.
10338        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10339                oldCodePath.getName());
10340
10341        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10342        // with "@".
10343        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10344        if (!oldMarkerPrefix.endsWith("@")) {
10345            oldMarkerPrefix += "@";
10346        }
10347        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10348        if (!newMarkerPrefix.endsWith("@")) {
10349            newMarkerPrefix += "@";
10350        }
10351
10352        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10353        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10354        for (String updatedPath : updatedPaths) {
10355            String updatedPathName = new File(updatedPath).getName();
10356            markerSuffixes.add(updatedPathName.replace('/', '@'));
10357        }
10358
10359        for (int userId : userIds) {
10360            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10361
10362            for (String markerSuffix : markerSuffixes) {
10363                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10364                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10365                if (oldForeignUseMark.exists()) {
10366                    try {
10367                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10368                                newForeignUseMark.getAbsolutePath());
10369                    } catch (ErrnoException e) {
10370                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10371                        oldForeignUseMark.delete();
10372                    }
10373                }
10374            }
10375        }
10376    }
10377
10378    /**
10379     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10380     * is derived purely on the basis of the contents of {@code scanFile} and
10381     * {@code cpuAbiOverride}.
10382     *
10383     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10384     */
10385    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10386                                 String cpuAbiOverride, boolean extractLibs,
10387                                 File appLib32InstallDir)
10388            throws PackageManagerException {
10389        // Give ourselves some initial paths; we'll come back for another
10390        // pass once we've determined ABI below.
10391        setNativeLibraryPaths(pkg, appLib32InstallDir);
10392
10393        // We would never need to extract libs for forward-locked and external packages,
10394        // since the container service will do it for us. We shouldn't attempt to
10395        // extract libs from system app when it was not updated.
10396        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10397                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10398            extractLibs = false;
10399        }
10400
10401        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10402        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10403
10404        NativeLibraryHelper.Handle handle = null;
10405        try {
10406            handle = NativeLibraryHelper.Handle.create(pkg);
10407            // TODO(multiArch): This can be null for apps that didn't go through the
10408            // usual installation process. We can calculate it again, like we
10409            // do during install time.
10410            //
10411            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10412            // unnecessary.
10413            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10414
10415            // Null out the abis so that they can be recalculated.
10416            pkg.applicationInfo.primaryCpuAbi = null;
10417            pkg.applicationInfo.secondaryCpuAbi = null;
10418            if (isMultiArch(pkg.applicationInfo)) {
10419                // Warn if we've set an abiOverride for multi-lib packages..
10420                // By definition, we need to copy both 32 and 64 bit libraries for
10421                // such packages.
10422                if (pkg.cpuAbiOverride != null
10423                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10424                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10425                }
10426
10427                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10428                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10429                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10430                    if (extractLibs) {
10431                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10432                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10433                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10434                                useIsaSpecificSubdirs);
10435                    } else {
10436                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10437                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10438                    }
10439                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10440                }
10441
10442                maybeThrowExceptionForMultiArchCopy(
10443                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10444
10445                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10446                    if (extractLibs) {
10447                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10448                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10449                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10450                                useIsaSpecificSubdirs);
10451                    } else {
10452                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10453                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10454                    }
10455                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10456                }
10457
10458                maybeThrowExceptionForMultiArchCopy(
10459                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10460
10461                if (abi64 >= 0) {
10462                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10463                }
10464
10465                if (abi32 >= 0) {
10466                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10467                    if (abi64 >= 0) {
10468                        if (pkg.use32bitAbi) {
10469                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10470                            pkg.applicationInfo.primaryCpuAbi = abi;
10471                        } else {
10472                            pkg.applicationInfo.secondaryCpuAbi = abi;
10473                        }
10474                    } else {
10475                        pkg.applicationInfo.primaryCpuAbi = abi;
10476                    }
10477                }
10478
10479            } else {
10480                String[] abiList = (cpuAbiOverride != null) ?
10481                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10482
10483                // Enable gross and lame hacks for apps that are built with old
10484                // SDK tools. We must scan their APKs for renderscript bitcode and
10485                // not launch them if it's present. Don't bother checking on devices
10486                // that don't have 64 bit support.
10487                boolean needsRenderScriptOverride = false;
10488                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10489                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10490                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10491                    needsRenderScriptOverride = true;
10492                }
10493
10494                final int copyRet;
10495                if (extractLibs) {
10496                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10497                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10498                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10499                } else {
10500                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10501                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10502                }
10503                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10504
10505                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10506                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10507                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10508                }
10509
10510                if (copyRet >= 0) {
10511                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10512                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10513                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10514                } else if (needsRenderScriptOverride) {
10515                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10516                }
10517            }
10518        } catch (IOException ioe) {
10519            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10520        } finally {
10521            IoUtils.closeQuietly(handle);
10522        }
10523
10524        // Now that we've calculated the ABIs and determined if it's an internal app,
10525        // we will go ahead and populate the nativeLibraryPath.
10526        setNativeLibraryPaths(pkg, appLib32InstallDir);
10527    }
10528
10529    /**
10530     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10531     * i.e, so that all packages can be run inside a single process if required.
10532     *
10533     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10534     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10535     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10536     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10537     * updating a package that belongs to a shared user.
10538     *
10539     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10540     * adds unnecessary complexity.
10541     */
10542    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10543            PackageParser.Package scannedPackage) {
10544        String requiredInstructionSet = null;
10545        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10546            requiredInstructionSet = VMRuntime.getInstructionSet(
10547                     scannedPackage.applicationInfo.primaryCpuAbi);
10548        }
10549
10550        PackageSetting requirer = null;
10551        for (PackageSetting ps : packagesForUser) {
10552            // If packagesForUser contains scannedPackage, we skip it. This will happen
10553            // when scannedPackage is an update of an existing package. Without this check,
10554            // we will never be able to change the ABI of any package belonging to a shared
10555            // user, even if it's compatible with other packages.
10556            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10557                if (ps.primaryCpuAbiString == null) {
10558                    continue;
10559                }
10560
10561                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10562                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10563                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10564                    // this but there's not much we can do.
10565                    String errorMessage = "Instruction set mismatch, "
10566                            + ((requirer == null) ? "[caller]" : requirer)
10567                            + " requires " + requiredInstructionSet + " whereas " + ps
10568                            + " requires " + instructionSet;
10569                    Slog.w(TAG, errorMessage);
10570                }
10571
10572                if (requiredInstructionSet == null) {
10573                    requiredInstructionSet = instructionSet;
10574                    requirer = ps;
10575                }
10576            }
10577        }
10578
10579        if (requiredInstructionSet != null) {
10580            String adjustedAbi;
10581            if (requirer != null) {
10582                // requirer != null implies that either scannedPackage was null or that scannedPackage
10583                // did not require an ABI, in which case we have to adjust scannedPackage to match
10584                // the ABI of the set (which is the same as requirer's ABI)
10585                adjustedAbi = requirer.primaryCpuAbiString;
10586                if (scannedPackage != null) {
10587                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10588                }
10589            } else {
10590                // requirer == null implies that we're updating all ABIs in the set to
10591                // match scannedPackage.
10592                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10593            }
10594
10595            for (PackageSetting ps : packagesForUser) {
10596                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10597                    if (ps.primaryCpuAbiString != null) {
10598                        continue;
10599                    }
10600
10601                    ps.primaryCpuAbiString = adjustedAbi;
10602                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10603                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10604                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10605                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10606                                + " (requirer="
10607                                + (requirer == null ? "null" : requirer.pkg.packageName)
10608                                + ", scannedPackage="
10609                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10610                                + ")");
10611                        try {
10612                            mInstaller.rmdex(ps.codePathString,
10613                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10614                        } catch (InstallerException ignored) {
10615                        }
10616                    }
10617                }
10618            }
10619        }
10620    }
10621
10622    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10623        synchronized (mPackages) {
10624            mResolverReplaced = true;
10625            // Set up information for custom user intent resolution activity.
10626            mResolveActivity.applicationInfo = pkg.applicationInfo;
10627            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10628            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10629            mResolveActivity.processName = pkg.applicationInfo.packageName;
10630            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10631            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10632                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10633            mResolveActivity.theme = 0;
10634            mResolveActivity.exported = true;
10635            mResolveActivity.enabled = true;
10636            mResolveInfo.activityInfo = mResolveActivity;
10637            mResolveInfo.priority = 0;
10638            mResolveInfo.preferredOrder = 0;
10639            mResolveInfo.match = 0;
10640            mResolveComponentName = mCustomResolverComponentName;
10641            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10642                    mResolveComponentName);
10643        }
10644    }
10645
10646    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10647        if (installerComponent == null) {
10648            if (DEBUG_EPHEMERAL) {
10649                Slog.d(TAG, "Clear ephemeral installer activity");
10650            }
10651            mEphemeralInstallerActivity.applicationInfo = null;
10652            return;
10653        }
10654
10655        if (DEBUG_EPHEMERAL) {
10656            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10657        }
10658        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10659        // Set up information for ephemeral installer activity
10660        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10661        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10662        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10663        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10664        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10665        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10666                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10667        mEphemeralInstallerActivity.theme = 0;
10668        mEphemeralInstallerActivity.exported = true;
10669        mEphemeralInstallerActivity.enabled = true;
10670        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10671        mEphemeralInstallerInfo.priority = 0;
10672        mEphemeralInstallerInfo.preferredOrder = 1;
10673        mEphemeralInstallerInfo.isDefault = true;
10674        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10675                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10676    }
10677
10678    private static String calculateBundledApkRoot(final String codePathString) {
10679        final File codePath = new File(codePathString);
10680        final File codeRoot;
10681        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10682            codeRoot = Environment.getRootDirectory();
10683        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10684            codeRoot = Environment.getOemDirectory();
10685        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10686            codeRoot = Environment.getVendorDirectory();
10687        } else {
10688            // Unrecognized code path; take its top real segment as the apk root:
10689            // e.g. /something/app/blah.apk => /something
10690            try {
10691                File f = codePath.getCanonicalFile();
10692                File parent = f.getParentFile();    // non-null because codePath is a file
10693                File tmp;
10694                while ((tmp = parent.getParentFile()) != null) {
10695                    f = parent;
10696                    parent = tmp;
10697                }
10698                codeRoot = f;
10699                Slog.w(TAG, "Unrecognized code path "
10700                        + codePath + " - using " + codeRoot);
10701            } catch (IOException e) {
10702                // Can't canonicalize the code path -- shenanigans?
10703                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10704                return Environment.getRootDirectory().getPath();
10705            }
10706        }
10707        return codeRoot.getPath();
10708    }
10709
10710    /**
10711     * Derive and set the location of native libraries for the given package,
10712     * which varies depending on where and how the package was installed.
10713     */
10714    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10715        final ApplicationInfo info = pkg.applicationInfo;
10716        final String codePath = pkg.codePath;
10717        final File codeFile = new File(codePath);
10718        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10719        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10720
10721        info.nativeLibraryRootDir = null;
10722        info.nativeLibraryRootRequiresIsa = false;
10723        info.nativeLibraryDir = null;
10724        info.secondaryNativeLibraryDir = null;
10725
10726        if (isApkFile(codeFile)) {
10727            // Monolithic install
10728            if (bundledApp) {
10729                // If "/system/lib64/apkname" exists, assume that is the per-package
10730                // native library directory to use; otherwise use "/system/lib/apkname".
10731                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10732                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10733                        getPrimaryInstructionSet(info));
10734
10735                // This is a bundled system app so choose the path based on the ABI.
10736                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10737                // is just the default path.
10738                final String apkName = deriveCodePathName(codePath);
10739                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10740                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10741                        apkName).getAbsolutePath();
10742
10743                if (info.secondaryCpuAbi != null) {
10744                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10745                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10746                            secondaryLibDir, apkName).getAbsolutePath();
10747                }
10748            } else if (asecApp) {
10749                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10750                        .getAbsolutePath();
10751            } else {
10752                final String apkName = deriveCodePathName(codePath);
10753                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10754                        .getAbsolutePath();
10755            }
10756
10757            info.nativeLibraryRootRequiresIsa = false;
10758            info.nativeLibraryDir = info.nativeLibraryRootDir;
10759        } else {
10760            // Cluster install
10761            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10762            info.nativeLibraryRootRequiresIsa = true;
10763
10764            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10765                    getPrimaryInstructionSet(info)).getAbsolutePath();
10766
10767            if (info.secondaryCpuAbi != null) {
10768                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10769                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10770            }
10771        }
10772    }
10773
10774    /**
10775     * Calculate the abis and roots for a bundled app. These can uniquely
10776     * be determined from the contents of the system partition, i.e whether
10777     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10778     * of this information, and instead assume that the system was built
10779     * sensibly.
10780     */
10781    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10782                                           PackageSetting pkgSetting) {
10783        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10784
10785        // If "/system/lib64/apkname" exists, assume that is the per-package
10786        // native library directory to use; otherwise use "/system/lib/apkname".
10787        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10788        setBundledAppAbi(pkg, apkRoot, apkName);
10789        // pkgSetting might be null during rescan following uninstall of updates
10790        // to a bundled app, so accommodate that possibility.  The settings in
10791        // that case will be established later from the parsed package.
10792        //
10793        // If the settings aren't null, sync them up with what we've just derived.
10794        // note that apkRoot isn't stored in the package settings.
10795        if (pkgSetting != null) {
10796            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10797            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10798        }
10799    }
10800
10801    /**
10802     * Deduces the ABI of a bundled app and sets the relevant fields on the
10803     * parsed pkg object.
10804     *
10805     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10806     *        under which system libraries are installed.
10807     * @param apkName the name of the installed package.
10808     */
10809    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10810        final File codeFile = new File(pkg.codePath);
10811
10812        final boolean has64BitLibs;
10813        final boolean has32BitLibs;
10814        if (isApkFile(codeFile)) {
10815            // Monolithic install
10816            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10817            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10818        } else {
10819            // Cluster install
10820            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10821            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10822                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10823                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10824                has64BitLibs = (new File(rootDir, isa)).exists();
10825            } else {
10826                has64BitLibs = false;
10827            }
10828            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10829                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10830                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10831                has32BitLibs = (new File(rootDir, isa)).exists();
10832            } else {
10833                has32BitLibs = false;
10834            }
10835        }
10836
10837        if (has64BitLibs && !has32BitLibs) {
10838            // The package has 64 bit libs, but not 32 bit libs. Its primary
10839            // ABI should be 64 bit. We can safely assume here that the bundled
10840            // native libraries correspond to the most preferred ABI in the list.
10841
10842            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10843            pkg.applicationInfo.secondaryCpuAbi = null;
10844        } else if (has32BitLibs && !has64BitLibs) {
10845            // The package has 32 bit libs but not 64 bit libs. Its primary
10846            // ABI should be 32 bit.
10847
10848            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10849            pkg.applicationInfo.secondaryCpuAbi = null;
10850        } else if (has32BitLibs && has64BitLibs) {
10851            // The application has both 64 and 32 bit bundled libraries. We check
10852            // here that the app declares multiArch support, and warn if it doesn't.
10853            //
10854            // We will be lenient here and record both ABIs. The primary will be the
10855            // ABI that's higher on the list, i.e, a device that's configured to prefer
10856            // 64 bit apps will see a 64 bit primary ABI,
10857
10858            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10859                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10860            }
10861
10862            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10863                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10864                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10865            } else {
10866                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10867                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10868            }
10869        } else {
10870            pkg.applicationInfo.primaryCpuAbi = null;
10871            pkg.applicationInfo.secondaryCpuAbi = null;
10872        }
10873    }
10874
10875    private void killApplication(String pkgName, int appId, String reason) {
10876        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10877    }
10878
10879    private void killApplication(String pkgName, int appId, int userId, String reason) {
10880        // Request the ActivityManager to kill the process(only for existing packages)
10881        // so that we do not end up in a confused state while the user is still using the older
10882        // version of the application while the new one gets installed.
10883        final long token = Binder.clearCallingIdentity();
10884        try {
10885            IActivityManager am = ActivityManager.getService();
10886            if (am != null) {
10887                try {
10888                    am.killApplication(pkgName, appId, userId, reason);
10889                } catch (RemoteException e) {
10890                }
10891            }
10892        } finally {
10893            Binder.restoreCallingIdentity(token);
10894        }
10895    }
10896
10897    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10898        // Remove the parent package setting
10899        PackageSetting ps = (PackageSetting) pkg.mExtras;
10900        if (ps != null) {
10901            removePackageLI(ps, chatty);
10902        }
10903        // Remove the child package setting
10904        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10905        for (int i = 0; i < childCount; i++) {
10906            PackageParser.Package childPkg = pkg.childPackages.get(i);
10907            ps = (PackageSetting) childPkg.mExtras;
10908            if (ps != null) {
10909                removePackageLI(ps, chatty);
10910            }
10911        }
10912    }
10913
10914    void removePackageLI(PackageSetting ps, boolean chatty) {
10915        if (DEBUG_INSTALL) {
10916            if (chatty)
10917                Log.d(TAG, "Removing package " + ps.name);
10918        }
10919
10920        // writer
10921        synchronized (mPackages) {
10922            mPackages.remove(ps.name);
10923            final PackageParser.Package pkg = ps.pkg;
10924            if (pkg != null) {
10925                cleanPackageDataStructuresLILPw(pkg, chatty);
10926            }
10927        }
10928    }
10929
10930    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10931        if (DEBUG_INSTALL) {
10932            if (chatty)
10933                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10934        }
10935
10936        // writer
10937        synchronized (mPackages) {
10938            // Remove the parent package
10939            mPackages.remove(pkg.applicationInfo.packageName);
10940            cleanPackageDataStructuresLILPw(pkg, chatty);
10941
10942            // Remove the child packages
10943            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10944            for (int i = 0; i < childCount; i++) {
10945                PackageParser.Package childPkg = pkg.childPackages.get(i);
10946                mPackages.remove(childPkg.applicationInfo.packageName);
10947                cleanPackageDataStructuresLILPw(childPkg, chatty);
10948            }
10949        }
10950    }
10951
10952    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10953        int N = pkg.providers.size();
10954        StringBuilder r = null;
10955        int i;
10956        for (i=0; i<N; i++) {
10957            PackageParser.Provider p = pkg.providers.get(i);
10958            mProviders.removeProvider(p);
10959            if (p.info.authority == null) {
10960
10961                /* There was another ContentProvider with this authority when
10962                 * this app was installed so this authority is null,
10963                 * Ignore it as we don't have to unregister the provider.
10964                 */
10965                continue;
10966            }
10967            String names[] = p.info.authority.split(";");
10968            for (int j = 0; j < names.length; j++) {
10969                if (mProvidersByAuthority.get(names[j]) == p) {
10970                    mProvidersByAuthority.remove(names[j]);
10971                    if (DEBUG_REMOVE) {
10972                        if (chatty)
10973                            Log.d(TAG, "Unregistered content provider: " + names[j]
10974                                    + ", className = " + p.info.name + ", isSyncable = "
10975                                    + p.info.isSyncable);
10976                    }
10977                }
10978            }
10979            if (DEBUG_REMOVE && chatty) {
10980                if (r == null) {
10981                    r = new StringBuilder(256);
10982                } else {
10983                    r.append(' ');
10984                }
10985                r.append(p.info.name);
10986            }
10987        }
10988        if (r != null) {
10989            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10990        }
10991
10992        N = pkg.services.size();
10993        r = null;
10994        for (i=0; i<N; i++) {
10995            PackageParser.Service s = pkg.services.get(i);
10996            mServices.removeService(s);
10997            if (chatty) {
10998                if (r == null) {
10999                    r = new StringBuilder(256);
11000                } else {
11001                    r.append(' ');
11002                }
11003                r.append(s.info.name);
11004            }
11005        }
11006        if (r != null) {
11007            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11008        }
11009
11010        N = pkg.receivers.size();
11011        r = null;
11012        for (i=0; i<N; i++) {
11013            PackageParser.Activity a = pkg.receivers.get(i);
11014            mReceivers.removeActivity(a, "receiver");
11015            if (DEBUG_REMOVE && chatty) {
11016                if (r == null) {
11017                    r = new StringBuilder(256);
11018                } else {
11019                    r.append(' ');
11020                }
11021                r.append(a.info.name);
11022            }
11023        }
11024        if (r != null) {
11025            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11026        }
11027
11028        N = pkg.activities.size();
11029        r = null;
11030        for (i=0; i<N; i++) {
11031            PackageParser.Activity a = pkg.activities.get(i);
11032            mActivities.removeActivity(a, "activity");
11033            if (DEBUG_REMOVE && chatty) {
11034                if (r == null) {
11035                    r = new StringBuilder(256);
11036                } else {
11037                    r.append(' ');
11038                }
11039                r.append(a.info.name);
11040            }
11041        }
11042        if (r != null) {
11043            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11044        }
11045
11046        N = pkg.permissions.size();
11047        r = null;
11048        for (i=0; i<N; i++) {
11049            PackageParser.Permission p = pkg.permissions.get(i);
11050            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11051            if (bp == null) {
11052                bp = mSettings.mPermissionTrees.get(p.info.name);
11053            }
11054            if (bp != null && bp.perm == p) {
11055                bp.perm = null;
11056                if (DEBUG_REMOVE && chatty) {
11057                    if (r == null) {
11058                        r = new StringBuilder(256);
11059                    } else {
11060                        r.append(' ');
11061                    }
11062                    r.append(p.info.name);
11063                }
11064            }
11065            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11066                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11067                if (appOpPkgs != null) {
11068                    appOpPkgs.remove(pkg.packageName);
11069                }
11070            }
11071        }
11072        if (r != null) {
11073            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11074        }
11075
11076        N = pkg.requestedPermissions.size();
11077        r = null;
11078        for (i=0; i<N; i++) {
11079            String perm = pkg.requestedPermissions.get(i);
11080            BasePermission bp = mSettings.mPermissions.get(perm);
11081            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11082                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11083                if (appOpPkgs != null) {
11084                    appOpPkgs.remove(pkg.packageName);
11085                    if (appOpPkgs.isEmpty()) {
11086                        mAppOpPermissionPackages.remove(perm);
11087                    }
11088                }
11089            }
11090        }
11091        if (r != null) {
11092            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11093        }
11094
11095        N = pkg.instrumentation.size();
11096        r = null;
11097        for (i=0; i<N; i++) {
11098            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11099            mInstrumentation.remove(a.getComponentName());
11100            if (DEBUG_REMOVE && chatty) {
11101                if (r == null) {
11102                    r = new StringBuilder(256);
11103                } else {
11104                    r.append(' ');
11105                }
11106                r.append(a.info.name);
11107            }
11108        }
11109        if (r != null) {
11110            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11111        }
11112
11113        r = null;
11114        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11115            // Only system apps can hold shared libraries.
11116            if (pkg.libraryNames != null) {
11117                for (i = 0; i < pkg.libraryNames.size(); i++) {
11118                    String name = pkg.libraryNames.get(i);
11119                    if (removeSharedLibraryLPw(name, 0)) {
11120                        if (DEBUG_REMOVE && chatty) {
11121                            if (r == null) {
11122                                r = new StringBuilder(256);
11123                            } else {
11124                                r.append(' ');
11125                            }
11126                            r.append(name);
11127                        }
11128                    }
11129                }
11130            }
11131        }
11132
11133        r = null;
11134
11135        // Any package can hold static shared libraries.
11136        if (pkg.staticSharedLibName != null) {
11137            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11138                if (DEBUG_REMOVE && chatty) {
11139                    if (r == null) {
11140                        r = new StringBuilder(256);
11141                    } else {
11142                        r.append(' ');
11143                    }
11144                    r.append(pkg.staticSharedLibName);
11145                }
11146            }
11147        }
11148
11149        if (r != null) {
11150            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11151        }
11152    }
11153
11154    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11155        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11156            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11157                return true;
11158            }
11159        }
11160        return false;
11161    }
11162
11163    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11164    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11165    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11166
11167    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11168        // Update the parent permissions
11169        updatePermissionsLPw(pkg.packageName, pkg, flags);
11170        // Update the child permissions
11171        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11172        for (int i = 0; i < childCount; i++) {
11173            PackageParser.Package childPkg = pkg.childPackages.get(i);
11174            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11175        }
11176    }
11177
11178    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11179            int flags) {
11180        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11181        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11182    }
11183
11184    private void updatePermissionsLPw(String changingPkg,
11185            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11186        // Make sure there are no dangling permission trees.
11187        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11188        while (it.hasNext()) {
11189            final BasePermission bp = it.next();
11190            if (bp.packageSetting == null) {
11191                // We may not yet have parsed the package, so just see if
11192                // we still know about its settings.
11193                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11194            }
11195            if (bp.packageSetting == null) {
11196                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11197                        + " from package " + bp.sourcePackage);
11198                it.remove();
11199            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11200                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11201                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11202                            + " from package " + bp.sourcePackage);
11203                    flags |= UPDATE_PERMISSIONS_ALL;
11204                    it.remove();
11205                }
11206            }
11207        }
11208
11209        // Make sure all dynamic permissions have been assigned to a package,
11210        // and make sure there are no dangling permissions.
11211        it = mSettings.mPermissions.values().iterator();
11212        while (it.hasNext()) {
11213            final BasePermission bp = it.next();
11214            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11215                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11216                        + bp.name + " pkg=" + bp.sourcePackage
11217                        + " info=" + bp.pendingInfo);
11218                if (bp.packageSetting == null && bp.pendingInfo != null) {
11219                    final BasePermission tree = findPermissionTreeLP(bp.name);
11220                    if (tree != null && tree.perm != null) {
11221                        bp.packageSetting = tree.packageSetting;
11222                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11223                                new PermissionInfo(bp.pendingInfo));
11224                        bp.perm.info.packageName = tree.perm.info.packageName;
11225                        bp.perm.info.name = bp.name;
11226                        bp.uid = tree.uid;
11227                    }
11228                }
11229            }
11230            if (bp.packageSetting == null) {
11231                // We may not yet have parsed the package, so just see if
11232                // we still know about its settings.
11233                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11234            }
11235            if (bp.packageSetting == null) {
11236                Slog.w(TAG, "Removing dangling permission: " + bp.name
11237                        + " from package " + bp.sourcePackage);
11238                it.remove();
11239            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11240                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11241                    Slog.i(TAG, "Removing old permission: " + bp.name
11242                            + " from package " + bp.sourcePackage);
11243                    flags |= UPDATE_PERMISSIONS_ALL;
11244                    it.remove();
11245                }
11246            }
11247        }
11248
11249        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11250        // Now update the permissions for all packages, in particular
11251        // replace the granted permissions of the system packages.
11252        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11253            for (PackageParser.Package pkg : mPackages.values()) {
11254                if (pkg != pkgInfo) {
11255                    // Only replace for packages on requested volume
11256                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11257                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11258                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11259                    grantPermissionsLPw(pkg, replace, changingPkg);
11260                }
11261            }
11262        }
11263
11264        if (pkgInfo != null) {
11265            // Only replace for packages on requested volume
11266            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11267            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11268                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11269            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11270        }
11271        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11272    }
11273
11274    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11275            String packageOfInterest) {
11276        // IMPORTANT: There are two types of permissions: install and runtime.
11277        // Install time permissions are granted when the app is installed to
11278        // all device users and users added in the future. Runtime permissions
11279        // are granted at runtime explicitly to specific users. Normal and signature
11280        // protected permissions are install time permissions. Dangerous permissions
11281        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11282        // otherwise they are runtime permissions. This function does not manage
11283        // runtime permissions except for the case an app targeting Lollipop MR1
11284        // being upgraded to target a newer SDK, in which case dangerous permissions
11285        // are transformed from install time to runtime ones.
11286
11287        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11288        if (ps == null) {
11289            return;
11290        }
11291
11292        PermissionsState permissionsState = ps.getPermissionsState();
11293        PermissionsState origPermissions = permissionsState;
11294
11295        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11296
11297        boolean runtimePermissionsRevoked = false;
11298        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11299
11300        boolean changedInstallPermission = false;
11301
11302        if (replace) {
11303            ps.installPermissionsFixed = false;
11304            if (!ps.isSharedUser()) {
11305                origPermissions = new PermissionsState(permissionsState);
11306                permissionsState.reset();
11307            } else {
11308                // We need to know only about runtime permission changes since the
11309                // calling code always writes the install permissions state but
11310                // the runtime ones are written only if changed. The only cases of
11311                // changed runtime permissions here are promotion of an install to
11312                // runtime and revocation of a runtime from a shared user.
11313                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11314                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11315                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11316                    runtimePermissionsRevoked = true;
11317                }
11318            }
11319        }
11320
11321        permissionsState.setGlobalGids(mGlobalGids);
11322
11323        final int N = pkg.requestedPermissions.size();
11324        for (int i=0; i<N; i++) {
11325            final String name = pkg.requestedPermissions.get(i);
11326            final BasePermission bp = mSettings.mPermissions.get(name);
11327
11328            if (DEBUG_INSTALL) {
11329                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11330            }
11331
11332            if (bp == null || bp.packageSetting == null) {
11333                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11334                    Slog.w(TAG, "Unknown permission " + name
11335                            + " in package " + pkg.packageName);
11336                }
11337                continue;
11338            }
11339
11340
11341            // Limit ephemeral apps to ephemeral allowed permissions.
11342            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11343                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11344                        + pkg.packageName);
11345                continue;
11346            }
11347
11348            final String perm = bp.name;
11349            boolean allowedSig = false;
11350            int grant = GRANT_DENIED;
11351
11352            // Keep track of app op permissions.
11353            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11354                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11355                if (pkgs == null) {
11356                    pkgs = new ArraySet<>();
11357                    mAppOpPermissionPackages.put(bp.name, pkgs);
11358                }
11359                pkgs.add(pkg.packageName);
11360            }
11361
11362            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11363            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11364                    >= Build.VERSION_CODES.M;
11365            switch (level) {
11366                case PermissionInfo.PROTECTION_NORMAL: {
11367                    // For all apps normal permissions are install time ones.
11368                    grant = GRANT_INSTALL;
11369                } break;
11370
11371                case PermissionInfo.PROTECTION_DANGEROUS: {
11372                    // If a permission review is required for legacy apps we represent
11373                    // their permissions as always granted runtime ones since we need
11374                    // to keep the review required permission flag per user while an
11375                    // install permission's state is shared across all users.
11376                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11377                        // For legacy apps dangerous permissions are install time ones.
11378                        grant = GRANT_INSTALL;
11379                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11380                        // For legacy apps that became modern, install becomes runtime.
11381                        grant = GRANT_UPGRADE;
11382                    } else if (mPromoteSystemApps
11383                            && isSystemApp(ps)
11384                            && mExistingSystemPackages.contains(ps.name)) {
11385                        // For legacy system apps, install becomes runtime.
11386                        // We cannot check hasInstallPermission() for system apps since those
11387                        // permissions were granted implicitly and not persisted pre-M.
11388                        grant = GRANT_UPGRADE;
11389                    } else {
11390                        // For modern apps keep runtime permissions unchanged.
11391                        grant = GRANT_RUNTIME;
11392                    }
11393                } break;
11394
11395                case PermissionInfo.PROTECTION_SIGNATURE: {
11396                    // For all apps signature permissions are install time ones.
11397                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11398                    if (allowedSig) {
11399                        grant = GRANT_INSTALL;
11400                    }
11401                } break;
11402            }
11403
11404            if (DEBUG_INSTALL) {
11405                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11406            }
11407
11408            if (grant != GRANT_DENIED) {
11409                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11410                    // If this is an existing, non-system package, then
11411                    // we can't add any new permissions to it.
11412                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11413                        // Except...  if this is a permission that was added
11414                        // to the platform (note: need to only do this when
11415                        // updating the platform).
11416                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11417                            grant = GRANT_DENIED;
11418                        }
11419                    }
11420                }
11421
11422                switch (grant) {
11423                    case GRANT_INSTALL: {
11424                        // Revoke this as runtime permission to handle the case of
11425                        // a runtime permission being downgraded to an install one.
11426                        // Also in permission review mode we keep dangerous permissions
11427                        // for legacy apps
11428                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11429                            if (origPermissions.getRuntimePermissionState(
11430                                    bp.name, userId) != null) {
11431                                // Revoke the runtime permission and clear the flags.
11432                                origPermissions.revokeRuntimePermission(bp, userId);
11433                                origPermissions.updatePermissionFlags(bp, userId,
11434                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11435                                // If we revoked a permission permission, we have to write.
11436                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11437                                        changedRuntimePermissionUserIds, userId);
11438                            }
11439                        }
11440                        // Grant an install permission.
11441                        if (permissionsState.grantInstallPermission(bp) !=
11442                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11443                            changedInstallPermission = true;
11444                        }
11445                    } break;
11446
11447                    case GRANT_RUNTIME: {
11448                        // Grant previously granted runtime permissions.
11449                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11450                            PermissionState permissionState = origPermissions
11451                                    .getRuntimePermissionState(bp.name, userId);
11452                            int flags = permissionState != null
11453                                    ? permissionState.getFlags() : 0;
11454                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11455                                // Don't propagate the permission in a permission review mode if
11456                                // the former was revoked, i.e. marked to not propagate on upgrade.
11457                                // Note that in a permission review mode install permissions are
11458                                // represented as constantly granted runtime ones since we need to
11459                                // keep a per user state associated with the permission. Also the
11460                                // revoke on upgrade flag is no longer applicable and is reset.
11461                                final boolean revokeOnUpgrade = (flags & PackageManager
11462                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11463                                if (revokeOnUpgrade) {
11464                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11465                                    // Since we changed the flags, we have to write.
11466                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11467                                            changedRuntimePermissionUserIds, userId);
11468                                }
11469                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11470                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11471                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11472                                        // If we cannot put the permission as it was,
11473                                        // we have to write.
11474                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11475                                                changedRuntimePermissionUserIds, userId);
11476                                    }
11477                                }
11478
11479                                // If the app supports runtime permissions no need for a review.
11480                                if (mPermissionReviewRequired
11481                                        && appSupportsRuntimePermissions
11482                                        && (flags & PackageManager
11483                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11484                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11485                                    // Since we changed the flags, we have to write.
11486                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11487                                            changedRuntimePermissionUserIds, userId);
11488                                }
11489                            } else if (mPermissionReviewRequired
11490                                    && !appSupportsRuntimePermissions) {
11491                                // For legacy apps that need a permission review, every new
11492                                // runtime permission is granted but it is pending a review.
11493                                // We also need to review only platform defined runtime
11494                                // permissions as these are the only ones the platform knows
11495                                // how to disable the API to simulate revocation as legacy
11496                                // apps don't expect to run with revoked permissions.
11497                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11498                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11499                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11500                                        // We changed the flags, hence have to write.
11501                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11502                                                changedRuntimePermissionUserIds, userId);
11503                                    }
11504                                }
11505                                if (permissionsState.grantRuntimePermission(bp, userId)
11506                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11507                                    // We changed the permission, hence have to write.
11508                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11509                                            changedRuntimePermissionUserIds, userId);
11510                                }
11511                            }
11512                            // Propagate the permission flags.
11513                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11514                        }
11515                    } break;
11516
11517                    case GRANT_UPGRADE: {
11518                        // Grant runtime permissions for a previously held install permission.
11519                        PermissionState permissionState = origPermissions
11520                                .getInstallPermissionState(bp.name);
11521                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11522
11523                        if (origPermissions.revokeInstallPermission(bp)
11524                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11525                            // We will be transferring the permission flags, so clear them.
11526                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11527                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11528                            changedInstallPermission = true;
11529                        }
11530
11531                        // If the permission is not to be promoted to runtime we ignore it and
11532                        // also its other flags as they are not applicable to install permissions.
11533                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11534                            for (int userId : currentUserIds) {
11535                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11536                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11537                                    // Transfer the permission flags.
11538                                    permissionsState.updatePermissionFlags(bp, userId,
11539                                            flags, flags);
11540                                    // If we granted the permission, we have to write.
11541                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11542                                            changedRuntimePermissionUserIds, userId);
11543                                }
11544                            }
11545                        }
11546                    } break;
11547
11548                    default: {
11549                        if (packageOfInterest == null
11550                                || packageOfInterest.equals(pkg.packageName)) {
11551                            Slog.w(TAG, "Not granting permission " + perm
11552                                    + " to package " + pkg.packageName
11553                                    + " because it was previously installed without");
11554                        }
11555                    } break;
11556                }
11557            } else {
11558                if (permissionsState.revokeInstallPermission(bp) !=
11559                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11560                    // Also drop the permission flags.
11561                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11562                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11563                    changedInstallPermission = true;
11564                    Slog.i(TAG, "Un-granting permission " + perm
11565                            + " from package " + pkg.packageName
11566                            + " (protectionLevel=" + bp.protectionLevel
11567                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11568                            + ")");
11569                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11570                    // Don't print warning for app op permissions, since it is fine for them
11571                    // not to be granted, there is a UI for the user to decide.
11572                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11573                        Slog.w(TAG, "Not granting permission " + perm
11574                                + " to package " + pkg.packageName
11575                                + " (protectionLevel=" + bp.protectionLevel
11576                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11577                                + ")");
11578                    }
11579                }
11580            }
11581        }
11582
11583        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11584                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11585            // This is the first that we have heard about this package, so the
11586            // permissions we have now selected are fixed until explicitly
11587            // changed.
11588            ps.installPermissionsFixed = true;
11589        }
11590
11591        // Persist the runtime permissions state for users with changes. If permissions
11592        // were revoked because no app in the shared user declares them we have to
11593        // write synchronously to avoid losing runtime permissions state.
11594        for (int userId : changedRuntimePermissionUserIds) {
11595            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11596        }
11597    }
11598
11599    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11600        boolean allowed = false;
11601        final int NP = PackageParser.NEW_PERMISSIONS.length;
11602        for (int ip=0; ip<NP; ip++) {
11603            final PackageParser.NewPermissionInfo npi
11604                    = PackageParser.NEW_PERMISSIONS[ip];
11605            if (npi.name.equals(perm)
11606                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11607                allowed = true;
11608                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11609                        + pkg.packageName);
11610                break;
11611            }
11612        }
11613        return allowed;
11614    }
11615
11616    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11617            BasePermission bp, PermissionsState origPermissions) {
11618        boolean privilegedPermission = (bp.protectionLevel
11619                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11620        boolean privappPermissionsDisable =
11621                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11622        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11623        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11624        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11625                && !platformPackage && platformPermission) {
11626            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11627                    .getPrivAppPermissions(pkg.packageName);
11628            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11629            if (!whitelisted) {
11630                Slog.w(TAG, "Privileged permission " + perm + " for package "
11631                        + pkg.packageName + " - not in privapp-permissions whitelist");
11632                if (!mSystemReady) {
11633                    if (mPrivappPermissionsViolations == null) {
11634                        mPrivappPermissionsViolations = new ArraySet<>();
11635                    }
11636                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11637                }
11638                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11639                    return false;
11640                }
11641            }
11642        }
11643        boolean allowed = (compareSignatures(
11644                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11645                        == PackageManager.SIGNATURE_MATCH)
11646                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11647                        == PackageManager.SIGNATURE_MATCH);
11648        if (!allowed && privilegedPermission) {
11649            if (isSystemApp(pkg)) {
11650                // For updated system applications, a system permission
11651                // is granted only if it had been defined by the original application.
11652                if (pkg.isUpdatedSystemApp()) {
11653                    final PackageSetting sysPs = mSettings
11654                            .getDisabledSystemPkgLPr(pkg.packageName);
11655                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11656                        // If the original was granted this permission, we take
11657                        // that grant decision as read and propagate it to the
11658                        // update.
11659                        if (sysPs.isPrivileged()) {
11660                            allowed = true;
11661                        }
11662                    } else {
11663                        // The system apk may have been updated with an older
11664                        // version of the one on the data partition, but which
11665                        // granted a new system permission that it didn't have
11666                        // before.  In this case we do want to allow the app to
11667                        // now get the new permission if the ancestral apk is
11668                        // privileged to get it.
11669                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11670                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11671                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11672                                    allowed = true;
11673                                    break;
11674                                }
11675                            }
11676                        }
11677                        // Also if a privileged parent package on the system image or any of
11678                        // its children requested a privileged permission, the updated child
11679                        // packages can also get the permission.
11680                        if (pkg.parentPackage != null) {
11681                            final PackageSetting disabledSysParentPs = mSettings
11682                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11683                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11684                                    && disabledSysParentPs.isPrivileged()) {
11685                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11686                                    allowed = true;
11687                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11688                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11689                                    for (int i = 0; i < count; i++) {
11690                                        PackageParser.Package disabledSysChildPkg =
11691                                                disabledSysParentPs.pkg.childPackages.get(i);
11692                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11693                                                perm)) {
11694                                            allowed = true;
11695                                            break;
11696                                        }
11697                                    }
11698                                }
11699                            }
11700                        }
11701                    }
11702                } else {
11703                    allowed = isPrivilegedApp(pkg);
11704                }
11705            }
11706        }
11707        if (!allowed) {
11708            if (!allowed && (bp.protectionLevel
11709                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11710                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11711                // If this was a previously normal/dangerous permission that got moved
11712                // to a system permission as part of the runtime permission redesign, then
11713                // we still want to blindly grant it to old apps.
11714                allowed = true;
11715            }
11716            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11717                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11718                // If this permission is to be granted to the system installer and
11719                // this app is an installer, then it gets the permission.
11720                allowed = true;
11721            }
11722            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11723                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11724                // If this permission is to be granted to the system verifier and
11725                // this app is a verifier, then it gets the permission.
11726                allowed = true;
11727            }
11728            if (!allowed && (bp.protectionLevel
11729                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11730                    && isSystemApp(pkg)) {
11731                // Any pre-installed system app is allowed to get this permission.
11732                allowed = true;
11733            }
11734            if (!allowed && (bp.protectionLevel
11735                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11736                // For development permissions, a development permission
11737                // is granted only if it was already granted.
11738                allowed = origPermissions.hasInstallPermission(perm);
11739            }
11740            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11741                    && pkg.packageName.equals(mSetupWizardPackage)) {
11742                // If this permission is to be granted to the system setup wizard and
11743                // this app is a setup wizard, then it gets the permission.
11744                allowed = true;
11745            }
11746        }
11747        return allowed;
11748    }
11749
11750    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11751        final int permCount = pkg.requestedPermissions.size();
11752        for (int j = 0; j < permCount; j++) {
11753            String requestedPermission = pkg.requestedPermissions.get(j);
11754            if (permission.equals(requestedPermission)) {
11755                return true;
11756            }
11757        }
11758        return false;
11759    }
11760
11761    final class ActivityIntentResolver
11762            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11763        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11764                boolean defaultOnly, int userId) {
11765            if (!sUserManager.exists(userId)) return null;
11766            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11767            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11768        }
11769
11770        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11771                int userId) {
11772            if (!sUserManager.exists(userId)) return null;
11773            mFlags = flags;
11774            return super.queryIntent(intent, resolvedType,
11775                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11776                    userId);
11777        }
11778
11779        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11780                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11781            if (!sUserManager.exists(userId)) return null;
11782            if (packageActivities == null) {
11783                return null;
11784            }
11785            mFlags = flags;
11786            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11787            final int N = packageActivities.size();
11788            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11789                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11790
11791            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11792            for (int i = 0; i < N; ++i) {
11793                intentFilters = packageActivities.get(i).intents;
11794                if (intentFilters != null && intentFilters.size() > 0) {
11795                    PackageParser.ActivityIntentInfo[] array =
11796                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11797                    intentFilters.toArray(array);
11798                    listCut.add(array);
11799                }
11800            }
11801            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11802        }
11803
11804        /**
11805         * Finds a privileged activity that matches the specified activity names.
11806         */
11807        private PackageParser.Activity findMatchingActivity(
11808                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11809            for (PackageParser.Activity sysActivity : activityList) {
11810                if (sysActivity.info.name.equals(activityInfo.name)) {
11811                    return sysActivity;
11812                }
11813                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11814                    return sysActivity;
11815                }
11816                if (sysActivity.info.targetActivity != null) {
11817                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11818                        return sysActivity;
11819                    }
11820                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11821                        return sysActivity;
11822                    }
11823                }
11824            }
11825            return null;
11826        }
11827
11828        public class IterGenerator<E> {
11829            public Iterator<E> generate(ActivityIntentInfo info) {
11830                return null;
11831            }
11832        }
11833
11834        public class ActionIterGenerator extends IterGenerator<String> {
11835            @Override
11836            public Iterator<String> generate(ActivityIntentInfo info) {
11837                return info.actionsIterator();
11838            }
11839        }
11840
11841        public class CategoriesIterGenerator extends IterGenerator<String> {
11842            @Override
11843            public Iterator<String> generate(ActivityIntentInfo info) {
11844                return info.categoriesIterator();
11845            }
11846        }
11847
11848        public class SchemesIterGenerator extends IterGenerator<String> {
11849            @Override
11850            public Iterator<String> generate(ActivityIntentInfo info) {
11851                return info.schemesIterator();
11852            }
11853        }
11854
11855        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11856            @Override
11857            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11858                return info.authoritiesIterator();
11859            }
11860        }
11861
11862        /**
11863         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11864         * MODIFIED. Do not pass in a list that should not be changed.
11865         */
11866        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11867                IterGenerator<T> generator, Iterator<T> searchIterator) {
11868            // loop through the set of actions; every one must be found in the intent filter
11869            while (searchIterator.hasNext()) {
11870                // we must have at least one filter in the list to consider a match
11871                if (intentList.size() == 0) {
11872                    break;
11873                }
11874
11875                final T searchAction = searchIterator.next();
11876
11877                // loop through the set of intent filters
11878                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11879                while (intentIter.hasNext()) {
11880                    final ActivityIntentInfo intentInfo = intentIter.next();
11881                    boolean selectionFound = false;
11882
11883                    // loop through the intent filter's selection criteria; at least one
11884                    // of them must match the searched criteria
11885                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11886                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11887                        final T intentSelection = intentSelectionIter.next();
11888                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11889                            selectionFound = true;
11890                            break;
11891                        }
11892                    }
11893
11894                    // the selection criteria wasn't found in this filter's set; this filter
11895                    // is not a potential match
11896                    if (!selectionFound) {
11897                        intentIter.remove();
11898                    }
11899                }
11900            }
11901        }
11902
11903        private boolean isProtectedAction(ActivityIntentInfo filter) {
11904            final Iterator<String> actionsIter = filter.actionsIterator();
11905            while (actionsIter != null && actionsIter.hasNext()) {
11906                final String filterAction = actionsIter.next();
11907                if (PROTECTED_ACTIONS.contains(filterAction)) {
11908                    return true;
11909                }
11910            }
11911            return false;
11912        }
11913
11914        /**
11915         * Adjusts the priority of the given intent filter according to policy.
11916         * <p>
11917         * <ul>
11918         * <li>The priority for non privileged applications is capped to '0'</li>
11919         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11920         * <li>The priority for unbundled updates to privileged applications is capped to the
11921         *      priority defined on the system partition</li>
11922         * </ul>
11923         * <p>
11924         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11925         * allowed to obtain any priority on any action.
11926         */
11927        private void adjustPriority(
11928                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11929            // nothing to do; priority is fine as-is
11930            if (intent.getPriority() <= 0) {
11931                return;
11932            }
11933
11934            final ActivityInfo activityInfo = intent.activity.info;
11935            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11936
11937            final boolean privilegedApp =
11938                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11939            if (!privilegedApp) {
11940                // non-privileged applications can never define a priority >0
11941                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11942                        + " package: " + applicationInfo.packageName
11943                        + " activity: " + intent.activity.className
11944                        + " origPrio: " + intent.getPriority());
11945                intent.setPriority(0);
11946                return;
11947            }
11948
11949            if (systemActivities == null) {
11950                // the system package is not disabled; we're parsing the system partition
11951                if (isProtectedAction(intent)) {
11952                    if (mDeferProtectedFilters) {
11953                        // We can't deal with these just yet. No component should ever obtain a
11954                        // >0 priority for a protected actions, with ONE exception -- the setup
11955                        // wizard. The setup wizard, however, cannot be known until we're able to
11956                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11957                        // until all intent filters have been processed. Chicken, meet egg.
11958                        // Let the filter temporarily have a high priority and rectify the
11959                        // priorities after all system packages have been scanned.
11960                        mProtectedFilters.add(intent);
11961                        if (DEBUG_FILTERS) {
11962                            Slog.i(TAG, "Protected action; save for later;"
11963                                    + " package: " + applicationInfo.packageName
11964                                    + " activity: " + intent.activity.className
11965                                    + " origPrio: " + intent.getPriority());
11966                        }
11967                        return;
11968                    } else {
11969                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11970                            Slog.i(TAG, "No setup wizard;"
11971                                + " All protected intents capped to priority 0");
11972                        }
11973                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11974                            if (DEBUG_FILTERS) {
11975                                Slog.i(TAG, "Found setup wizard;"
11976                                    + " allow priority " + intent.getPriority() + ";"
11977                                    + " package: " + intent.activity.info.packageName
11978                                    + " activity: " + intent.activity.className
11979                                    + " priority: " + intent.getPriority());
11980                            }
11981                            // setup wizard gets whatever it wants
11982                            return;
11983                        }
11984                        Slog.w(TAG, "Protected action; cap priority to 0;"
11985                                + " package: " + intent.activity.info.packageName
11986                                + " activity: " + intent.activity.className
11987                                + " origPrio: " + intent.getPriority());
11988                        intent.setPriority(0);
11989                        return;
11990                    }
11991                }
11992                // privileged apps on the system image get whatever priority they request
11993                return;
11994            }
11995
11996            // privileged app unbundled update ... try to find the same activity
11997            final PackageParser.Activity foundActivity =
11998                    findMatchingActivity(systemActivities, activityInfo);
11999            if (foundActivity == null) {
12000                // this is a new activity; it cannot obtain >0 priority
12001                if (DEBUG_FILTERS) {
12002                    Slog.i(TAG, "New activity; cap priority to 0;"
12003                            + " package: " + applicationInfo.packageName
12004                            + " activity: " + intent.activity.className
12005                            + " origPrio: " + intent.getPriority());
12006                }
12007                intent.setPriority(0);
12008                return;
12009            }
12010
12011            // found activity, now check for filter equivalence
12012
12013            // a shallow copy is enough; we modify the list, not its contents
12014            final List<ActivityIntentInfo> intentListCopy =
12015                    new ArrayList<>(foundActivity.intents);
12016            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12017
12018            // find matching action subsets
12019            final Iterator<String> actionsIterator = intent.actionsIterator();
12020            if (actionsIterator != null) {
12021                getIntentListSubset(
12022                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12023                if (intentListCopy.size() == 0) {
12024                    // no more intents to match; we're not equivalent
12025                    if (DEBUG_FILTERS) {
12026                        Slog.i(TAG, "Mismatched action; 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 category subsets
12037            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12038            if (categoriesIterator != null) {
12039                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12040                        categoriesIterator);
12041                if (intentListCopy.size() == 0) {
12042                    // no more intents to match; we're not equivalent
12043                    if (DEBUG_FILTERS) {
12044                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12045                                + " package: " + applicationInfo.packageName
12046                                + " activity: " + intent.activity.className
12047                                + " origPrio: " + intent.getPriority());
12048                    }
12049                    intent.setPriority(0);
12050                    return;
12051                }
12052            }
12053
12054            // find matching schemes subsets
12055            final Iterator<String> schemesIterator = intent.schemesIterator();
12056            if (schemesIterator != null) {
12057                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12058                        schemesIterator);
12059                if (intentListCopy.size() == 0) {
12060                    // no more intents to match; we're not equivalent
12061                    if (DEBUG_FILTERS) {
12062                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12063                                + " package: " + applicationInfo.packageName
12064                                + " activity: " + intent.activity.className
12065                                + " origPrio: " + intent.getPriority());
12066                    }
12067                    intent.setPriority(0);
12068                    return;
12069                }
12070            }
12071
12072            // find matching authorities subsets
12073            final Iterator<IntentFilter.AuthorityEntry>
12074                    authoritiesIterator = intent.authoritiesIterator();
12075            if (authoritiesIterator != null) {
12076                getIntentListSubset(intentListCopy,
12077                        new AuthoritiesIterGenerator(),
12078                        authoritiesIterator);
12079                if (intentListCopy.size() == 0) {
12080                    // no more intents to match; we're not equivalent
12081                    if (DEBUG_FILTERS) {
12082                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12083                                + " package: " + applicationInfo.packageName
12084                                + " activity: " + intent.activity.className
12085                                + " origPrio: " + intent.getPriority());
12086                    }
12087                    intent.setPriority(0);
12088                    return;
12089                }
12090            }
12091
12092            // we found matching filter(s); app gets the max priority of all intents
12093            int cappedPriority = 0;
12094            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12095                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12096            }
12097            if (intent.getPriority() > cappedPriority) {
12098                if (DEBUG_FILTERS) {
12099                    Slog.i(TAG, "Found matching filter(s);"
12100                            + " cap priority to " + cappedPriority + ";"
12101                            + " package: " + applicationInfo.packageName
12102                            + " activity: " + intent.activity.className
12103                            + " origPrio: " + intent.getPriority());
12104                }
12105                intent.setPriority(cappedPriority);
12106                return;
12107            }
12108            // all this for nothing; the requested priority was <= what was on the system
12109        }
12110
12111        public final void addActivity(PackageParser.Activity a, String type) {
12112            mActivities.put(a.getComponentName(), a);
12113            if (DEBUG_SHOW_INFO)
12114                Log.v(
12115                TAG, "  " + type + " " +
12116                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12117            if (DEBUG_SHOW_INFO)
12118                Log.v(TAG, "    Class=" + a.info.name);
12119            final int NI = a.intents.size();
12120            for (int j=0; j<NI; j++) {
12121                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12122                if ("activity".equals(type)) {
12123                    final PackageSetting ps =
12124                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12125                    final List<PackageParser.Activity> systemActivities =
12126                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12127                    adjustPriority(systemActivities, intent);
12128                }
12129                if (DEBUG_SHOW_INFO) {
12130                    Log.v(TAG, "    IntentFilter:");
12131                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12132                }
12133                if (!intent.debugCheck()) {
12134                    Log.w(TAG, "==> For Activity " + a.info.name);
12135                }
12136                addFilter(intent);
12137            }
12138        }
12139
12140        public final void removeActivity(PackageParser.Activity a, String type) {
12141            mActivities.remove(a.getComponentName());
12142            if (DEBUG_SHOW_INFO) {
12143                Log.v(TAG, "  " + type + " "
12144                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12145                                : a.info.name) + ":");
12146                Log.v(TAG, "    Class=" + a.info.name);
12147            }
12148            final int NI = a.intents.size();
12149            for (int j=0; j<NI; j++) {
12150                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12151                if (DEBUG_SHOW_INFO) {
12152                    Log.v(TAG, "    IntentFilter:");
12153                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12154                }
12155                removeFilter(intent);
12156            }
12157        }
12158
12159        @Override
12160        protected boolean allowFilterResult(
12161                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12162            ActivityInfo filterAi = filter.activity.info;
12163            for (int i=dest.size()-1; i>=0; i--) {
12164                ActivityInfo destAi = dest.get(i).activityInfo;
12165                if (destAi.name == filterAi.name
12166                        && destAi.packageName == filterAi.packageName) {
12167                    return false;
12168                }
12169            }
12170            return true;
12171        }
12172
12173        @Override
12174        protected ActivityIntentInfo[] newArray(int size) {
12175            return new ActivityIntentInfo[size];
12176        }
12177
12178        @Override
12179        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12180            if (!sUserManager.exists(userId)) return true;
12181            PackageParser.Package p = filter.activity.owner;
12182            if (p != null) {
12183                PackageSetting ps = (PackageSetting)p.mExtras;
12184                if (ps != null) {
12185                    // System apps are never considered stopped for purposes of
12186                    // filtering, because there may be no way for the user to
12187                    // actually re-launch them.
12188                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12189                            && ps.getStopped(userId);
12190                }
12191            }
12192            return false;
12193        }
12194
12195        @Override
12196        protected boolean isPackageForFilter(String packageName,
12197                PackageParser.ActivityIntentInfo info) {
12198            return packageName.equals(info.activity.owner.packageName);
12199        }
12200
12201        @Override
12202        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12203                int match, int userId) {
12204            if (!sUserManager.exists(userId)) return null;
12205            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12206                return null;
12207            }
12208            final PackageParser.Activity activity = info.activity;
12209            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12210            if (ps == null) {
12211                return null;
12212            }
12213            final PackageUserState userState = ps.readUserState(userId);
12214            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12215                    userState, userId);
12216            if (ai == null) {
12217                return null;
12218            }
12219            final boolean matchVisibleToInstantApp =
12220                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12221            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12222            // throw out filters that aren't visible to ephemeral apps
12223            if (matchVisibleToInstantApp
12224                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12225                return null;
12226            }
12227            // throw out ephemeral filters if we're not explicitly requesting them
12228            if (!isInstantApp && userState.instantApp) {
12229                return null;
12230            }
12231            final ResolveInfo res = new ResolveInfo();
12232            res.activityInfo = ai;
12233            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12234                res.filter = info;
12235            }
12236            if (info != null) {
12237                res.handleAllWebDataURI = info.handleAllWebDataURI();
12238            }
12239            res.priority = info.getPriority();
12240            res.preferredOrder = activity.owner.mPreferredOrder;
12241            //System.out.println("Result: " + res.activityInfo.className +
12242            //                   " = " + res.priority);
12243            res.match = match;
12244            res.isDefault = info.hasDefault;
12245            res.labelRes = info.labelRes;
12246            res.nonLocalizedLabel = info.nonLocalizedLabel;
12247            if (userNeedsBadging(userId)) {
12248                res.noResourceId = true;
12249            } else {
12250                res.icon = info.icon;
12251            }
12252            res.iconResourceId = info.icon;
12253            res.system = res.activityInfo.applicationInfo.isSystemApp();
12254            return res;
12255        }
12256
12257        @Override
12258        protected void sortResults(List<ResolveInfo> results) {
12259            Collections.sort(results, mResolvePrioritySorter);
12260        }
12261
12262        @Override
12263        protected void dumpFilter(PrintWriter out, String prefix,
12264                PackageParser.ActivityIntentInfo filter) {
12265            out.print(prefix); out.print(
12266                    Integer.toHexString(System.identityHashCode(filter.activity)));
12267                    out.print(' ');
12268                    filter.activity.printComponentShortName(out);
12269                    out.print(" filter ");
12270                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12271        }
12272
12273        @Override
12274        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12275            return filter.activity;
12276        }
12277
12278        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12279            PackageParser.Activity activity = (PackageParser.Activity)label;
12280            out.print(prefix); out.print(
12281                    Integer.toHexString(System.identityHashCode(activity)));
12282                    out.print(' ');
12283                    activity.printComponentShortName(out);
12284            if (count > 1) {
12285                out.print(" ("); out.print(count); out.print(" filters)");
12286            }
12287            out.println();
12288        }
12289
12290        // Keys are String (activity class name), values are Activity.
12291        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12292                = new ArrayMap<ComponentName, PackageParser.Activity>();
12293        private int mFlags;
12294    }
12295
12296    private final class ServiceIntentResolver
12297            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12298        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12299                boolean defaultOnly, int userId) {
12300            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12301            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12302        }
12303
12304        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12305                int userId) {
12306            if (!sUserManager.exists(userId)) return null;
12307            mFlags = flags;
12308            return super.queryIntent(intent, resolvedType,
12309                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12310                    userId);
12311        }
12312
12313        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12314                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12315            if (!sUserManager.exists(userId)) return null;
12316            if (packageServices == null) {
12317                return null;
12318            }
12319            mFlags = flags;
12320            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12321            final int N = packageServices.size();
12322            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12323                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12324
12325            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12326            for (int i = 0; i < N; ++i) {
12327                intentFilters = packageServices.get(i).intents;
12328                if (intentFilters != null && intentFilters.size() > 0) {
12329                    PackageParser.ServiceIntentInfo[] array =
12330                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12331                    intentFilters.toArray(array);
12332                    listCut.add(array);
12333                }
12334            }
12335            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12336        }
12337
12338        public final void addService(PackageParser.Service s) {
12339            mServices.put(s.getComponentName(), s);
12340            if (DEBUG_SHOW_INFO) {
12341                Log.v(TAG, "  "
12342                        + (s.info.nonLocalizedLabel != null
12343                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12344                Log.v(TAG, "    Class=" + s.info.name);
12345            }
12346            final int NI = s.intents.size();
12347            int j;
12348            for (j=0; j<NI; j++) {
12349                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12350                if (DEBUG_SHOW_INFO) {
12351                    Log.v(TAG, "    IntentFilter:");
12352                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12353                }
12354                if (!intent.debugCheck()) {
12355                    Log.w(TAG, "==> For Service " + s.info.name);
12356                }
12357                addFilter(intent);
12358            }
12359        }
12360
12361        public final void removeService(PackageParser.Service s) {
12362            mServices.remove(s.getComponentName());
12363            if (DEBUG_SHOW_INFO) {
12364                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12365                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12366                Log.v(TAG, "    Class=" + s.info.name);
12367            }
12368            final int NI = s.intents.size();
12369            int j;
12370            for (j=0; j<NI; j++) {
12371                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12372                if (DEBUG_SHOW_INFO) {
12373                    Log.v(TAG, "    IntentFilter:");
12374                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12375                }
12376                removeFilter(intent);
12377            }
12378        }
12379
12380        @Override
12381        protected boolean allowFilterResult(
12382                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12383            ServiceInfo filterSi = filter.service.info;
12384            for (int i=dest.size()-1; i>=0; i--) {
12385                ServiceInfo destAi = dest.get(i).serviceInfo;
12386                if (destAi.name == filterSi.name
12387                        && destAi.packageName == filterSi.packageName) {
12388                    return false;
12389                }
12390            }
12391            return true;
12392        }
12393
12394        @Override
12395        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12396            return new PackageParser.ServiceIntentInfo[size];
12397        }
12398
12399        @Override
12400        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12401            if (!sUserManager.exists(userId)) return true;
12402            PackageParser.Package p = filter.service.owner;
12403            if (p != null) {
12404                PackageSetting ps = (PackageSetting)p.mExtras;
12405                if (ps != null) {
12406                    // System apps are never considered stopped for purposes of
12407                    // filtering, because there may be no way for the user to
12408                    // actually re-launch them.
12409                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12410                            && ps.getStopped(userId);
12411                }
12412            }
12413            return false;
12414        }
12415
12416        @Override
12417        protected boolean isPackageForFilter(String packageName,
12418                PackageParser.ServiceIntentInfo info) {
12419            return packageName.equals(info.service.owner.packageName);
12420        }
12421
12422        @Override
12423        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12424                int match, int userId) {
12425            if (!sUserManager.exists(userId)) return null;
12426            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12427            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12428                return null;
12429            }
12430            final PackageParser.Service service = info.service;
12431            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12432            if (ps == null) {
12433                return null;
12434            }
12435            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12436                    ps.readUserState(userId), userId);
12437            if (si == null) {
12438                return null;
12439            }
12440            final ResolveInfo res = new ResolveInfo();
12441            res.serviceInfo = si;
12442            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12443                res.filter = filter;
12444            }
12445            res.priority = info.getPriority();
12446            res.preferredOrder = service.owner.mPreferredOrder;
12447            res.match = match;
12448            res.isDefault = info.hasDefault;
12449            res.labelRes = info.labelRes;
12450            res.nonLocalizedLabel = info.nonLocalizedLabel;
12451            res.icon = info.icon;
12452            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12453            return res;
12454        }
12455
12456        @Override
12457        protected void sortResults(List<ResolveInfo> results) {
12458            Collections.sort(results, mResolvePrioritySorter);
12459        }
12460
12461        @Override
12462        protected void dumpFilter(PrintWriter out, String prefix,
12463                PackageParser.ServiceIntentInfo filter) {
12464            out.print(prefix); out.print(
12465                    Integer.toHexString(System.identityHashCode(filter.service)));
12466                    out.print(' ');
12467                    filter.service.printComponentShortName(out);
12468                    out.print(" filter ");
12469                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12470        }
12471
12472        @Override
12473        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12474            return filter.service;
12475        }
12476
12477        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12478            PackageParser.Service service = (PackageParser.Service)label;
12479            out.print(prefix); out.print(
12480                    Integer.toHexString(System.identityHashCode(service)));
12481                    out.print(' ');
12482                    service.printComponentShortName(out);
12483            if (count > 1) {
12484                out.print(" ("); out.print(count); out.print(" filters)");
12485            }
12486            out.println();
12487        }
12488
12489//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12490//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12491//            final List<ResolveInfo> retList = Lists.newArrayList();
12492//            while (i.hasNext()) {
12493//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12494//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12495//                    retList.add(resolveInfo);
12496//                }
12497//            }
12498//            return retList;
12499//        }
12500
12501        // Keys are String (activity class name), values are Activity.
12502        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12503                = new ArrayMap<ComponentName, PackageParser.Service>();
12504        private int mFlags;
12505    }
12506
12507    private final class ProviderIntentResolver
12508            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12509        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12510                boolean defaultOnly, int userId) {
12511            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12512            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12513        }
12514
12515        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12516                int userId) {
12517            if (!sUserManager.exists(userId))
12518                return null;
12519            mFlags = flags;
12520            return super.queryIntent(intent, resolvedType,
12521                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12522                    userId);
12523        }
12524
12525        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12526                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12527            if (!sUserManager.exists(userId))
12528                return null;
12529            if (packageProviders == null) {
12530                return null;
12531            }
12532            mFlags = flags;
12533            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12534            final int N = packageProviders.size();
12535            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12536                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12537
12538            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12539            for (int i = 0; i < N; ++i) {
12540                intentFilters = packageProviders.get(i).intents;
12541                if (intentFilters != null && intentFilters.size() > 0) {
12542                    PackageParser.ProviderIntentInfo[] array =
12543                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12544                    intentFilters.toArray(array);
12545                    listCut.add(array);
12546                }
12547            }
12548            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12549        }
12550
12551        public final void addProvider(PackageParser.Provider p) {
12552            if (mProviders.containsKey(p.getComponentName())) {
12553                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12554                return;
12555            }
12556
12557            mProviders.put(p.getComponentName(), p);
12558            if (DEBUG_SHOW_INFO) {
12559                Log.v(TAG, "  "
12560                        + (p.info.nonLocalizedLabel != null
12561                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12562                Log.v(TAG, "    Class=" + p.info.name);
12563            }
12564            final int NI = p.intents.size();
12565            int j;
12566            for (j = 0; j < NI; j++) {
12567                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12568                if (DEBUG_SHOW_INFO) {
12569                    Log.v(TAG, "    IntentFilter:");
12570                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12571                }
12572                if (!intent.debugCheck()) {
12573                    Log.w(TAG, "==> For Provider " + p.info.name);
12574                }
12575                addFilter(intent);
12576            }
12577        }
12578
12579        public final void removeProvider(PackageParser.Provider p) {
12580            mProviders.remove(p.getComponentName());
12581            if (DEBUG_SHOW_INFO) {
12582                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12583                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12584                Log.v(TAG, "    Class=" + p.info.name);
12585            }
12586            final int NI = p.intents.size();
12587            int j;
12588            for (j = 0; j < NI; j++) {
12589                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12590                if (DEBUG_SHOW_INFO) {
12591                    Log.v(TAG, "    IntentFilter:");
12592                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12593                }
12594                removeFilter(intent);
12595            }
12596        }
12597
12598        @Override
12599        protected boolean allowFilterResult(
12600                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12601            ProviderInfo filterPi = filter.provider.info;
12602            for (int i = dest.size() - 1; i >= 0; i--) {
12603                ProviderInfo destPi = dest.get(i).providerInfo;
12604                if (destPi.name == filterPi.name
12605                        && destPi.packageName == filterPi.packageName) {
12606                    return false;
12607                }
12608            }
12609            return true;
12610        }
12611
12612        @Override
12613        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12614            return new PackageParser.ProviderIntentInfo[size];
12615        }
12616
12617        @Override
12618        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12619            if (!sUserManager.exists(userId))
12620                return true;
12621            PackageParser.Package p = filter.provider.owner;
12622            if (p != null) {
12623                PackageSetting ps = (PackageSetting) p.mExtras;
12624                if (ps != null) {
12625                    // System apps are never considered stopped for purposes of
12626                    // filtering, because there may be no way for the user to
12627                    // actually re-launch them.
12628                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12629                            && ps.getStopped(userId);
12630                }
12631            }
12632            return false;
12633        }
12634
12635        @Override
12636        protected boolean isPackageForFilter(String packageName,
12637                PackageParser.ProviderIntentInfo info) {
12638            return packageName.equals(info.provider.owner.packageName);
12639        }
12640
12641        @Override
12642        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12643                int match, int userId) {
12644            if (!sUserManager.exists(userId))
12645                return null;
12646            final PackageParser.ProviderIntentInfo info = filter;
12647            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12648                return null;
12649            }
12650            final PackageParser.Provider provider = info.provider;
12651            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12652            if (ps == null) {
12653                return null;
12654            }
12655            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12656                    ps.readUserState(userId), userId);
12657            if (pi == null) {
12658                return null;
12659            }
12660            final ResolveInfo res = new ResolveInfo();
12661            res.providerInfo = pi;
12662            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12663                res.filter = filter;
12664            }
12665            res.priority = info.getPriority();
12666            res.preferredOrder = provider.owner.mPreferredOrder;
12667            res.match = match;
12668            res.isDefault = info.hasDefault;
12669            res.labelRes = info.labelRes;
12670            res.nonLocalizedLabel = info.nonLocalizedLabel;
12671            res.icon = info.icon;
12672            res.system = res.providerInfo.applicationInfo.isSystemApp();
12673            return res;
12674        }
12675
12676        @Override
12677        protected void sortResults(List<ResolveInfo> results) {
12678            Collections.sort(results, mResolvePrioritySorter);
12679        }
12680
12681        @Override
12682        protected void dumpFilter(PrintWriter out, String prefix,
12683                PackageParser.ProviderIntentInfo filter) {
12684            out.print(prefix);
12685            out.print(
12686                    Integer.toHexString(System.identityHashCode(filter.provider)));
12687            out.print(' ');
12688            filter.provider.printComponentShortName(out);
12689            out.print(" filter ");
12690            out.println(Integer.toHexString(System.identityHashCode(filter)));
12691        }
12692
12693        @Override
12694        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12695            return filter.provider;
12696        }
12697
12698        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12699            PackageParser.Provider provider = (PackageParser.Provider)label;
12700            out.print(prefix); out.print(
12701                    Integer.toHexString(System.identityHashCode(provider)));
12702                    out.print(' ');
12703                    provider.printComponentShortName(out);
12704            if (count > 1) {
12705                out.print(" ("); out.print(count); out.print(" filters)");
12706            }
12707            out.println();
12708        }
12709
12710        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12711                = new ArrayMap<ComponentName, PackageParser.Provider>();
12712        private int mFlags;
12713    }
12714
12715    static final class EphemeralIntentResolver
12716            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12717        /**
12718         * The result that has the highest defined order. Ordering applies on a
12719         * per-package basis. Mapping is from package name to Pair of order and
12720         * EphemeralResolveInfo.
12721         * <p>
12722         * NOTE: This is implemented as a field variable for convenience and efficiency.
12723         * By having a field variable, we're able to track filter ordering as soon as
12724         * a non-zero order is defined. Otherwise, multiple loops across the result set
12725         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12726         * this needs to be contained entirely within {@link #filterResults()}.
12727         */
12728        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12729
12730        @Override
12731        protected EphemeralResponse[] newArray(int size) {
12732            return new EphemeralResponse[size];
12733        }
12734
12735        @Override
12736        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12737            return true;
12738        }
12739
12740        @Override
12741        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12742                int userId) {
12743            if (!sUserManager.exists(userId)) {
12744                return null;
12745            }
12746            final String packageName = responseObj.resolveInfo.getPackageName();
12747            final Integer order = responseObj.getOrder();
12748            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12749                    mOrderResult.get(packageName);
12750            // ordering is enabled and this item's order isn't high enough
12751            if (lastOrderResult != null && lastOrderResult.first >= order) {
12752                return null;
12753            }
12754            final EphemeralResolveInfo res = responseObj.resolveInfo;
12755            if (order > 0) {
12756                // non-zero order, enable ordering
12757                mOrderResult.put(packageName, new Pair<>(order, res));
12758            }
12759            return responseObj;
12760        }
12761
12762        @Override
12763        protected void filterResults(List<EphemeralResponse> results) {
12764            // only do work if ordering is enabled [most of the time it won't be]
12765            if (mOrderResult.size() == 0) {
12766                return;
12767            }
12768            int resultSize = results.size();
12769            for (int i = 0; i < resultSize; i++) {
12770                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12771                final String packageName = info.getPackageName();
12772                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12773                if (savedInfo == null) {
12774                    // package doesn't having ordering
12775                    continue;
12776                }
12777                if (savedInfo.second == info) {
12778                    // circled back to the highest ordered item; remove from order list
12779                    mOrderResult.remove(savedInfo);
12780                    if (mOrderResult.size() == 0) {
12781                        // no more ordered items
12782                        break;
12783                    }
12784                    continue;
12785                }
12786                // item has a worse order, remove it from the result list
12787                results.remove(i);
12788                resultSize--;
12789                i--;
12790            }
12791        }
12792    }
12793
12794    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12795            new Comparator<ResolveInfo>() {
12796        public int compare(ResolveInfo r1, ResolveInfo r2) {
12797            int v1 = r1.priority;
12798            int v2 = r2.priority;
12799            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12800            if (v1 != v2) {
12801                return (v1 > v2) ? -1 : 1;
12802            }
12803            v1 = r1.preferredOrder;
12804            v2 = r2.preferredOrder;
12805            if (v1 != v2) {
12806                return (v1 > v2) ? -1 : 1;
12807            }
12808            if (r1.isDefault != r2.isDefault) {
12809                return r1.isDefault ? -1 : 1;
12810            }
12811            v1 = r1.match;
12812            v2 = r2.match;
12813            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12814            if (v1 != v2) {
12815                return (v1 > v2) ? -1 : 1;
12816            }
12817            if (r1.system != r2.system) {
12818                return r1.system ? -1 : 1;
12819            }
12820            if (r1.activityInfo != null) {
12821                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12822            }
12823            if (r1.serviceInfo != null) {
12824                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12825            }
12826            if (r1.providerInfo != null) {
12827                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12828            }
12829            return 0;
12830        }
12831    };
12832
12833    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12834            new Comparator<ProviderInfo>() {
12835        public int compare(ProviderInfo p1, ProviderInfo p2) {
12836            final int v1 = p1.initOrder;
12837            final int v2 = p2.initOrder;
12838            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12839        }
12840    };
12841
12842    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12843            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12844            final int[] userIds) {
12845        mHandler.post(new Runnable() {
12846            @Override
12847            public void run() {
12848                try {
12849                    final IActivityManager am = ActivityManager.getService();
12850                    if (am == null) return;
12851                    final int[] resolvedUserIds;
12852                    if (userIds == null) {
12853                        resolvedUserIds = am.getRunningUserIds();
12854                    } else {
12855                        resolvedUserIds = userIds;
12856                    }
12857                    for (int id : resolvedUserIds) {
12858                        final Intent intent = new Intent(action,
12859                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12860                        if (extras != null) {
12861                            intent.putExtras(extras);
12862                        }
12863                        if (targetPkg != null) {
12864                            intent.setPackage(targetPkg);
12865                        }
12866                        // Modify the UID when posting to other users
12867                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12868                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12869                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12870                            intent.putExtra(Intent.EXTRA_UID, uid);
12871                        }
12872                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12873                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12874                        if (DEBUG_BROADCASTS) {
12875                            RuntimeException here = new RuntimeException("here");
12876                            here.fillInStackTrace();
12877                            Slog.d(TAG, "Sending to user " + id + ": "
12878                                    + intent.toShortString(false, true, false, false)
12879                                    + " " + intent.getExtras(), here);
12880                        }
12881                        am.broadcastIntent(null, intent, null, finishedReceiver,
12882                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12883                                null, finishedReceiver != null, false, id);
12884                    }
12885                } catch (RemoteException ex) {
12886                }
12887            }
12888        });
12889    }
12890
12891    /**
12892     * Check if the external storage media is available. This is true if there
12893     * is a mounted external storage medium or if the external storage is
12894     * emulated.
12895     */
12896    private boolean isExternalMediaAvailable() {
12897        return mMediaMounted || Environment.isExternalStorageEmulated();
12898    }
12899
12900    @Override
12901    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12902        // writer
12903        synchronized (mPackages) {
12904            if (!isExternalMediaAvailable()) {
12905                // If the external storage is no longer mounted at this point,
12906                // the caller may not have been able to delete all of this
12907                // packages files and can not delete any more.  Bail.
12908                return null;
12909            }
12910            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12911            if (lastPackage != null) {
12912                pkgs.remove(lastPackage);
12913            }
12914            if (pkgs.size() > 0) {
12915                return pkgs.get(0);
12916            }
12917        }
12918        return null;
12919    }
12920
12921    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12922        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12923                userId, andCode ? 1 : 0, packageName);
12924        if (mSystemReady) {
12925            msg.sendToTarget();
12926        } else {
12927            if (mPostSystemReadyMessages == null) {
12928                mPostSystemReadyMessages = new ArrayList<>();
12929            }
12930            mPostSystemReadyMessages.add(msg);
12931        }
12932    }
12933
12934    void startCleaningPackages() {
12935        // reader
12936        if (!isExternalMediaAvailable()) {
12937            return;
12938        }
12939        synchronized (mPackages) {
12940            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12941                return;
12942            }
12943        }
12944        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12945        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12946        IActivityManager am = ActivityManager.getService();
12947        if (am != null) {
12948            try {
12949                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12950                        UserHandle.USER_SYSTEM);
12951            } catch (RemoteException e) {
12952            }
12953        }
12954    }
12955
12956    @Override
12957    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12958            int installFlags, String installerPackageName, int userId) {
12959        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12960
12961        final int callingUid = Binder.getCallingUid();
12962        enforceCrossUserPermission(callingUid, userId,
12963                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12964
12965        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12966            try {
12967                if (observer != null) {
12968                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12969                }
12970            } catch (RemoteException re) {
12971            }
12972            return;
12973        }
12974
12975        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12976            installFlags |= PackageManager.INSTALL_FROM_ADB;
12977
12978        } else {
12979            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12980            // about installerPackageName.
12981
12982            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12983            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12984        }
12985
12986        UserHandle user;
12987        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12988            user = UserHandle.ALL;
12989        } else {
12990            user = new UserHandle(userId);
12991        }
12992
12993        // Only system components can circumvent runtime permissions when installing.
12994        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12995                && mContext.checkCallingOrSelfPermission(Manifest.permission
12996                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12997            throw new SecurityException("You need the "
12998                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12999                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13000        }
13001
13002        final File originFile = new File(originPath);
13003        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13004
13005        final Message msg = mHandler.obtainMessage(INIT_COPY);
13006        final VerificationInfo verificationInfo = new VerificationInfo(
13007                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13008        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13009                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13010                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13011                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13012        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13013        msg.obj = params;
13014
13015        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13016                System.identityHashCode(msg.obj));
13017        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13018                System.identityHashCode(msg.obj));
13019
13020        mHandler.sendMessage(msg);
13021    }
13022
13023
13024    /**
13025     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13026     * it is acting on behalf on an enterprise or the user).
13027     *
13028     * Note that the ordering of the conditionals in this method is important. The checks we perform
13029     * are as follows, in this order:
13030     *
13031     * 1) If the install is being performed by a system app, we can trust the app to have set the
13032     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13033     *    what it is.
13034     * 2) If the install is being performed by a device or profile owner app, the install reason
13035     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13036     *    set the install reason correctly. If the app targets an older SDK version where install
13037     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13038     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13039     * 3) In all other cases, the install is being performed by a regular app that is neither part
13040     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13041     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13042     *    set to enterprise policy and if so, change it to unknown instead.
13043     */
13044    private int fixUpInstallReason(String installerPackageName, int installerUid,
13045            int installReason) {
13046        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13047                == PERMISSION_GRANTED) {
13048            // If the install is being performed by a system app, we trust that app to have set the
13049            // install reason correctly.
13050            return installReason;
13051        }
13052
13053        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13054            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13055        if (dpm != null) {
13056            ComponentName owner = null;
13057            try {
13058                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13059                if (owner == null) {
13060                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13061                }
13062            } catch (RemoteException e) {
13063            }
13064            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13065                // If the install is being performed by a device or profile owner, the install
13066                // reason should be enterprise policy.
13067                return PackageManager.INSTALL_REASON_POLICY;
13068            }
13069        }
13070
13071        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13072            // If the install is being performed by a regular app (i.e. neither system app nor
13073            // device or profile owner), we have no reason to believe that the app is acting on
13074            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13075            // change it to unknown instead.
13076            return PackageManager.INSTALL_REASON_UNKNOWN;
13077        }
13078
13079        // If the install is being performed by a regular app and the install reason was set to any
13080        // value but enterprise policy, leave the install reason unchanged.
13081        return installReason;
13082    }
13083
13084    void installStage(String packageName, File stagedDir, String stagedCid,
13085            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13086            String installerPackageName, int installerUid, UserHandle user,
13087            Certificate[][] certificates) {
13088        if (DEBUG_EPHEMERAL) {
13089            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13090                Slog.d(TAG, "Ephemeral install of " + packageName);
13091            }
13092        }
13093        final VerificationInfo verificationInfo = new VerificationInfo(
13094                sessionParams.originatingUri, sessionParams.referrerUri,
13095                sessionParams.originatingUid, installerUid);
13096
13097        final OriginInfo origin;
13098        if (stagedDir != null) {
13099            origin = OriginInfo.fromStagedFile(stagedDir);
13100        } else {
13101            origin = OriginInfo.fromStagedContainer(stagedCid);
13102        }
13103
13104        final Message msg = mHandler.obtainMessage(INIT_COPY);
13105        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13106                sessionParams.installReason);
13107        final InstallParams params = new InstallParams(origin, null, observer,
13108                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13109                verificationInfo, user, sessionParams.abiOverride,
13110                sessionParams.grantedRuntimePermissions, certificates, installReason);
13111        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13112        msg.obj = params;
13113
13114        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13115                System.identityHashCode(msg.obj));
13116        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13117                System.identityHashCode(msg.obj));
13118
13119        mHandler.sendMessage(msg);
13120    }
13121
13122    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13123            int userId) {
13124        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13125        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13126    }
13127
13128    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13129            int appId, int... userIds) {
13130        if (ArrayUtils.isEmpty(userIds)) {
13131            return;
13132        }
13133        Bundle extras = new Bundle(1);
13134        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13135        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13136
13137        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13138                packageName, extras, 0, null, null, userIds);
13139        if (isSystem) {
13140            mHandler.post(() -> {
13141                        for (int userId : userIds) {
13142                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13143                        }
13144                    }
13145            );
13146        }
13147    }
13148
13149    /**
13150     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13151     * automatically without needing an explicit launch.
13152     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13153     */
13154    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13155        // If user is not running, the app didn't miss any broadcast
13156        if (!mUserManagerInternal.isUserRunning(userId)) {
13157            return;
13158        }
13159        final IActivityManager am = ActivityManager.getService();
13160        try {
13161            // Deliver LOCKED_BOOT_COMPLETED first
13162            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13163                    .setPackage(packageName);
13164            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13165            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13166                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13167
13168            // Deliver BOOT_COMPLETED only if user is unlocked
13169            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13170                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13171                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13172                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13173            }
13174        } catch (RemoteException e) {
13175            throw e.rethrowFromSystemServer();
13176        }
13177    }
13178
13179    @Override
13180    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13181            int userId) {
13182        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13183        PackageSetting pkgSetting;
13184        final int uid = Binder.getCallingUid();
13185        enforceCrossUserPermission(uid, userId,
13186                true /* requireFullPermission */, true /* checkShell */,
13187                "setApplicationHiddenSetting for user " + userId);
13188
13189        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13190            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13191            return false;
13192        }
13193
13194        long callingId = Binder.clearCallingIdentity();
13195        try {
13196            boolean sendAdded = false;
13197            boolean sendRemoved = false;
13198            // writer
13199            synchronized (mPackages) {
13200                pkgSetting = mSettings.mPackages.get(packageName);
13201                if (pkgSetting == null) {
13202                    return false;
13203                }
13204                // Do not allow "android" is being disabled
13205                if ("android".equals(packageName)) {
13206                    Slog.w(TAG, "Cannot hide package: android");
13207                    return false;
13208                }
13209                // Cannot hide static shared libs as they are considered
13210                // a part of the using app (emulating static linking). Also
13211                // static libs are installed always on internal storage.
13212                PackageParser.Package pkg = mPackages.get(packageName);
13213                if (pkg != null && pkg.staticSharedLibName != null) {
13214                    Slog.w(TAG, "Cannot hide package: " + packageName
13215                            + " providing static shared library: "
13216                            + pkg.staticSharedLibName);
13217                    return false;
13218                }
13219                // Only allow protected packages to hide themselves.
13220                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13221                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13222                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13223                    return false;
13224                }
13225
13226                if (pkgSetting.getHidden(userId) != hidden) {
13227                    pkgSetting.setHidden(hidden, userId);
13228                    mSettings.writePackageRestrictionsLPr(userId);
13229                    if (hidden) {
13230                        sendRemoved = true;
13231                    } else {
13232                        sendAdded = true;
13233                    }
13234                }
13235            }
13236            if (sendAdded) {
13237                sendPackageAddedForUser(packageName, pkgSetting, userId);
13238                return true;
13239            }
13240            if (sendRemoved) {
13241                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13242                        "hiding pkg");
13243                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13244                return true;
13245            }
13246        } finally {
13247            Binder.restoreCallingIdentity(callingId);
13248        }
13249        return false;
13250    }
13251
13252    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13253            int userId) {
13254        final PackageRemovedInfo info = new PackageRemovedInfo();
13255        info.removedPackage = packageName;
13256        info.removedUsers = new int[] {userId};
13257        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13258        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13259    }
13260
13261    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13262        if (pkgList.length > 0) {
13263            Bundle extras = new Bundle(1);
13264            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13265
13266            sendPackageBroadcast(
13267                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13268                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13269                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13270                    new int[] {userId});
13271        }
13272    }
13273
13274    /**
13275     * Returns true if application is not found or there was an error. Otherwise it returns
13276     * the hidden state of the package for the given user.
13277     */
13278    @Override
13279    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13280        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13281        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13282                true /* requireFullPermission */, false /* checkShell */,
13283                "getApplicationHidden for user " + userId);
13284        PackageSetting pkgSetting;
13285        long callingId = Binder.clearCallingIdentity();
13286        try {
13287            // writer
13288            synchronized (mPackages) {
13289                pkgSetting = mSettings.mPackages.get(packageName);
13290                if (pkgSetting == null) {
13291                    return true;
13292                }
13293                return pkgSetting.getHidden(userId);
13294            }
13295        } finally {
13296            Binder.restoreCallingIdentity(callingId);
13297        }
13298    }
13299
13300    /**
13301     * @hide
13302     */
13303    @Override
13304    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13305            int installReason) {
13306        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13307                null);
13308        PackageSetting pkgSetting;
13309        final int uid = Binder.getCallingUid();
13310        enforceCrossUserPermission(uid, userId,
13311                true /* requireFullPermission */, true /* checkShell */,
13312                "installExistingPackage for user " + userId);
13313        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13314            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13315        }
13316
13317        long callingId = Binder.clearCallingIdentity();
13318        try {
13319            boolean installed = false;
13320            final boolean instantApp =
13321                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13322            final boolean fullApp =
13323                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13324
13325            // writer
13326            synchronized (mPackages) {
13327                pkgSetting = mSettings.mPackages.get(packageName);
13328                if (pkgSetting == null) {
13329                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13330                }
13331                if (!pkgSetting.getInstalled(userId)) {
13332                    pkgSetting.setInstalled(true, userId);
13333                    pkgSetting.setHidden(false, userId);
13334                    pkgSetting.setInstallReason(installReason, userId);
13335                    mSettings.writePackageRestrictionsLPr(userId);
13336                    mSettings.writeKernelMappingLPr(pkgSetting);
13337                    installed = true;
13338                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13339                    // upgrade app from instant to full; we don't allow app downgrade
13340                    installed = true;
13341                }
13342                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13343            }
13344
13345            if (installed) {
13346                if (pkgSetting.pkg != null) {
13347                    synchronized (mInstallLock) {
13348                        // We don't need to freeze for a brand new install
13349                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13350                    }
13351                }
13352                sendPackageAddedForUser(packageName, pkgSetting, userId);
13353                synchronized (mPackages) {
13354                    updateSequenceNumberLP(packageName, new int[]{ userId });
13355                }
13356            }
13357        } finally {
13358            Binder.restoreCallingIdentity(callingId);
13359        }
13360
13361        return PackageManager.INSTALL_SUCCEEDED;
13362    }
13363
13364    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13365            boolean instantApp, boolean fullApp) {
13366        // no state specified; do nothing
13367        if (!instantApp && !fullApp) {
13368            return;
13369        }
13370        if (userId != UserHandle.USER_ALL) {
13371            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13372                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13373            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13374                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13375            }
13376        } else {
13377            for (int currentUserId : sUserManager.getUserIds()) {
13378                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13379                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13380                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13381                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13382                }
13383            }
13384        }
13385    }
13386
13387    boolean isUserRestricted(int userId, String restrictionKey) {
13388        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13389        if (restrictions.getBoolean(restrictionKey, false)) {
13390            Log.w(TAG, "User is restricted: " + restrictionKey);
13391            return true;
13392        }
13393        return false;
13394    }
13395
13396    @Override
13397    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13398            int userId) {
13399        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13400        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13401                true /* requireFullPermission */, true /* checkShell */,
13402                "setPackagesSuspended for user " + userId);
13403
13404        if (ArrayUtils.isEmpty(packageNames)) {
13405            return packageNames;
13406        }
13407
13408        // List of package names for whom the suspended state has changed.
13409        List<String> changedPackages = new ArrayList<>(packageNames.length);
13410        // List of package names for whom the suspended state is not set as requested in this
13411        // method.
13412        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13413        long callingId = Binder.clearCallingIdentity();
13414        try {
13415            for (int i = 0; i < packageNames.length; i++) {
13416                String packageName = packageNames[i];
13417                boolean changed = false;
13418                final int appId;
13419                synchronized (mPackages) {
13420                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13421                    if (pkgSetting == null) {
13422                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13423                                + "\". Skipping suspending/un-suspending.");
13424                        unactionedPackages.add(packageName);
13425                        continue;
13426                    }
13427                    appId = pkgSetting.appId;
13428                    if (pkgSetting.getSuspended(userId) != suspended) {
13429                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13430                            unactionedPackages.add(packageName);
13431                            continue;
13432                        }
13433                        pkgSetting.setSuspended(suspended, userId);
13434                        mSettings.writePackageRestrictionsLPr(userId);
13435                        changed = true;
13436                        changedPackages.add(packageName);
13437                    }
13438                }
13439
13440                if (changed && suspended) {
13441                    killApplication(packageName, UserHandle.getUid(userId, appId),
13442                            "suspending package");
13443                }
13444            }
13445        } finally {
13446            Binder.restoreCallingIdentity(callingId);
13447        }
13448
13449        if (!changedPackages.isEmpty()) {
13450            sendPackagesSuspendedForUser(changedPackages.toArray(
13451                    new String[changedPackages.size()]), userId, suspended);
13452        }
13453
13454        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13455    }
13456
13457    @Override
13458    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13459        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13460                true /* requireFullPermission */, false /* checkShell */,
13461                "isPackageSuspendedForUser for user " + userId);
13462        synchronized (mPackages) {
13463            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13464            if (pkgSetting == null) {
13465                throw new IllegalArgumentException("Unknown target package: " + packageName);
13466            }
13467            return pkgSetting.getSuspended(userId);
13468        }
13469    }
13470
13471    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13472        if (isPackageDeviceAdmin(packageName, userId)) {
13473            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13474                    + "\": has an active device admin");
13475            return false;
13476        }
13477
13478        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13479        if (packageName.equals(activeLauncherPackageName)) {
13480            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13481                    + "\": contains the active launcher");
13482            return false;
13483        }
13484
13485        if (packageName.equals(mRequiredInstallerPackage)) {
13486            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13487                    + "\": required for package installation");
13488            return false;
13489        }
13490
13491        if (packageName.equals(mRequiredUninstallerPackage)) {
13492            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13493                    + "\": required for package uninstallation");
13494            return false;
13495        }
13496
13497        if (packageName.equals(mRequiredVerifierPackage)) {
13498            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13499                    + "\": required for package verification");
13500            return false;
13501        }
13502
13503        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13504            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13505                    + "\": is the default dialer");
13506            return false;
13507        }
13508
13509        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13510            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13511                    + "\": protected package");
13512            return false;
13513        }
13514
13515        // Cannot suspend static shared libs as they are considered
13516        // a part of the using app (emulating static linking). Also
13517        // static libs are installed always on internal storage.
13518        PackageParser.Package pkg = mPackages.get(packageName);
13519        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13520            Slog.w(TAG, "Cannot suspend package: " + packageName
13521                    + " providing static shared library: "
13522                    + pkg.staticSharedLibName);
13523            return false;
13524        }
13525
13526        return true;
13527    }
13528
13529    private String getActiveLauncherPackageName(int userId) {
13530        Intent intent = new Intent(Intent.ACTION_MAIN);
13531        intent.addCategory(Intent.CATEGORY_HOME);
13532        ResolveInfo resolveInfo = resolveIntent(
13533                intent,
13534                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13535                PackageManager.MATCH_DEFAULT_ONLY,
13536                userId);
13537
13538        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13539    }
13540
13541    private String getDefaultDialerPackageName(int userId) {
13542        synchronized (mPackages) {
13543            return mSettings.getDefaultDialerPackageNameLPw(userId);
13544        }
13545    }
13546
13547    @Override
13548    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13549        mContext.enforceCallingOrSelfPermission(
13550                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13551                "Only package verification agents can verify applications");
13552
13553        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13554        final PackageVerificationResponse response = new PackageVerificationResponse(
13555                verificationCode, Binder.getCallingUid());
13556        msg.arg1 = id;
13557        msg.obj = response;
13558        mHandler.sendMessage(msg);
13559    }
13560
13561    @Override
13562    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13563            long millisecondsToDelay) {
13564        mContext.enforceCallingOrSelfPermission(
13565                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13566                "Only package verification agents can extend verification timeouts");
13567
13568        final PackageVerificationState state = mPendingVerification.get(id);
13569        final PackageVerificationResponse response = new PackageVerificationResponse(
13570                verificationCodeAtTimeout, Binder.getCallingUid());
13571
13572        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13573            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13574        }
13575        if (millisecondsToDelay < 0) {
13576            millisecondsToDelay = 0;
13577        }
13578        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13579                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13580            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13581        }
13582
13583        if ((state != null) && !state.timeoutExtended()) {
13584            state.extendTimeout();
13585
13586            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13587            msg.arg1 = id;
13588            msg.obj = response;
13589            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13590        }
13591    }
13592
13593    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13594            int verificationCode, UserHandle user) {
13595        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13596        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13597        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13598        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13599        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13600
13601        mContext.sendBroadcastAsUser(intent, user,
13602                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13603    }
13604
13605    private ComponentName matchComponentForVerifier(String packageName,
13606            List<ResolveInfo> receivers) {
13607        ActivityInfo targetReceiver = null;
13608
13609        final int NR = receivers.size();
13610        for (int i = 0; i < NR; i++) {
13611            final ResolveInfo info = receivers.get(i);
13612            if (info.activityInfo == null) {
13613                continue;
13614            }
13615
13616            if (packageName.equals(info.activityInfo.packageName)) {
13617                targetReceiver = info.activityInfo;
13618                break;
13619            }
13620        }
13621
13622        if (targetReceiver == null) {
13623            return null;
13624        }
13625
13626        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13627    }
13628
13629    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13630            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13631        if (pkgInfo.verifiers.length == 0) {
13632            return null;
13633        }
13634
13635        final int N = pkgInfo.verifiers.length;
13636        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13637        for (int i = 0; i < N; i++) {
13638            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13639
13640            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13641                    receivers);
13642            if (comp == null) {
13643                continue;
13644            }
13645
13646            final int verifierUid = getUidForVerifier(verifierInfo);
13647            if (verifierUid == -1) {
13648                continue;
13649            }
13650
13651            if (DEBUG_VERIFY) {
13652                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13653                        + " with the correct signature");
13654            }
13655            sufficientVerifiers.add(comp);
13656            verificationState.addSufficientVerifier(verifierUid);
13657        }
13658
13659        return sufficientVerifiers;
13660    }
13661
13662    private int getUidForVerifier(VerifierInfo verifierInfo) {
13663        synchronized (mPackages) {
13664            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13665            if (pkg == null) {
13666                return -1;
13667            } else if (pkg.mSignatures.length != 1) {
13668                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13669                        + " has more than one signature; ignoring");
13670                return -1;
13671            }
13672
13673            /*
13674             * If the public key of the package's signature does not match
13675             * our expected public key, then this is a different package and
13676             * we should skip.
13677             */
13678
13679            final byte[] expectedPublicKey;
13680            try {
13681                final Signature verifierSig = pkg.mSignatures[0];
13682                final PublicKey publicKey = verifierSig.getPublicKey();
13683                expectedPublicKey = publicKey.getEncoded();
13684            } catch (CertificateException e) {
13685                return -1;
13686            }
13687
13688            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13689
13690            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13691                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13692                        + " does not have the expected public key; ignoring");
13693                return -1;
13694            }
13695
13696            return pkg.applicationInfo.uid;
13697        }
13698    }
13699
13700    @Override
13701    public void finishPackageInstall(int token, boolean didLaunch) {
13702        enforceSystemOrRoot("Only the system is allowed to finish installs");
13703
13704        if (DEBUG_INSTALL) {
13705            Slog.v(TAG, "BM finishing package install for " + token);
13706        }
13707        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13708
13709        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13710        mHandler.sendMessage(msg);
13711    }
13712
13713    /**
13714     * Get the verification agent timeout.
13715     *
13716     * @return verification timeout in milliseconds
13717     */
13718    private long getVerificationTimeout() {
13719        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13720                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13721                DEFAULT_VERIFICATION_TIMEOUT);
13722    }
13723
13724    /**
13725     * Get the default verification agent response code.
13726     *
13727     * @return default verification response code
13728     */
13729    private int getDefaultVerificationResponse() {
13730        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13731                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13732                DEFAULT_VERIFICATION_RESPONSE);
13733    }
13734
13735    /**
13736     * Check whether or not package verification has been enabled.
13737     *
13738     * @return true if verification should be performed
13739     */
13740    private boolean isVerificationEnabled(int userId, int installFlags) {
13741        if (!DEFAULT_VERIFY_ENABLE) {
13742            return false;
13743        }
13744        // Ephemeral apps don't get the full verification treatment
13745        if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13746            if (DEBUG_EPHEMERAL) {
13747                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13748            }
13749            return false;
13750        }
13751
13752        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13753
13754        // Check if installing from ADB
13755        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13756            // Do not run verification in a test harness environment
13757            if (ActivityManager.isRunningInTestHarness()) {
13758                return false;
13759            }
13760            if (ensureVerifyAppsEnabled) {
13761                return true;
13762            }
13763            // Check if the developer does not want package verification for ADB installs
13764            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13765                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13766                return false;
13767            }
13768        }
13769
13770        if (ensureVerifyAppsEnabled) {
13771            return true;
13772        }
13773
13774        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13775                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13776    }
13777
13778    @Override
13779    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13780            throws RemoteException {
13781        mContext.enforceCallingOrSelfPermission(
13782                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13783                "Only intentfilter verification agents can verify applications");
13784
13785        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13786        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13787                Binder.getCallingUid(), verificationCode, failedDomains);
13788        msg.arg1 = id;
13789        msg.obj = response;
13790        mHandler.sendMessage(msg);
13791    }
13792
13793    @Override
13794    public int getIntentVerificationStatus(String packageName, int userId) {
13795        synchronized (mPackages) {
13796            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13797        }
13798    }
13799
13800    @Override
13801    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13802        mContext.enforceCallingOrSelfPermission(
13803                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13804
13805        boolean result = false;
13806        synchronized (mPackages) {
13807            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13808        }
13809        if (result) {
13810            scheduleWritePackageRestrictionsLocked(userId);
13811        }
13812        return result;
13813    }
13814
13815    @Override
13816    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13817            String packageName) {
13818        synchronized (mPackages) {
13819            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13820        }
13821    }
13822
13823    @Override
13824    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13825        if (TextUtils.isEmpty(packageName)) {
13826            return ParceledListSlice.emptyList();
13827        }
13828        synchronized (mPackages) {
13829            PackageParser.Package pkg = mPackages.get(packageName);
13830            if (pkg == null || pkg.activities == null) {
13831                return ParceledListSlice.emptyList();
13832            }
13833            final int count = pkg.activities.size();
13834            ArrayList<IntentFilter> result = new ArrayList<>();
13835            for (int n=0; n<count; n++) {
13836                PackageParser.Activity activity = pkg.activities.get(n);
13837                if (activity.intents != null && activity.intents.size() > 0) {
13838                    result.addAll(activity.intents);
13839                }
13840            }
13841            return new ParceledListSlice<>(result);
13842        }
13843    }
13844
13845    @Override
13846    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13847        mContext.enforceCallingOrSelfPermission(
13848                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13849
13850        synchronized (mPackages) {
13851            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13852            if (packageName != null) {
13853                result |= updateIntentVerificationStatus(packageName,
13854                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13855                        userId);
13856                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13857                        packageName, userId);
13858            }
13859            return result;
13860        }
13861    }
13862
13863    @Override
13864    public String getDefaultBrowserPackageName(int userId) {
13865        synchronized (mPackages) {
13866            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13867        }
13868    }
13869
13870    /**
13871     * Get the "allow unknown sources" setting.
13872     *
13873     * @return the current "allow unknown sources" setting
13874     */
13875    private int getUnknownSourcesSettings() {
13876        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13877                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13878                -1);
13879    }
13880
13881    @Override
13882    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13883        final int uid = Binder.getCallingUid();
13884        // writer
13885        synchronized (mPackages) {
13886            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13887            if (targetPackageSetting == null) {
13888                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13889            }
13890
13891            PackageSetting installerPackageSetting;
13892            if (installerPackageName != null) {
13893                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13894                if (installerPackageSetting == null) {
13895                    throw new IllegalArgumentException("Unknown installer package: "
13896                            + installerPackageName);
13897                }
13898            } else {
13899                installerPackageSetting = null;
13900            }
13901
13902            Signature[] callerSignature;
13903            Object obj = mSettings.getUserIdLPr(uid);
13904            if (obj != null) {
13905                if (obj instanceof SharedUserSetting) {
13906                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13907                } else if (obj instanceof PackageSetting) {
13908                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13909                } else {
13910                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13911                }
13912            } else {
13913                throw new SecurityException("Unknown calling UID: " + uid);
13914            }
13915
13916            // Verify: can't set installerPackageName to a package that is
13917            // not signed with the same cert as the caller.
13918            if (installerPackageSetting != null) {
13919                if (compareSignatures(callerSignature,
13920                        installerPackageSetting.signatures.mSignatures)
13921                        != PackageManager.SIGNATURE_MATCH) {
13922                    throw new SecurityException(
13923                            "Caller does not have same cert as new installer package "
13924                            + installerPackageName);
13925                }
13926            }
13927
13928            // Verify: if target already has an installer package, it must
13929            // be signed with the same cert as the caller.
13930            if (targetPackageSetting.installerPackageName != null) {
13931                PackageSetting setting = mSettings.mPackages.get(
13932                        targetPackageSetting.installerPackageName);
13933                // If the currently set package isn't valid, then it's always
13934                // okay to change it.
13935                if (setting != null) {
13936                    if (compareSignatures(callerSignature,
13937                            setting.signatures.mSignatures)
13938                            != PackageManager.SIGNATURE_MATCH) {
13939                        throw new SecurityException(
13940                                "Caller does not have same cert as old installer package "
13941                                + targetPackageSetting.installerPackageName);
13942                    }
13943                }
13944            }
13945
13946            // Okay!
13947            targetPackageSetting.installerPackageName = installerPackageName;
13948            if (installerPackageName != null) {
13949                mSettings.mInstallerPackages.add(installerPackageName);
13950            }
13951            scheduleWriteSettingsLocked();
13952        }
13953    }
13954
13955    @Override
13956    public void setApplicationCategoryHint(String packageName, int categoryHint,
13957            String callerPackageName) {
13958        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13959                callerPackageName);
13960        synchronized (mPackages) {
13961            PackageSetting ps = mSettings.mPackages.get(packageName);
13962            if (ps == null) {
13963                throw new IllegalArgumentException("Unknown target package " + packageName);
13964            }
13965
13966            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13967                throw new IllegalArgumentException("Calling package " + callerPackageName
13968                        + " is not installer for " + packageName);
13969            }
13970
13971            if (ps.categoryHint != categoryHint) {
13972                ps.categoryHint = categoryHint;
13973                scheduleWriteSettingsLocked();
13974            }
13975        }
13976    }
13977
13978    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13979        // Queue up an async operation since the package installation may take a little while.
13980        mHandler.post(new Runnable() {
13981            public void run() {
13982                mHandler.removeCallbacks(this);
13983                 // Result object to be returned
13984                PackageInstalledInfo res = new PackageInstalledInfo();
13985                res.setReturnCode(currentStatus);
13986                res.uid = -1;
13987                res.pkg = null;
13988                res.removedInfo = null;
13989                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13990                    args.doPreInstall(res.returnCode);
13991                    synchronized (mInstallLock) {
13992                        installPackageTracedLI(args, res);
13993                    }
13994                    args.doPostInstall(res.returnCode, res.uid);
13995                }
13996
13997                // A restore should be performed at this point if (a) the install
13998                // succeeded, (b) the operation is not an update, and (c) the new
13999                // package has not opted out of backup participation.
14000                final boolean update = res.removedInfo != null
14001                        && res.removedInfo.removedPackage != null;
14002                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14003                boolean doRestore = !update
14004                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14005
14006                // Set up the post-install work request bookkeeping.  This will be used
14007                // and cleaned up by the post-install event handling regardless of whether
14008                // there's a restore pass performed.  Token values are >= 1.
14009                int token;
14010                if (mNextInstallToken < 0) mNextInstallToken = 1;
14011                token = mNextInstallToken++;
14012
14013                PostInstallData data = new PostInstallData(args, res);
14014                mRunningInstalls.put(token, data);
14015                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14016
14017                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14018                    // Pass responsibility to the Backup Manager.  It will perform a
14019                    // restore if appropriate, then pass responsibility back to the
14020                    // Package Manager to run the post-install observer callbacks
14021                    // and broadcasts.
14022                    IBackupManager bm = IBackupManager.Stub.asInterface(
14023                            ServiceManager.getService(Context.BACKUP_SERVICE));
14024                    if (bm != null) {
14025                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14026                                + " to BM for possible restore");
14027                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14028                        try {
14029                            // TODO: http://b/22388012
14030                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14031                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14032                            } else {
14033                                doRestore = false;
14034                            }
14035                        } catch (RemoteException e) {
14036                            // can't happen; the backup manager is local
14037                        } catch (Exception e) {
14038                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14039                            doRestore = false;
14040                        }
14041                    } else {
14042                        Slog.e(TAG, "Backup Manager not found!");
14043                        doRestore = false;
14044                    }
14045                }
14046
14047                if (!doRestore) {
14048                    // No restore possible, or the Backup Manager was mysteriously not
14049                    // available -- just fire the post-install work request directly.
14050                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14051
14052                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14053
14054                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14055                    mHandler.sendMessage(msg);
14056                }
14057            }
14058        });
14059    }
14060
14061    /**
14062     * Callback from PackageSettings whenever an app is first transitioned out of the
14063     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14064     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14065     * here whether the app is the target of an ongoing install, and only send the
14066     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14067     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14068     * handling.
14069     */
14070    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14071        // Serialize this with the rest of the install-process message chain.  In the
14072        // restore-at-install case, this Runnable will necessarily run before the
14073        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14074        // are coherent.  In the non-restore case, the app has already completed install
14075        // and been launched through some other means, so it is not in a problematic
14076        // state for observers to see the FIRST_LAUNCH signal.
14077        mHandler.post(new Runnable() {
14078            @Override
14079            public void run() {
14080                for (int i = 0; i < mRunningInstalls.size(); i++) {
14081                    final PostInstallData data = mRunningInstalls.valueAt(i);
14082                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14083                        continue;
14084                    }
14085                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14086                        // right package; but is it for the right user?
14087                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14088                            if (userId == data.res.newUsers[uIndex]) {
14089                                if (DEBUG_BACKUP) {
14090                                    Slog.i(TAG, "Package " + pkgName
14091                                            + " being restored so deferring FIRST_LAUNCH");
14092                                }
14093                                return;
14094                            }
14095                        }
14096                    }
14097                }
14098                // didn't find it, so not being restored
14099                if (DEBUG_BACKUP) {
14100                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14101                }
14102                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14103            }
14104        });
14105    }
14106
14107    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14108        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14109                installerPkg, null, userIds);
14110    }
14111
14112    private abstract class HandlerParams {
14113        private static final int MAX_RETRIES = 4;
14114
14115        /**
14116         * Number of times startCopy() has been attempted and had a non-fatal
14117         * error.
14118         */
14119        private int mRetries = 0;
14120
14121        /** User handle for the user requesting the information or installation. */
14122        private final UserHandle mUser;
14123        String traceMethod;
14124        int traceCookie;
14125
14126        HandlerParams(UserHandle user) {
14127            mUser = user;
14128        }
14129
14130        UserHandle getUser() {
14131            return mUser;
14132        }
14133
14134        HandlerParams setTraceMethod(String traceMethod) {
14135            this.traceMethod = traceMethod;
14136            return this;
14137        }
14138
14139        HandlerParams setTraceCookie(int traceCookie) {
14140            this.traceCookie = traceCookie;
14141            return this;
14142        }
14143
14144        final boolean startCopy() {
14145            boolean res;
14146            try {
14147                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14148
14149                if (++mRetries > MAX_RETRIES) {
14150                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14151                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14152                    handleServiceError();
14153                    return false;
14154                } else {
14155                    handleStartCopy();
14156                    res = true;
14157                }
14158            } catch (RemoteException e) {
14159                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14160                mHandler.sendEmptyMessage(MCS_RECONNECT);
14161                res = false;
14162            }
14163            handleReturnCode();
14164            return res;
14165        }
14166
14167        final void serviceError() {
14168            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14169            handleServiceError();
14170            handleReturnCode();
14171        }
14172
14173        abstract void handleStartCopy() throws RemoteException;
14174        abstract void handleServiceError();
14175        abstract void handleReturnCode();
14176    }
14177
14178    class MeasureParams extends HandlerParams {
14179        private final PackageStats mStats;
14180        private boolean mSuccess;
14181
14182        private final IPackageStatsObserver mObserver;
14183
14184        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14185            super(new UserHandle(stats.userHandle));
14186            mObserver = observer;
14187            mStats = stats;
14188        }
14189
14190        @Override
14191        public String toString() {
14192            return "MeasureParams{"
14193                + Integer.toHexString(System.identityHashCode(this))
14194                + " " + mStats.packageName + "}";
14195        }
14196
14197        @Override
14198        void handleStartCopy() throws RemoteException {
14199            synchronized (mInstallLock) {
14200                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14201            }
14202
14203            if (mSuccess) {
14204                boolean mounted = false;
14205                try {
14206                    final String status = Environment.getExternalStorageState();
14207                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14208                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14209                } catch (Exception e) {
14210                }
14211
14212                if (mounted) {
14213                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14214
14215                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14216                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14217
14218                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14219                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14220
14221                    // Always subtract cache size, since it's a subdirectory
14222                    mStats.externalDataSize -= mStats.externalCacheSize;
14223
14224                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14225                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14226
14227                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14228                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14229                }
14230            }
14231        }
14232
14233        @Override
14234        void handleReturnCode() {
14235            if (mObserver != null) {
14236                try {
14237                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14238                } catch (RemoteException e) {
14239                    Slog.i(TAG, "Observer no longer exists.");
14240                }
14241            }
14242        }
14243
14244        @Override
14245        void handleServiceError() {
14246            Slog.e(TAG, "Could not measure application " + mStats.packageName
14247                            + " external storage");
14248        }
14249    }
14250
14251    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14252            throws RemoteException {
14253        long result = 0;
14254        for (File path : paths) {
14255            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14256        }
14257        return result;
14258    }
14259
14260    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14261        for (File path : paths) {
14262            try {
14263                mcs.clearDirectory(path.getAbsolutePath());
14264            } catch (RemoteException e) {
14265            }
14266        }
14267    }
14268
14269    static class OriginInfo {
14270        /**
14271         * Location where install is coming from, before it has been
14272         * copied/renamed into place. This could be a single monolithic APK
14273         * file, or a cluster directory. This location may be untrusted.
14274         */
14275        final File file;
14276        final String cid;
14277
14278        /**
14279         * Flag indicating that {@link #file} or {@link #cid} has already been
14280         * staged, meaning downstream users don't need to defensively copy the
14281         * contents.
14282         */
14283        final boolean staged;
14284
14285        /**
14286         * Flag indicating that {@link #file} or {@link #cid} is an already
14287         * installed app that is being moved.
14288         */
14289        final boolean existing;
14290
14291        final String resolvedPath;
14292        final File resolvedFile;
14293
14294        static OriginInfo fromNothing() {
14295            return new OriginInfo(null, null, false, false);
14296        }
14297
14298        static OriginInfo fromUntrustedFile(File file) {
14299            return new OriginInfo(file, null, false, false);
14300        }
14301
14302        static OriginInfo fromExistingFile(File file) {
14303            return new OriginInfo(file, null, false, true);
14304        }
14305
14306        static OriginInfo fromStagedFile(File file) {
14307            return new OriginInfo(file, null, true, false);
14308        }
14309
14310        static OriginInfo fromStagedContainer(String cid) {
14311            return new OriginInfo(null, cid, true, false);
14312        }
14313
14314        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14315            this.file = file;
14316            this.cid = cid;
14317            this.staged = staged;
14318            this.existing = existing;
14319
14320            if (cid != null) {
14321                resolvedPath = PackageHelper.getSdDir(cid);
14322                resolvedFile = new File(resolvedPath);
14323            } else if (file != null) {
14324                resolvedPath = file.getAbsolutePath();
14325                resolvedFile = file;
14326            } else {
14327                resolvedPath = null;
14328                resolvedFile = null;
14329            }
14330        }
14331    }
14332
14333    static class MoveInfo {
14334        final int moveId;
14335        final String fromUuid;
14336        final String toUuid;
14337        final String packageName;
14338        final String dataAppName;
14339        final int appId;
14340        final String seinfo;
14341        final int targetSdkVersion;
14342
14343        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14344                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14345            this.moveId = moveId;
14346            this.fromUuid = fromUuid;
14347            this.toUuid = toUuid;
14348            this.packageName = packageName;
14349            this.dataAppName = dataAppName;
14350            this.appId = appId;
14351            this.seinfo = seinfo;
14352            this.targetSdkVersion = targetSdkVersion;
14353        }
14354    }
14355
14356    static class VerificationInfo {
14357        /** A constant used to indicate that a uid value is not present. */
14358        public static final int NO_UID = -1;
14359
14360        /** URI referencing where the package was downloaded from. */
14361        final Uri originatingUri;
14362
14363        /** HTTP referrer URI associated with the originatingURI. */
14364        final Uri referrer;
14365
14366        /** UID of the application that the install request originated from. */
14367        final int originatingUid;
14368
14369        /** UID of application requesting the install */
14370        final int installerUid;
14371
14372        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14373            this.originatingUri = originatingUri;
14374            this.referrer = referrer;
14375            this.originatingUid = originatingUid;
14376            this.installerUid = installerUid;
14377        }
14378    }
14379
14380    class InstallParams extends HandlerParams {
14381        final OriginInfo origin;
14382        final MoveInfo move;
14383        final IPackageInstallObserver2 observer;
14384        int installFlags;
14385        final String installerPackageName;
14386        final String volumeUuid;
14387        private InstallArgs mArgs;
14388        private int mRet;
14389        final String packageAbiOverride;
14390        final String[] grantedRuntimePermissions;
14391        final VerificationInfo verificationInfo;
14392        final Certificate[][] certificates;
14393        final int installReason;
14394
14395        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14396                int installFlags, String installerPackageName, String volumeUuid,
14397                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14398                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14399            super(user);
14400            this.origin = origin;
14401            this.move = move;
14402            this.observer = observer;
14403            this.installFlags = installFlags;
14404            this.installerPackageName = installerPackageName;
14405            this.volumeUuid = volumeUuid;
14406            this.verificationInfo = verificationInfo;
14407            this.packageAbiOverride = packageAbiOverride;
14408            this.grantedRuntimePermissions = grantedPermissions;
14409            this.certificates = certificates;
14410            this.installReason = installReason;
14411        }
14412
14413        @Override
14414        public String toString() {
14415            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14416                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14417        }
14418
14419        private int installLocationPolicy(PackageInfoLite pkgLite) {
14420            String packageName = pkgLite.packageName;
14421            int installLocation = pkgLite.installLocation;
14422            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14423            // reader
14424            synchronized (mPackages) {
14425                // Currently installed package which the new package is attempting to replace or
14426                // null if no such package is installed.
14427                PackageParser.Package installedPkg = mPackages.get(packageName);
14428                // Package which currently owns the data which the new package will own if installed.
14429                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14430                // will be null whereas dataOwnerPkg will contain information about the package
14431                // which was uninstalled while keeping its data.
14432                PackageParser.Package dataOwnerPkg = installedPkg;
14433                if (dataOwnerPkg  == null) {
14434                    PackageSetting ps = mSettings.mPackages.get(packageName);
14435                    if (ps != null) {
14436                        dataOwnerPkg = ps.pkg;
14437                    }
14438                }
14439
14440                if (dataOwnerPkg != null) {
14441                    // If installed, the package will get access to data left on the device by its
14442                    // predecessor. As a security measure, this is permited only if this is not a
14443                    // version downgrade or if the predecessor package is marked as debuggable and
14444                    // a downgrade is explicitly requested.
14445                    //
14446                    // On debuggable platform builds, downgrades are permitted even for
14447                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14448                    // not offer security guarantees and thus it's OK to disable some security
14449                    // mechanisms to make debugging/testing easier on those builds. However, even on
14450                    // debuggable builds downgrades of packages are permitted only if requested via
14451                    // installFlags. This is because we aim to keep the behavior of debuggable
14452                    // platform builds as close as possible to the behavior of non-debuggable
14453                    // platform builds.
14454                    final boolean downgradeRequested =
14455                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14456                    final boolean packageDebuggable =
14457                                (dataOwnerPkg.applicationInfo.flags
14458                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14459                    final boolean downgradePermitted =
14460                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14461                    if (!downgradePermitted) {
14462                        try {
14463                            checkDowngrade(dataOwnerPkg, pkgLite);
14464                        } catch (PackageManagerException e) {
14465                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14466                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14467                        }
14468                    }
14469                }
14470
14471                if (installedPkg != null) {
14472                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14473                        // Check for updated system application.
14474                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14475                            if (onSd) {
14476                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14477                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14478                            }
14479                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14480                        } else {
14481                            if (onSd) {
14482                                // Install flag overrides everything.
14483                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14484                            }
14485                            // If current upgrade specifies particular preference
14486                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14487                                // Application explicitly specified internal.
14488                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14489                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14490                                // App explictly prefers external. Let policy decide
14491                            } else {
14492                                // Prefer previous location
14493                                if (isExternal(installedPkg)) {
14494                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14495                                }
14496                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14497                            }
14498                        }
14499                    } else {
14500                        // Invalid install. Return error code
14501                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14502                    }
14503                }
14504            }
14505            // All the special cases have been taken care of.
14506            // Return result based on recommended install location.
14507            if (onSd) {
14508                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14509            }
14510            return pkgLite.recommendedInstallLocation;
14511        }
14512
14513        /*
14514         * Invoke remote method to get package information and install
14515         * location values. Override install location based on default
14516         * policy if needed and then create install arguments based
14517         * on the install location.
14518         */
14519        public void handleStartCopy() throws RemoteException {
14520            int ret = PackageManager.INSTALL_SUCCEEDED;
14521
14522            // If we're already staged, we've firmly committed to an install location
14523            if (origin.staged) {
14524                if (origin.file != null) {
14525                    installFlags |= PackageManager.INSTALL_INTERNAL;
14526                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14527                } else if (origin.cid != null) {
14528                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14529                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14530                } else {
14531                    throw new IllegalStateException("Invalid stage location");
14532                }
14533            }
14534
14535            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14536            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14537            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14538            PackageInfoLite pkgLite = null;
14539
14540            if (onInt && onSd) {
14541                // Check if both bits are set.
14542                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14543                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14544            } else if (onSd && ephemeral) {
14545                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14546                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14547            } else {
14548                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14549                        packageAbiOverride);
14550
14551                if (DEBUG_EPHEMERAL && ephemeral) {
14552                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14553                }
14554
14555                /*
14556                 * If we have too little free space, try to free cache
14557                 * before giving up.
14558                 */
14559                if (!origin.staged && pkgLite.recommendedInstallLocation
14560                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14561                    // TODO: focus freeing disk space on the target device
14562                    final StorageManager storage = StorageManager.from(mContext);
14563                    final long lowThreshold = storage.getStorageLowBytes(
14564                            Environment.getDataDirectory());
14565
14566                    final long sizeBytes = mContainerService.calculateInstalledSize(
14567                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14568
14569                    try {
14570                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14571                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14572                                installFlags, packageAbiOverride);
14573                    } catch (InstallerException e) {
14574                        Slog.w(TAG, "Failed to free cache", e);
14575                    }
14576
14577                    /*
14578                     * The cache free must have deleted the file we
14579                     * downloaded to install.
14580                     *
14581                     * TODO: fix the "freeCache" call to not delete
14582                     *       the file we care about.
14583                     */
14584                    if (pkgLite.recommendedInstallLocation
14585                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14586                        pkgLite.recommendedInstallLocation
14587                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14588                    }
14589                }
14590            }
14591
14592            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14593                int loc = pkgLite.recommendedInstallLocation;
14594                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14595                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14596                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14597                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14598                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14599                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14600                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14601                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14602                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14603                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14604                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14605                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14606                } else {
14607                    // Override with defaults if needed.
14608                    loc = installLocationPolicy(pkgLite);
14609                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14610                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14611                    } else if (!onSd && !onInt) {
14612                        // Override install location with flags
14613                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14614                            // Set the flag to install on external media.
14615                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14616                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14617                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14618                            if (DEBUG_EPHEMERAL) {
14619                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14620                            }
14621                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14622                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14623                                    |PackageManager.INSTALL_INTERNAL);
14624                        } else {
14625                            // Make sure the flag for installing on external
14626                            // media is unset
14627                            installFlags |= PackageManager.INSTALL_INTERNAL;
14628                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14629                        }
14630                    }
14631                }
14632            }
14633
14634            final InstallArgs args = createInstallArgs(this);
14635            mArgs = args;
14636
14637            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14638                // TODO: http://b/22976637
14639                // Apps installed for "all" users use the device owner to verify the app
14640                UserHandle verifierUser = getUser();
14641                if (verifierUser == UserHandle.ALL) {
14642                    verifierUser = UserHandle.SYSTEM;
14643                }
14644
14645                /*
14646                 * Determine if we have any installed package verifiers. If we
14647                 * do, then we'll defer to them to verify the packages.
14648                 */
14649                final int requiredUid = mRequiredVerifierPackage == null ? -1
14650                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14651                                verifierUser.getIdentifier());
14652                if (!origin.existing && requiredUid != -1
14653                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14654                    final Intent verification = new Intent(
14655                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14656                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14657                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14658                            PACKAGE_MIME_TYPE);
14659                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14660
14661                    // Query all live verifiers based on current user state
14662                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14663                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14664
14665                    if (DEBUG_VERIFY) {
14666                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14667                                + verification.toString() + " with " + pkgLite.verifiers.length
14668                                + " optional verifiers");
14669                    }
14670
14671                    final int verificationId = mPendingVerificationToken++;
14672
14673                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14674
14675                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14676                            installerPackageName);
14677
14678                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14679                            installFlags);
14680
14681                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14682                            pkgLite.packageName);
14683
14684                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14685                            pkgLite.versionCode);
14686
14687                    if (verificationInfo != null) {
14688                        if (verificationInfo.originatingUri != null) {
14689                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14690                                    verificationInfo.originatingUri);
14691                        }
14692                        if (verificationInfo.referrer != null) {
14693                            verification.putExtra(Intent.EXTRA_REFERRER,
14694                                    verificationInfo.referrer);
14695                        }
14696                        if (verificationInfo.originatingUid >= 0) {
14697                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14698                                    verificationInfo.originatingUid);
14699                        }
14700                        if (verificationInfo.installerUid >= 0) {
14701                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14702                                    verificationInfo.installerUid);
14703                        }
14704                    }
14705
14706                    final PackageVerificationState verificationState = new PackageVerificationState(
14707                            requiredUid, args);
14708
14709                    mPendingVerification.append(verificationId, verificationState);
14710
14711                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14712                            receivers, verificationState);
14713
14714                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14715                    final long idleDuration = getVerificationTimeout();
14716
14717                    /*
14718                     * If any sufficient verifiers were listed in the package
14719                     * manifest, attempt to ask them.
14720                     */
14721                    if (sufficientVerifiers != null) {
14722                        final int N = sufficientVerifiers.size();
14723                        if (N == 0) {
14724                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14725                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14726                        } else {
14727                            for (int i = 0; i < N; i++) {
14728                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14729                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14730                                        verifierComponent.getPackageName(), idleDuration,
14731                                        verifierUser.getIdentifier(), false, "package verifier");
14732
14733                                final Intent sufficientIntent = new Intent(verification);
14734                                sufficientIntent.setComponent(verifierComponent);
14735                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14736                            }
14737                        }
14738                    }
14739
14740                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14741                            mRequiredVerifierPackage, receivers);
14742                    if (ret == PackageManager.INSTALL_SUCCEEDED
14743                            && mRequiredVerifierPackage != null) {
14744                        Trace.asyncTraceBegin(
14745                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14746                        /*
14747                         * Send the intent to the required verification agent,
14748                         * but only start the verification timeout after the
14749                         * target BroadcastReceivers have run.
14750                         */
14751                        verification.setComponent(requiredVerifierComponent);
14752                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14753                                requiredVerifierComponent.getPackageName(), idleDuration,
14754                                verifierUser.getIdentifier(), false, "package verifier");
14755                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14756                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14757                                new BroadcastReceiver() {
14758                                    @Override
14759                                    public void onReceive(Context context, Intent intent) {
14760                                        final Message msg = mHandler
14761                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14762                                        msg.arg1 = verificationId;
14763                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14764                                    }
14765                                }, null, 0, null, null);
14766
14767                        /*
14768                         * We don't want the copy to proceed until verification
14769                         * succeeds, so null out this field.
14770                         */
14771                        mArgs = null;
14772                    }
14773                } else {
14774                    /*
14775                     * No package verification is enabled, so immediately start
14776                     * the remote call to initiate copy using temporary file.
14777                     */
14778                    ret = args.copyApk(mContainerService, true);
14779                }
14780            }
14781
14782            mRet = ret;
14783        }
14784
14785        @Override
14786        void handleReturnCode() {
14787            // If mArgs is null, then MCS couldn't be reached. When it
14788            // reconnects, it will try again to install. At that point, this
14789            // will succeed.
14790            if (mArgs != null) {
14791                processPendingInstall(mArgs, mRet);
14792            }
14793        }
14794
14795        @Override
14796        void handleServiceError() {
14797            mArgs = createInstallArgs(this);
14798            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14799        }
14800
14801        public boolean isForwardLocked() {
14802            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14803        }
14804    }
14805
14806    /**
14807     * Used during creation of InstallArgs
14808     *
14809     * @param installFlags package installation flags
14810     * @return true if should be installed on external storage
14811     */
14812    private static boolean installOnExternalAsec(int installFlags) {
14813        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14814            return false;
14815        }
14816        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14817            return true;
14818        }
14819        return false;
14820    }
14821
14822    /**
14823     * Used during creation of InstallArgs
14824     *
14825     * @param installFlags package installation flags
14826     * @return true if should be installed as forward locked
14827     */
14828    private static boolean installForwardLocked(int installFlags) {
14829        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14830    }
14831
14832    private InstallArgs createInstallArgs(InstallParams params) {
14833        if (params.move != null) {
14834            return new MoveInstallArgs(params);
14835        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14836            return new AsecInstallArgs(params);
14837        } else {
14838            return new FileInstallArgs(params);
14839        }
14840    }
14841
14842    /**
14843     * Create args that describe an existing installed package. Typically used
14844     * when cleaning up old installs, or used as a move source.
14845     */
14846    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14847            String resourcePath, String[] instructionSets) {
14848        final boolean isInAsec;
14849        if (installOnExternalAsec(installFlags)) {
14850            /* Apps on SD card are always in ASEC containers. */
14851            isInAsec = true;
14852        } else if (installForwardLocked(installFlags)
14853                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14854            /*
14855             * Forward-locked apps are only in ASEC containers if they're the
14856             * new style
14857             */
14858            isInAsec = true;
14859        } else {
14860            isInAsec = false;
14861        }
14862
14863        if (isInAsec) {
14864            return new AsecInstallArgs(codePath, instructionSets,
14865                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14866        } else {
14867            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14868        }
14869    }
14870
14871    static abstract class InstallArgs {
14872        /** @see InstallParams#origin */
14873        final OriginInfo origin;
14874        /** @see InstallParams#move */
14875        final MoveInfo move;
14876
14877        final IPackageInstallObserver2 observer;
14878        // Always refers to PackageManager flags only
14879        final int installFlags;
14880        final String installerPackageName;
14881        final String volumeUuid;
14882        final UserHandle user;
14883        final String abiOverride;
14884        final String[] installGrantPermissions;
14885        /** If non-null, drop an async trace when the install completes */
14886        final String traceMethod;
14887        final int traceCookie;
14888        final Certificate[][] certificates;
14889        final int installReason;
14890
14891        // The list of instruction sets supported by this app. This is currently
14892        // only used during the rmdex() phase to clean up resources. We can get rid of this
14893        // if we move dex files under the common app path.
14894        /* nullable */ String[] instructionSets;
14895
14896        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14897                int installFlags, String installerPackageName, String volumeUuid,
14898                UserHandle user, String[] instructionSets,
14899                String abiOverride, String[] installGrantPermissions,
14900                String traceMethod, int traceCookie, Certificate[][] certificates,
14901                int installReason) {
14902            this.origin = origin;
14903            this.move = move;
14904            this.installFlags = installFlags;
14905            this.observer = observer;
14906            this.installerPackageName = installerPackageName;
14907            this.volumeUuid = volumeUuid;
14908            this.user = user;
14909            this.instructionSets = instructionSets;
14910            this.abiOverride = abiOverride;
14911            this.installGrantPermissions = installGrantPermissions;
14912            this.traceMethod = traceMethod;
14913            this.traceCookie = traceCookie;
14914            this.certificates = certificates;
14915            this.installReason = installReason;
14916        }
14917
14918        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14919        abstract int doPreInstall(int status);
14920
14921        /**
14922         * Rename package into final resting place. All paths on the given
14923         * scanned package should be updated to reflect the rename.
14924         */
14925        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14926        abstract int doPostInstall(int status, int uid);
14927
14928        /** @see PackageSettingBase#codePathString */
14929        abstract String getCodePath();
14930        /** @see PackageSettingBase#resourcePathString */
14931        abstract String getResourcePath();
14932
14933        // Need installer lock especially for dex file removal.
14934        abstract void cleanUpResourcesLI();
14935        abstract boolean doPostDeleteLI(boolean delete);
14936
14937        /**
14938         * Called before the source arguments are copied. This is used mostly
14939         * for MoveParams when it needs to read the source file to put it in the
14940         * destination.
14941         */
14942        int doPreCopy() {
14943            return PackageManager.INSTALL_SUCCEEDED;
14944        }
14945
14946        /**
14947         * Called after the source arguments are copied. This is used mostly for
14948         * MoveParams when it needs to read the source file to put it in the
14949         * destination.
14950         */
14951        int doPostCopy(int uid) {
14952            return PackageManager.INSTALL_SUCCEEDED;
14953        }
14954
14955        protected boolean isFwdLocked() {
14956            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14957        }
14958
14959        protected boolean isExternalAsec() {
14960            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14961        }
14962
14963        protected boolean isEphemeral() {
14964            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14965        }
14966
14967        UserHandle getUser() {
14968            return user;
14969        }
14970    }
14971
14972    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14973        if (!allCodePaths.isEmpty()) {
14974            if (instructionSets == null) {
14975                throw new IllegalStateException("instructionSet == null");
14976            }
14977            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14978            for (String codePath : allCodePaths) {
14979                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14980                    try {
14981                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14982                    } catch (InstallerException ignored) {
14983                    }
14984                }
14985            }
14986        }
14987    }
14988
14989    /**
14990     * Logic to handle installation of non-ASEC applications, including copying
14991     * and renaming logic.
14992     */
14993    class FileInstallArgs extends InstallArgs {
14994        private File codeFile;
14995        private File resourceFile;
14996
14997        // Example topology:
14998        // /data/app/com.example/base.apk
14999        // /data/app/com.example/split_foo.apk
15000        // /data/app/com.example/lib/arm/libfoo.so
15001        // /data/app/com.example/lib/arm64/libfoo.so
15002        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15003
15004        /** New install */
15005        FileInstallArgs(InstallParams params) {
15006            super(params.origin, params.move, params.observer, params.installFlags,
15007                    params.installerPackageName, params.volumeUuid,
15008                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15009                    params.grantedRuntimePermissions,
15010                    params.traceMethod, params.traceCookie, params.certificates,
15011                    params.installReason);
15012            if (isFwdLocked()) {
15013                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15014            }
15015        }
15016
15017        /** Existing install */
15018        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15019            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15020                    null, null, null, 0, null /*certificates*/,
15021                    PackageManager.INSTALL_REASON_UNKNOWN);
15022            this.codeFile = (codePath != null) ? new File(codePath) : null;
15023            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15024        }
15025
15026        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15027            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15028            try {
15029                return doCopyApk(imcs, temp);
15030            } finally {
15031                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15032            }
15033        }
15034
15035        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15036            if (origin.staged) {
15037                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15038                codeFile = origin.file;
15039                resourceFile = origin.file;
15040                return PackageManager.INSTALL_SUCCEEDED;
15041            }
15042
15043            try {
15044                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15045                final File tempDir =
15046                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15047                codeFile = tempDir;
15048                resourceFile = tempDir;
15049            } catch (IOException e) {
15050                Slog.w(TAG, "Failed to create copy file: " + e);
15051                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15052            }
15053
15054            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15055                @Override
15056                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15057                    if (!FileUtils.isValidExtFilename(name)) {
15058                        throw new IllegalArgumentException("Invalid filename: " + name);
15059                    }
15060                    try {
15061                        final File file = new File(codeFile, name);
15062                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15063                                O_RDWR | O_CREAT, 0644);
15064                        Os.chmod(file.getAbsolutePath(), 0644);
15065                        return new ParcelFileDescriptor(fd);
15066                    } catch (ErrnoException e) {
15067                        throw new RemoteException("Failed to open: " + e.getMessage());
15068                    }
15069                }
15070            };
15071
15072            int ret = PackageManager.INSTALL_SUCCEEDED;
15073            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15074            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15075                Slog.e(TAG, "Failed to copy package");
15076                return ret;
15077            }
15078
15079            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15080            NativeLibraryHelper.Handle handle = null;
15081            try {
15082                handle = NativeLibraryHelper.Handle.create(codeFile);
15083                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15084                        abiOverride);
15085            } catch (IOException e) {
15086                Slog.e(TAG, "Copying native libraries failed", e);
15087                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15088            } finally {
15089                IoUtils.closeQuietly(handle);
15090            }
15091
15092            return ret;
15093        }
15094
15095        int doPreInstall(int status) {
15096            if (status != PackageManager.INSTALL_SUCCEEDED) {
15097                cleanUp();
15098            }
15099            return status;
15100        }
15101
15102        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15103            if (status != PackageManager.INSTALL_SUCCEEDED) {
15104                cleanUp();
15105                return false;
15106            }
15107
15108            final File targetDir = codeFile.getParentFile();
15109            final File beforeCodeFile = codeFile;
15110            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15111
15112            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15113            try {
15114                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15115            } catch (ErrnoException e) {
15116                Slog.w(TAG, "Failed to rename", e);
15117                return false;
15118            }
15119
15120            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15121                Slog.w(TAG, "Failed to restorecon");
15122                return false;
15123            }
15124
15125            // Reflect the rename internally
15126            codeFile = afterCodeFile;
15127            resourceFile = afterCodeFile;
15128
15129            // Reflect the rename in scanned details
15130            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15131            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15132                    afterCodeFile, pkg.baseCodePath));
15133            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15134                    afterCodeFile, pkg.splitCodePaths));
15135
15136            // Reflect the rename in app info
15137            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15138            pkg.setApplicationInfoCodePath(pkg.codePath);
15139            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15140            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15141            pkg.setApplicationInfoResourcePath(pkg.codePath);
15142            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15143            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15144
15145            return true;
15146        }
15147
15148        int doPostInstall(int status, int uid) {
15149            if (status != PackageManager.INSTALL_SUCCEEDED) {
15150                cleanUp();
15151            }
15152            return status;
15153        }
15154
15155        @Override
15156        String getCodePath() {
15157            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15158        }
15159
15160        @Override
15161        String getResourcePath() {
15162            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15163        }
15164
15165        private boolean cleanUp() {
15166            if (codeFile == null || !codeFile.exists()) {
15167                return false;
15168            }
15169
15170            removeCodePathLI(codeFile);
15171
15172            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15173                resourceFile.delete();
15174            }
15175
15176            return true;
15177        }
15178
15179        void cleanUpResourcesLI() {
15180            // Try enumerating all code paths before deleting
15181            List<String> allCodePaths = Collections.EMPTY_LIST;
15182            if (codeFile != null && codeFile.exists()) {
15183                try {
15184                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15185                    allCodePaths = pkg.getAllCodePaths();
15186                } catch (PackageParserException e) {
15187                    // Ignored; we tried our best
15188                }
15189            }
15190
15191            cleanUp();
15192            removeDexFiles(allCodePaths, instructionSets);
15193        }
15194
15195        boolean doPostDeleteLI(boolean delete) {
15196            // XXX err, shouldn't we respect the delete flag?
15197            cleanUpResourcesLI();
15198            return true;
15199        }
15200    }
15201
15202    private boolean isAsecExternal(String cid) {
15203        final String asecPath = PackageHelper.getSdFilesystem(cid);
15204        return !asecPath.startsWith(mAsecInternalPath);
15205    }
15206
15207    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15208            PackageManagerException {
15209        if (copyRet < 0) {
15210            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15211                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15212                throw new PackageManagerException(copyRet, message);
15213            }
15214        }
15215    }
15216
15217    /**
15218     * Extract the StorageManagerService "container ID" from the full code path of an
15219     * .apk.
15220     */
15221    static String cidFromCodePath(String fullCodePath) {
15222        int eidx = fullCodePath.lastIndexOf("/");
15223        String subStr1 = fullCodePath.substring(0, eidx);
15224        int sidx = subStr1.lastIndexOf("/");
15225        return subStr1.substring(sidx+1, eidx);
15226    }
15227
15228    /**
15229     * Logic to handle installation of ASEC applications, including copying and
15230     * renaming logic.
15231     */
15232    class AsecInstallArgs extends InstallArgs {
15233        static final String RES_FILE_NAME = "pkg.apk";
15234        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15235
15236        String cid;
15237        String packagePath;
15238        String resourcePath;
15239
15240        /** New install */
15241        AsecInstallArgs(InstallParams params) {
15242            super(params.origin, params.move, params.observer, params.installFlags,
15243                    params.installerPackageName, params.volumeUuid,
15244                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15245                    params.grantedRuntimePermissions,
15246                    params.traceMethod, params.traceCookie, params.certificates,
15247                    params.installReason);
15248        }
15249
15250        /** Existing install */
15251        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15252                        boolean isExternal, boolean isForwardLocked) {
15253            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15254                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15255                    instructionSets, null, null, null, 0, null /*certificates*/,
15256                    PackageManager.INSTALL_REASON_UNKNOWN);
15257            // Hackily pretend we're still looking at a full code path
15258            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15259                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15260            }
15261
15262            // Extract cid from fullCodePath
15263            int eidx = fullCodePath.lastIndexOf("/");
15264            String subStr1 = fullCodePath.substring(0, eidx);
15265            int sidx = subStr1.lastIndexOf("/");
15266            cid = subStr1.substring(sidx+1, eidx);
15267            setMountPath(subStr1);
15268        }
15269
15270        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15271            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15272                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15273                    instructionSets, null, null, null, 0, null /*certificates*/,
15274                    PackageManager.INSTALL_REASON_UNKNOWN);
15275            this.cid = cid;
15276            setMountPath(PackageHelper.getSdDir(cid));
15277        }
15278
15279        void createCopyFile() {
15280            cid = mInstallerService.allocateExternalStageCidLegacy();
15281        }
15282
15283        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15284            if (origin.staged && origin.cid != null) {
15285                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15286                cid = origin.cid;
15287                setMountPath(PackageHelper.getSdDir(cid));
15288                return PackageManager.INSTALL_SUCCEEDED;
15289            }
15290
15291            if (temp) {
15292                createCopyFile();
15293            } else {
15294                /*
15295                 * Pre-emptively destroy the container since it's destroyed if
15296                 * copying fails due to it existing anyway.
15297                 */
15298                PackageHelper.destroySdDir(cid);
15299            }
15300
15301            final String newMountPath = imcs.copyPackageToContainer(
15302                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15303                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15304
15305            if (newMountPath != null) {
15306                setMountPath(newMountPath);
15307                return PackageManager.INSTALL_SUCCEEDED;
15308            } else {
15309                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15310            }
15311        }
15312
15313        @Override
15314        String getCodePath() {
15315            return packagePath;
15316        }
15317
15318        @Override
15319        String getResourcePath() {
15320            return resourcePath;
15321        }
15322
15323        int doPreInstall(int status) {
15324            if (status != PackageManager.INSTALL_SUCCEEDED) {
15325                // Destroy container
15326                PackageHelper.destroySdDir(cid);
15327            } else {
15328                boolean mounted = PackageHelper.isContainerMounted(cid);
15329                if (!mounted) {
15330                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15331                            Process.SYSTEM_UID);
15332                    if (newMountPath != null) {
15333                        setMountPath(newMountPath);
15334                    } else {
15335                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15336                    }
15337                }
15338            }
15339            return status;
15340        }
15341
15342        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15343            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15344            String newMountPath = null;
15345            if (PackageHelper.isContainerMounted(cid)) {
15346                // Unmount the container
15347                if (!PackageHelper.unMountSdDir(cid)) {
15348                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15349                    return false;
15350                }
15351            }
15352            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15353                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15354                        " which might be stale. Will try to clean up.");
15355                // Clean up the stale container and proceed to recreate.
15356                if (!PackageHelper.destroySdDir(newCacheId)) {
15357                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15358                    return false;
15359                }
15360                // Successfully cleaned up stale container. Try to rename again.
15361                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15362                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15363                            + " inspite of cleaning it up.");
15364                    return false;
15365                }
15366            }
15367            if (!PackageHelper.isContainerMounted(newCacheId)) {
15368                Slog.w(TAG, "Mounting container " + newCacheId);
15369                newMountPath = PackageHelper.mountSdDir(newCacheId,
15370                        getEncryptKey(), Process.SYSTEM_UID);
15371            } else {
15372                newMountPath = PackageHelper.getSdDir(newCacheId);
15373            }
15374            if (newMountPath == null) {
15375                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15376                return false;
15377            }
15378            Log.i(TAG, "Succesfully renamed " + cid +
15379                    " to " + newCacheId +
15380                    " at new path: " + newMountPath);
15381            cid = newCacheId;
15382
15383            final File beforeCodeFile = new File(packagePath);
15384            setMountPath(newMountPath);
15385            final File afterCodeFile = new File(packagePath);
15386
15387            // Reflect the rename in scanned details
15388            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15389            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15390                    afterCodeFile, pkg.baseCodePath));
15391            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15392                    afterCodeFile, pkg.splitCodePaths));
15393
15394            // Reflect the rename in app info
15395            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15396            pkg.setApplicationInfoCodePath(pkg.codePath);
15397            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15398            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15399            pkg.setApplicationInfoResourcePath(pkg.codePath);
15400            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15401            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15402
15403            return true;
15404        }
15405
15406        private void setMountPath(String mountPath) {
15407            final File mountFile = new File(mountPath);
15408
15409            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15410            if (monolithicFile.exists()) {
15411                packagePath = monolithicFile.getAbsolutePath();
15412                if (isFwdLocked()) {
15413                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15414                } else {
15415                    resourcePath = packagePath;
15416                }
15417            } else {
15418                packagePath = mountFile.getAbsolutePath();
15419                resourcePath = packagePath;
15420            }
15421        }
15422
15423        int doPostInstall(int status, int uid) {
15424            if (status != PackageManager.INSTALL_SUCCEEDED) {
15425                cleanUp();
15426            } else {
15427                final int groupOwner;
15428                final String protectedFile;
15429                if (isFwdLocked()) {
15430                    groupOwner = UserHandle.getSharedAppGid(uid);
15431                    protectedFile = RES_FILE_NAME;
15432                } else {
15433                    groupOwner = -1;
15434                    protectedFile = null;
15435                }
15436
15437                if (uid < Process.FIRST_APPLICATION_UID
15438                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15439                    Slog.e(TAG, "Failed to finalize " + cid);
15440                    PackageHelper.destroySdDir(cid);
15441                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15442                }
15443
15444                boolean mounted = PackageHelper.isContainerMounted(cid);
15445                if (!mounted) {
15446                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15447                }
15448            }
15449            return status;
15450        }
15451
15452        private void cleanUp() {
15453            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15454
15455            // Destroy secure container
15456            PackageHelper.destroySdDir(cid);
15457        }
15458
15459        private List<String> getAllCodePaths() {
15460            final File codeFile = new File(getCodePath());
15461            if (codeFile != null && codeFile.exists()) {
15462                try {
15463                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15464                    return pkg.getAllCodePaths();
15465                } catch (PackageParserException e) {
15466                    // Ignored; we tried our best
15467                }
15468            }
15469            return Collections.EMPTY_LIST;
15470        }
15471
15472        void cleanUpResourcesLI() {
15473            // Enumerate all code paths before deleting
15474            cleanUpResourcesLI(getAllCodePaths());
15475        }
15476
15477        private void cleanUpResourcesLI(List<String> allCodePaths) {
15478            cleanUp();
15479            removeDexFiles(allCodePaths, instructionSets);
15480        }
15481
15482        String getPackageName() {
15483            return getAsecPackageName(cid);
15484        }
15485
15486        boolean doPostDeleteLI(boolean delete) {
15487            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15488            final List<String> allCodePaths = getAllCodePaths();
15489            boolean mounted = PackageHelper.isContainerMounted(cid);
15490            if (mounted) {
15491                // Unmount first
15492                if (PackageHelper.unMountSdDir(cid)) {
15493                    mounted = false;
15494                }
15495            }
15496            if (!mounted && delete) {
15497                cleanUpResourcesLI(allCodePaths);
15498            }
15499            return !mounted;
15500        }
15501
15502        @Override
15503        int doPreCopy() {
15504            if (isFwdLocked()) {
15505                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15506                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15507                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15508                }
15509            }
15510
15511            return PackageManager.INSTALL_SUCCEEDED;
15512        }
15513
15514        @Override
15515        int doPostCopy(int uid) {
15516            if (isFwdLocked()) {
15517                if (uid < Process.FIRST_APPLICATION_UID
15518                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15519                                RES_FILE_NAME)) {
15520                    Slog.e(TAG, "Failed to finalize " + cid);
15521                    PackageHelper.destroySdDir(cid);
15522                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15523                }
15524            }
15525
15526            return PackageManager.INSTALL_SUCCEEDED;
15527        }
15528    }
15529
15530    /**
15531     * Logic to handle movement of existing installed applications.
15532     */
15533    class MoveInstallArgs extends InstallArgs {
15534        private File codeFile;
15535        private File resourceFile;
15536
15537        /** New install */
15538        MoveInstallArgs(InstallParams params) {
15539            super(params.origin, params.move, params.observer, params.installFlags,
15540                    params.installerPackageName, params.volumeUuid,
15541                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15542                    params.grantedRuntimePermissions,
15543                    params.traceMethod, params.traceCookie, params.certificates,
15544                    params.installReason);
15545        }
15546
15547        int copyApk(IMediaContainerService imcs, boolean temp) {
15548            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15549                    + move.fromUuid + " to " + move.toUuid);
15550            synchronized (mInstaller) {
15551                try {
15552                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15553                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15554                } catch (InstallerException e) {
15555                    Slog.w(TAG, "Failed to move app", e);
15556                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15557                }
15558            }
15559
15560            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15561            resourceFile = codeFile;
15562            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15563
15564            return PackageManager.INSTALL_SUCCEEDED;
15565        }
15566
15567        int doPreInstall(int status) {
15568            if (status != PackageManager.INSTALL_SUCCEEDED) {
15569                cleanUp(move.toUuid);
15570            }
15571            return status;
15572        }
15573
15574        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15575            if (status != PackageManager.INSTALL_SUCCEEDED) {
15576                cleanUp(move.toUuid);
15577                return false;
15578            }
15579
15580            // Reflect the move in app info
15581            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15582            pkg.setApplicationInfoCodePath(pkg.codePath);
15583            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15584            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15585            pkg.setApplicationInfoResourcePath(pkg.codePath);
15586            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15587            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15588
15589            return true;
15590        }
15591
15592        int doPostInstall(int status, int uid) {
15593            if (status == PackageManager.INSTALL_SUCCEEDED) {
15594                cleanUp(move.fromUuid);
15595            } else {
15596                cleanUp(move.toUuid);
15597            }
15598            return status;
15599        }
15600
15601        @Override
15602        String getCodePath() {
15603            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15604        }
15605
15606        @Override
15607        String getResourcePath() {
15608            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15609        }
15610
15611        private boolean cleanUp(String volumeUuid) {
15612            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15613                    move.dataAppName);
15614            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15615            final int[] userIds = sUserManager.getUserIds();
15616            synchronized (mInstallLock) {
15617                // Clean up both app data and code
15618                // All package moves are frozen until finished
15619                for (int userId : userIds) {
15620                    try {
15621                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15622                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15623                    } catch (InstallerException e) {
15624                        Slog.w(TAG, String.valueOf(e));
15625                    }
15626                }
15627                removeCodePathLI(codeFile);
15628            }
15629            return true;
15630        }
15631
15632        void cleanUpResourcesLI() {
15633            throw new UnsupportedOperationException();
15634        }
15635
15636        boolean doPostDeleteLI(boolean delete) {
15637            throw new UnsupportedOperationException();
15638        }
15639    }
15640
15641    static String getAsecPackageName(String packageCid) {
15642        int idx = packageCid.lastIndexOf("-");
15643        if (idx == -1) {
15644            return packageCid;
15645        }
15646        return packageCid.substring(0, idx);
15647    }
15648
15649    // Utility method used to create code paths based on package name and available index.
15650    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15651        String idxStr = "";
15652        int idx = 1;
15653        // Fall back to default value of idx=1 if prefix is not
15654        // part of oldCodePath
15655        if (oldCodePath != null) {
15656            String subStr = oldCodePath;
15657            // Drop the suffix right away
15658            if (suffix != null && subStr.endsWith(suffix)) {
15659                subStr = subStr.substring(0, subStr.length() - suffix.length());
15660            }
15661            // If oldCodePath already contains prefix find out the
15662            // ending index to either increment or decrement.
15663            int sidx = subStr.lastIndexOf(prefix);
15664            if (sidx != -1) {
15665                subStr = subStr.substring(sidx + prefix.length());
15666                if (subStr != null) {
15667                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15668                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15669                    }
15670                    try {
15671                        idx = Integer.parseInt(subStr);
15672                        if (idx <= 1) {
15673                            idx++;
15674                        } else {
15675                            idx--;
15676                        }
15677                    } catch(NumberFormatException e) {
15678                    }
15679                }
15680            }
15681        }
15682        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15683        return prefix + idxStr;
15684    }
15685
15686    private File getNextCodePath(File targetDir, String packageName) {
15687        File result;
15688        SecureRandom random = new SecureRandom();
15689        byte[] bytes = new byte[16];
15690        do {
15691            random.nextBytes(bytes);
15692            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15693            result = new File(targetDir, packageName + "-" + suffix);
15694        } while (result.exists());
15695        return result;
15696    }
15697
15698    // Utility method that returns the relative package path with respect
15699    // to the installation directory. Like say for /data/data/com.test-1.apk
15700    // string com.test-1 is returned.
15701    static String deriveCodePathName(String codePath) {
15702        if (codePath == null) {
15703            return null;
15704        }
15705        final File codeFile = new File(codePath);
15706        final String name = codeFile.getName();
15707        if (codeFile.isDirectory()) {
15708            return name;
15709        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15710            final int lastDot = name.lastIndexOf('.');
15711            return name.substring(0, lastDot);
15712        } else {
15713            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15714            return null;
15715        }
15716    }
15717
15718    static class PackageInstalledInfo {
15719        String name;
15720        int uid;
15721        // The set of users that originally had this package installed.
15722        int[] origUsers;
15723        // The set of users that now have this package installed.
15724        int[] newUsers;
15725        PackageParser.Package pkg;
15726        int returnCode;
15727        String returnMsg;
15728        PackageRemovedInfo removedInfo;
15729        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15730
15731        public void setError(int code, String msg) {
15732            setReturnCode(code);
15733            setReturnMessage(msg);
15734            Slog.w(TAG, msg);
15735        }
15736
15737        public void setError(String msg, PackageParserException e) {
15738            setReturnCode(e.error);
15739            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15740            Slog.w(TAG, msg, e);
15741        }
15742
15743        public void setError(String msg, PackageManagerException e) {
15744            returnCode = e.error;
15745            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15746            Slog.w(TAG, msg, e);
15747        }
15748
15749        public void setReturnCode(int returnCode) {
15750            this.returnCode = returnCode;
15751            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15752            for (int i = 0; i < childCount; i++) {
15753                addedChildPackages.valueAt(i).returnCode = returnCode;
15754            }
15755        }
15756
15757        private void setReturnMessage(String returnMsg) {
15758            this.returnMsg = returnMsg;
15759            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15760            for (int i = 0; i < childCount; i++) {
15761                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15762            }
15763        }
15764
15765        // In some error cases we want to convey more info back to the observer
15766        String origPackage;
15767        String origPermission;
15768    }
15769
15770    /*
15771     * Install a non-existing package.
15772     */
15773    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15774            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15775            PackageInstalledInfo res, int installReason) {
15776        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15777
15778        // Remember this for later, in case we need to rollback this install
15779        String pkgName = pkg.packageName;
15780
15781        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15782
15783        synchronized(mPackages) {
15784            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15785            if (renamedPackage != null) {
15786                // A package with the same name is already installed, though
15787                // it has been renamed to an older name.  The package we
15788                // are trying to install should be installed as an update to
15789                // the existing one, but that has not been requested, so bail.
15790                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15791                        + " without first uninstalling package running as "
15792                        + renamedPackage);
15793                return;
15794            }
15795            if (mPackages.containsKey(pkgName)) {
15796                // Don't allow installation over an existing package with the same name.
15797                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15798                        + " without first uninstalling.");
15799                return;
15800            }
15801        }
15802
15803        try {
15804            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15805                    System.currentTimeMillis(), user);
15806
15807            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15808
15809            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15810                prepareAppDataAfterInstallLIF(newPackage);
15811
15812            } else {
15813                // Remove package from internal structures, but keep around any
15814                // data that might have already existed
15815                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15816                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15817            }
15818        } catch (PackageManagerException e) {
15819            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15820        }
15821
15822        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15823    }
15824
15825    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15826        // Can't rotate keys during boot or if sharedUser.
15827        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15828                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15829            return false;
15830        }
15831        // app is using upgradeKeySets; make sure all are valid
15832        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15833        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15834        for (int i = 0; i < upgradeKeySets.length; i++) {
15835            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15836                Slog.wtf(TAG, "Package "
15837                         + (oldPs.name != null ? oldPs.name : "<null>")
15838                         + " contains upgrade-key-set reference to unknown key-set: "
15839                         + upgradeKeySets[i]
15840                         + " reverting to signatures check.");
15841                return false;
15842            }
15843        }
15844        return true;
15845    }
15846
15847    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15848        // Upgrade keysets are being used.  Determine if new package has a superset of the
15849        // required keys.
15850        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15851        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15852        for (int i = 0; i < upgradeKeySets.length; i++) {
15853            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15854            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15855                return true;
15856            }
15857        }
15858        return false;
15859    }
15860
15861    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15862        try (DigestInputStream digestStream =
15863                new DigestInputStream(new FileInputStream(file), digest)) {
15864            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15865        }
15866    }
15867
15868    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15869            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15870            int installReason) {
15871        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15872
15873        final PackageParser.Package oldPackage;
15874        final String pkgName = pkg.packageName;
15875        final int[] allUsers;
15876        final int[] installedUsers;
15877
15878        synchronized(mPackages) {
15879            oldPackage = mPackages.get(pkgName);
15880            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15881
15882            // don't allow upgrade to target a release SDK from a pre-release SDK
15883            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15884                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15885            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15886                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15887            if (oldTargetsPreRelease
15888                    && !newTargetsPreRelease
15889                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15890                Slog.w(TAG, "Can't install package targeting released sdk");
15891                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15892                return;
15893            }
15894
15895            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15896
15897            // don't allow an upgrade from full to ephemeral
15898            if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) {
15899                // can't downgrade from full to instant
15900                Slog.w(TAG, "Can't replace app with instant app: " + pkgName);
15901                res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15902                return;
15903            }
15904
15905            // verify signatures are valid
15906            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15907                if (!checkUpgradeKeySetLP(ps, pkg)) {
15908                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15909                            "New package not signed by keys specified by upgrade-keysets: "
15910                                    + pkgName);
15911                    return;
15912                }
15913            } else {
15914                // default to original signature matching
15915                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15916                        != PackageManager.SIGNATURE_MATCH) {
15917                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15918                            "New package has a different signature: " + pkgName);
15919                    return;
15920                }
15921            }
15922
15923            // don't allow a system upgrade unless the upgrade hash matches
15924            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15925                byte[] digestBytes = null;
15926                try {
15927                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15928                    updateDigest(digest, new File(pkg.baseCodePath));
15929                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15930                        for (String path : pkg.splitCodePaths) {
15931                            updateDigest(digest, new File(path));
15932                        }
15933                    }
15934                    digestBytes = digest.digest();
15935                } catch (NoSuchAlgorithmException | IOException e) {
15936                    res.setError(INSTALL_FAILED_INVALID_APK,
15937                            "Could not compute hash: " + pkgName);
15938                    return;
15939                }
15940                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15941                    res.setError(INSTALL_FAILED_INVALID_APK,
15942                            "New package fails restrict-update check: " + pkgName);
15943                    return;
15944                }
15945                // retain upgrade restriction
15946                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15947            }
15948
15949            // Check for shared user id changes
15950            String invalidPackageName =
15951                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15952            if (invalidPackageName != null) {
15953                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15954                        "Package " + invalidPackageName + " tried to change user "
15955                                + oldPackage.mSharedUserId);
15956                return;
15957            }
15958
15959            // In case of rollback, remember per-user/profile install state
15960            allUsers = sUserManager.getUserIds();
15961            installedUsers = ps.queryInstalledUsers(allUsers, true);
15962        }
15963
15964        // Update what is removed
15965        res.removedInfo = new PackageRemovedInfo();
15966        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15967        res.removedInfo.removedPackage = oldPackage.packageName;
15968        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15969        res.removedInfo.isUpdate = true;
15970        res.removedInfo.origUsers = installedUsers;
15971        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15972        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15973        for (int i = 0; i < installedUsers.length; i++) {
15974            final int userId = installedUsers[i];
15975            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15976        }
15977
15978        final int childCount = (oldPackage.childPackages != null)
15979                ? oldPackage.childPackages.size() : 0;
15980        for (int i = 0; i < childCount; i++) {
15981            boolean childPackageUpdated = false;
15982            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15983            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15984            if (res.addedChildPackages != null) {
15985                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15986                if (childRes != null) {
15987                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15988                    childRes.removedInfo.removedPackage = childPkg.packageName;
15989                    childRes.removedInfo.isUpdate = true;
15990                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15991                    childPackageUpdated = true;
15992                }
15993            }
15994            if (!childPackageUpdated) {
15995                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15996                childRemovedRes.removedPackage = childPkg.packageName;
15997                childRemovedRes.isUpdate = false;
15998                childRemovedRes.dataRemoved = true;
15999                synchronized (mPackages) {
16000                    if (childPs != null) {
16001                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16002                    }
16003                }
16004                if (res.removedInfo.removedChildPackages == null) {
16005                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16006                }
16007                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16008            }
16009        }
16010
16011        boolean sysPkg = (isSystemApp(oldPackage));
16012        if (sysPkg) {
16013            // Set the system/privileged flags as needed
16014            final boolean privileged =
16015                    (oldPackage.applicationInfo.privateFlags
16016                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16017            final int systemPolicyFlags = policyFlags
16018                    | PackageParser.PARSE_IS_SYSTEM
16019                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16020
16021            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16022                    user, allUsers, installerPackageName, res, installReason);
16023        } else {
16024            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16025                    user, allUsers, installerPackageName, res, installReason);
16026        }
16027    }
16028
16029    public List<String> getPreviousCodePaths(String packageName) {
16030        final PackageSetting ps = mSettings.mPackages.get(packageName);
16031        final List<String> result = new ArrayList<String>();
16032        if (ps != null && ps.oldCodePaths != null) {
16033            result.addAll(ps.oldCodePaths);
16034        }
16035        return result;
16036    }
16037
16038    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16039            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16040            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16041            int installReason) {
16042        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16043                + deletedPackage);
16044
16045        String pkgName = deletedPackage.packageName;
16046        boolean deletedPkg = true;
16047        boolean addedPkg = false;
16048        boolean updatedSettings = false;
16049        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16050        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16051                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16052
16053        final long origUpdateTime = (pkg.mExtras != null)
16054                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16055
16056        // First delete the existing package while retaining the data directory
16057        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16058                res.removedInfo, true, pkg)) {
16059            // If the existing package wasn't successfully deleted
16060            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16061            deletedPkg = false;
16062        } else {
16063            // Successfully deleted the old package; proceed with replace.
16064
16065            // If deleted package lived in a container, give users a chance to
16066            // relinquish resources before killing.
16067            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16068                if (DEBUG_INSTALL) {
16069                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16070                }
16071                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16072                final ArrayList<String> pkgList = new ArrayList<String>(1);
16073                pkgList.add(deletedPackage.applicationInfo.packageName);
16074                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16075            }
16076
16077            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16078                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16079            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16080
16081            try {
16082                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16083                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16084                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16085                        installReason);
16086
16087                // Update the in-memory copy of the previous code paths.
16088                PackageSetting ps = mSettings.mPackages.get(pkgName);
16089                if (!killApp) {
16090                    if (ps.oldCodePaths == null) {
16091                        ps.oldCodePaths = new ArraySet<>();
16092                    }
16093                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16094                    if (deletedPackage.splitCodePaths != null) {
16095                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16096                    }
16097                } else {
16098                    ps.oldCodePaths = null;
16099                }
16100                if (ps.childPackageNames != null) {
16101                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16102                        final String childPkgName = ps.childPackageNames.get(i);
16103                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16104                        childPs.oldCodePaths = ps.oldCodePaths;
16105                    }
16106                }
16107                // set instant app status, but, only if it's explicitly specified
16108                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16109                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16110                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16111                prepareAppDataAfterInstallLIF(newPackage);
16112                addedPkg = true;
16113                mDexManager.notifyPackageUpdated(newPackage.packageName,
16114                        newPackage.baseCodePath, newPackage.splitCodePaths);
16115            } catch (PackageManagerException e) {
16116                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16117            }
16118        }
16119
16120        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16121            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16122
16123            // Revert all internal state mutations and added folders for the failed install
16124            if (addedPkg) {
16125                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16126                        res.removedInfo, true, null);
16127            }
16128
16129            // Restore the old package
16130            if (deletedPkg) {
16131                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16132                File restoreFile = new File(deletedPackage.codePath);
16133                // Parse old package
16134                boolean oldExternal = isExternal(deletedPackage);
16135                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16136                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16137                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16138                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16139                try {
16140                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16141                            null);
16142                } catch (PackageManagerException e) {
16143                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16144                            + e.getMessage());
16145                    return;
16146                }
16147
16148                synchronized (mPackages) {
16149                    // Ensure the installer package name up to date
16150                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16151
16152                    // Update permissions for restored package
16153                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16154
16155                    mSettings.writeLPr();
16156                }
16157
16158                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16159            }
16160        } else {
16161            synchronized (mPackages) {
16162                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16163                if (ps != null) {
16164                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16165                    if (res.removedInfo.removedChildPackages != null) {
16166                        final int childCount = res.removedInfo.removedChildPackages.size();
16167                        // Iterate in reverse as we may modify the collection
16168                        for (int i = childCount - 1; i >= 0; i--) {
16169                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16170                            if (res.addedChildPackages.containsKey(childPackageName)) {
16171                                res.removedInfo.removedChildPackages.removeAt(i);
16172                            } else {
16173                                PackageRemovedInfo childInfo = res.removedInfo
16174                                        .removedChildPackages.valueAt(i);
16175                                childInfo.removedForAllUsers = mPackages.get(
16176                                        childInfo.removedPackage) == null;
16177                            }
16178                        }
16179                    }
16180                }
16181            }
16182        }
16183    }
16184
16185    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16186            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16187            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16188            int installReason) {
16189        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16190                + ", old=" + deletedPackage);
16191
16192        final boolean disabledSystem;
16193
16194        // Remove existing system package
16195        removePackageLI(deletedPackage, true);
16196
16197        synchronized (mPackages) {
16198            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16199        }
16200        if (!disabledSystem) {
16201            // We didn't need to disable the .apk as a current system package,
16202            // which means we are replacing another update that is already
16203            // installed.  We need to make sure to delete the older one's .apk.
16204            res.removedInfo.args = createInstallArgsForExisting(0,
16205                    deletedPackage.applicationInfo.getCodePath(),
16206                    deletedPackage.applicationInfo.getResourcePath(),
16207                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16208        } else {
16209            res.removedInfo.args = null;
16210        }
16211
16212        // Successfully disabled the old package. Now proceed with re-installation
16213        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16214                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16215        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16216
16217        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16218        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16219                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16220
16221        PackageParser.Package newPackage = null;
16222        try {
16223            // Add the package to the internal data structures
16224            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16225
16226            // Set the update and install times
16227            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16228            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16229                    System.currentTimeMillis());
16230
16231            // Update the package dynamic state if succeeded
16232            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16233                // Now that the install succeeded make sure we remove data
16234                // directories for any child package the update removed.
16235                final int deletedChildCount = (deletedPackage.childPackages != null)
16236                        ? deletedPackage.childPackages.size() : 0;
16237                final int newChildCount = (newPackage.childPackages != null)
16238                        ? newPackage.childPackages.size() : 0;
16239                for (int i = 0; i < deletedChildCount; i++) {
16240                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16241                    boolean childPackageDeleted = true;
16242                    for (int j = 0; j < newChildCount; j++) {
16243                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16244                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16245                            childPackageDeleted = false;
16246                            break;
16247                        }
16248                    }
16249                    if (childPackageDeleted) {
16250                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16251                                deletedChildPkg.packageName);
16252                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16253                            PackageRemovedInfo removedChildRes = res.removedInfo
16254                                    .removedChildPackages.get(deletedChildPkg.packageName);
16255                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16256                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16257                        }
16258                    }
16259                }
16260
16261                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16262                        installReason);
16263                prepareAppDataAfterInstallLIF(newPackage);
16264
16265                mDexManager.notifyPackageUpdated(newPackage.packageName,
16266                            newPackage.baseCodePath, newPackage.splitCodePaths);
16267            }
16268        } catch (PackageManagerException e) {
16269            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16270            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16271        }
16272
16273        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16274            // Re installation failed. Restore old information
16275            // Remove new pkg information
16276            if (newPackage != null) {
16277                removeInstalledPackageLI(newPackage, true);
16278            }
16279            // Add back the old system package
16280            try {
16281                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16282            } catch (PackageManagerException e) {
16283                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16284            }
16285
16286            synchronized (mPackages) {
16287                if (disabledSystem) {
16288                    enableSystemPackageLPw(deletedPackage);
16289                }
16290
16291                // Ensure the installer package name up to date
16292                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16293
16294                // Update permissions for restored package
16295                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16296
16297                mSettings.writeLPr();
16298            }
16299
16300            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16301                    + " after failed upgrade");
16302        }
16303    }
16304
16305    /**
16306     * Checks whether the parent or any of the child packages have a change shared
16307     * user. For a package to be a valid update the shred users of the parent and
16308     * the children should match. We may later support changing child shared users.
16309     * @param oldPkg The updated package.
16310     * @param newPkg The update package.
16311     * @return The shared user that change between the versions.
16312     */
16313    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16314            PackageParser.Package newPkg) {
16315        // Check parent shared user
16316        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16317            return newPkg.packageName;
16318        }
16319        // Check child shared users
16320        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16321        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16322        for (int i = 0; i < newChildCount; i++) {
16323            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16324            // If this child was present, did it have the same shared user?
16325            for (int j = 0; j < oldChildCount; j++) {
16326                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16327                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16328                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16329                    return newChildPkg.packageName;
16330                }
16331            }
16332        }
16333        return null;
16334    }
16335
16336    private void removeNativeBinariesLI(PackageSetting ps) {
16337        // Remove the lib path for the parent package
16338        if (ps != null) {
16339            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16340            // Remove the lib path for the child packages
16341            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16342            for (int i = 0; i < childCount; i++) {
16343                PackageSetting childPs = null;
16344                synchronized (mPackages) {
16345                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16346                }
16347                if (childPs != null) {
16348                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16349                            .legacyNativeLibraryPathString);
16350                }
16351            }
16352        }
16353    }
16354
16355    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16356        // Enable the parent package
16357        mSettings.enableSystemPackageLPw(pkg.packageName);
16358        // Enable the child packages
16359        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16360        for (int i = 0; i < childCount; i++) {
16361            PackageParser.Package childPkg = pkg.childPackages.get(i);
16362            mSettings.enableSystemPackageLPw(childPkg.packageName);
16363        }
16364    }
16365
16366    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16367            PackageParser.Package newPkg) {
16368        // Disable the parent package (parent always replaced)
16369        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16370        // Disable the child packages
16371        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16372        for (int i = 0; i < childCount; i++) {
16373            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16374            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16375            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16376        }
16377        return disabled;
16378    }
16379
16380    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16381            String installerPackageName) {
16382        // Enable the parent package
16383        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16384        // Enable the child packages
16385        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16386        for (int i = 0; i < childCount; i++) {
16387            PackageParser.Package childPkg = pkg.childPackages.get(i);
16388            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16389        }
16390    }
16391
16392    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16393        // Collect all used permissions in the UID
16394        ArraySet<String> usedPermissions = new ArraySet<>();
16395        final int packageCount = su.packages.size();
16396        for (int i = 0; i < packageCount; i++) {
16397            PackageSetting ps = su.packages.valueAt(i);
16398            if (ps.pkg == null) {
16399                continue;
16400            }
16401            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16402            for (int j = 0; j < requestedPermCount; j++) {
16403                String permission = ps.pkg.requestedPermissions.get(j);
16404                BasePermission bp = mSettings.mPermissions.get(permission);
16405                if (bp != null) {
16406                    usedPermissions.add(permission);
16407                }
16408            }
16409        }
16410
16411        PermissionsState permissionsState = su.getPermissionsState();
16412        // Prune install permissions
16413        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16414        final int installPermCount = installPermStates.size();
16415        for (int i = installPermCount - 1; i >= 0;  i--) {
16416            PermissionState permissionState = installPermStates.get(i);
16417            if (!usedPermissions.contains(permissionState.getName())) {
16418                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16419                if (bp != null) {
16420                    permissionsState.revokeInstallPermission(bp);
16421                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16422                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16423                }
16424            }
16425        }
16426
16427        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16428
16429        // Prune runtime permissions
16430        for (int userId : allUserIds) {
16431            List<PermissionState> runtimePermStates = permissionsState
16432                    .getRuntimePermissionStates(userId);
16433            final int runtimePermCount = runtimePermStates.size();
16434            for (int i = runtimePermCount - 1; i >= 0; i--) {
16435                PermissionState permissionState = runtimePermStates.get(i);
16436                if (!usedPermissions.contains(permissionState.getName())) {
16437                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16438                    if (bp != null) {
16439                        permissionsState.revokeRuntimePermission(bp, userId);
16440                        permissionsState.updatePermissionFlags(bp, userId,
16441                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16442                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16443                                runtimePermissionChangedUserIds, userId);
16444                    }
16445                }
16446            }
16447        }
16448
16449        return runtimePermissionChangedUserIds;
16450    }
16451
16452    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16453            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16454        // Update the parent package setting
16455        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16456                res, user, installReason);
16457        // Update the child packages setting
16458        final int childCount = (newPackage.childPackages != null)
16459                ? newPackage.childPackages.size() : 0;
16460        for (int i = 0; i < childCount; i++) {
16461            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16462            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16463            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16464                    childRes.origUsers, childRes, user, installReason);
16465        }
16466    }
16467
16468    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16469            String installerPackageName, int[] allUsers, int[] installedForUsers,
16470            PackageInstalledInfo res, UserHandle user, int installReason) {
16471        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16472
16473        String pkgName = newPackage.packageName;
16474        synchronized (mPackages) {
16475            //write settings. the installStatus will be incomplete at this stage.
16476            //note that the new package setting would have already been
16477            //added to mPackages. It hasn't been persisted yet.
16478            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16479            // TODO: Remove this write? It's also written at the end of this method
16480            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16481            mSettings.writeLPr();
16482            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16483        }
16484
16485        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16486        synchronized (mPackages) {
16487            updatePermissionsLPw(newPackage.packageName, newPackage,
16488                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16489                            ? UPDATE_PERMISSIONS_ALL : 0));
16490            // For system-bundled packages, we assume that installing an upgraded version
16491            // of the package implies that the user actually wants to run that new code,
16492            // so we enable the package.
16493            PackageSetting ps = mSettings.mPackages.get(pkgName);
16494            final int userId = user.getIdentifier();
16495            if (ps != null) {
16496                if (isSystemApp(newPackage)) {
16497                    if (DEBUG_INSTALL) {
16498                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16499                    }
16500                    // Enable system package for requested users
16501                    if (res.origUsers != null) {
16502                        for (int origUserId : res.origUsers) {
16503                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16504                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16505                                        origUserId, installerPackageName);
16506                            }
16507                        }
16508                    }
16509                    // Also convey the prior install/uninstall state
16510                    if (allUsers != null && installedForUsers != null) {
16511                        for (int currentUserId : allUsers) {
16512                            final boolean installed = ArrayUtils.contains(
16513                                    installedForUsers, currentUserId);
16514                            if (DEBUG_INSTALL) {
16515                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16516                            }
16517                            ps.setInstalled(installed, currentUserId);
16518                        }
16519                        // these install state changes will be persisted in the
16520                        // upcoming call to mSettings.writeLPr().
16521                    }
16522                }
16523                // It's implied that when a user requests installation, they want the app to be
16524                // installed and enabled.
16525                if (userId != UserHandle.USER_ALL) {
16526                    ps.setInstalled(true, userId);
16527                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16528                }
16529
16530                // When replacing an existing package, preserve the original install reason for all
16531                // users that had the package installed before.
16532                final Set<Integer> previousUserIds = new ArraySet<>();
16533                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16534                    final int installReasonCount = res.removedInfo.installReasons.size();
16535                    for (int i = 0; i < installReasonCount; i++) {
16536                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16537                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16538                        ps.setInstallReason(previousInstallReason, previousUserId);
16539                        previousUserIds.add(previousUserId);
16540                    }
16541                }
16542
16543                // Set install reason for users that are having the package newly installed.
16544                if (userId == UserHandle.USER_ALL) {
16545                    for (int currentUserId : sUserManager.getUserIds()) {
16546                        if (!previousUserIds.contains(currentUserId)) {
16547                            ps.setInstallReason(installReason, currentUserId);
16548                        }
16549                    }
16550                } else if (!previousUserIds.contains(userId)) {
16551                    ps.setInstallReason(installReason, userId);
16552                }
16553                mSettings.writeKernelMappingLPr(ps);
16554            }
16555            res.name = pkgName;
16556            res.uid = newPackage.applicationInfo.uid;
16557            res.pkg = newPackage;
16558            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16559            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16560            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16561            //to update install status
16562            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16563            mSettings.writeLPr();
16564            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16565        }
16566
16567        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16568    }
16569
16570    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16571        try {
16572            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16573            installPackageLI(args, res);
16574        } finally {
16575            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16576        }
16577    }
16578
16579    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16580        final int installFlags = args.installFlags;
16581        final String installerPackageName = args.installerPackageName;
16582        final String volumeUuid = args.volumeUuid;
16583        final File tmpPackageFile = new File(args.getCodePath());
16584        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16585        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16586                || (args.volumeUuid != null));
16587        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16588        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16589        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16590        boolean replace = false;
16591        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16592        if (args.move != null) {
16593            // moving a complete application; perform an initial scan on the new install location
16594            scanFlags |= SCAN_INITIAL;
16595        }
16596        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16597            scanFlags |= SCAN_DONT_KILL_APP;
16598        }
16599        if (instantApp) {
16600            scanFlags |= SCAN_AS_INSTANT_APP;
16601        }
16602        if (fullApp) {
16603            scanFlags |= SCAN_AS_FULL_APP;
16604        }
16605
16606        // Result object to be returned
16607        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16608
16609        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16610
16611        // Sanity check
16612        if (instantApp && (forwardLocked || onExternal)) {
16613            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16614                    + " external=" + onExternal);
16615            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16616            return;
16617        }
16618
16619        // Retrieve PackageSettings and parse package
16620        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16621                | PackageParser.PARSE_ENFORCE_CODE
16622                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16623                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16624                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16625                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16626        PackageParser pp = new PackageParser();
16627        pp.setSeparateProcesses(mSeparateProcesses);
16628        pp.setDisplayMetrics(mMetrics);
16629
16630        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16631        final PackageParser.Package pkg;
16632        try {
16633            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16634        } catch (PackageParserException e) {
16635            res.setError("Failed parse during installPackageLI", e);
16636            return;
16637        } finally {
16638            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16639        }
16640
16641//        // Ephemeral apps must have target SDK >= O.
16642//        // TODO: Update conditional and error message when O gets locked down
16643//        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16644//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16645//                    "Ephemeral apps must have target SDK version of at least O");
16646//            return;
16647//        }
16648
16649        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16650            // Static shared libraries have synthetic package names
16651            renameStaticSharedLibraryPackage(pkg);
16652
16653            // No static shared libs on external storage
16654            if (onExternal) {
16655                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16656                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16657                        "Packages declaring static-shared libs cannot be updated");
16658                return;
16659            }
16660        }
16661
16662        // If we are installing a clustered package add results for the children
16663        if (pkg.childPackages != null) {
16664            synchronized (mPackages) {
16665                final int childCount = pkg.childPackages.size();
16666                for (int i = 0; i < childCount; i++) {
16667                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16668                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16669                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16670                    childRes.pkg = childPkg;
16671                    childRes.name = childPkg.packageName;
16672                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16673                    if (childPs != null) {
16674                        childRes.origUsers = childPs.queryInstalledUsers(
16675                                sUserManager.getUserIds(), true);
16676                    }
16677                    if ((mPackages.containsKey(childPkg.packageName))) {
16678                        childRes.removedInfo = new PackageRemovedInfo();
16679                        childRes.removedInfo.removedPackage = childPkg.packageName;
16680                    }
16681                    if (res.addedChildPackages == null) {
16682                        res.addedChildPackages = new ArrayMap<>();
16683                    }
16684                    res.addedChildPackages.put(childPkg.packageName, childRes);
16685                }
16686            }
16687        }
16688
16689        // If package doesn't declare API override, mark that we have an install
16690        // time CPU ABI override.
16691        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16692            pkg.cpuAbiOverride = args.abiOverride;
16693        }
16694
16695        String pkgName = res.name = pkg.packageName;
16696        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16697            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16698                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16699                return;
16700            }
16701        }
16702
16703        try {
16704            // either use what we've been given or parse directly from the APK
16705            if (args.certificates != null) {
16706                try {
16707                    PackageParser.populateCertificates(pkg, args.certificates);
16708                } catch (PackageParserException e) {
16709                    // there was something wrong with the certificates we were given;
16710                    // try to pull them from the APK
16711                    PackageParser.collectCertificates(pkg, parseFlags);
16712                }
16713            } else {
16714                PackageParser.collectCertificates(pkg, parseFlags);
16715            }
16716        } catch (PackageParserException e) {
16717            res.setError("Failed collect during installPackageLI", e);
16718            return;
16719        }
16720
16721        // Get rid of all references to package scan path via parser.
16722        pp = null;
16723        String oldCodePath = null;
16724        boolean systemApp = false;
16725        synchronized (mPackages) {
16726            // Check if installing already existing package
16727            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16728                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16729                if (pkg.mOriginalPackages != null
16730                        && pkg.mOriginalPackages.contains(oldName)
16731                        && mPackages.containsKey(oldName)) {
16732                    // This package is derived from an original package,
16733                    // and this device has been updating from that original
16734                    // name.  We must continue using the original name, so
16735                    // rename the new package here.
16736                    pkg.setPackageName(oldName);
16737                    pkgName = pkg.packageName;
16738                    replace = true;
16739                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16740                            + oldName + " pkgName=" + pkgName);
16741                } else if (mPackages.containsKey(pkgName)) {
16742                    // This package, under its official name, already exists
16743                    // on the device; we should replace it.
16744                    replace = true;
16745                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16746                }
16747
16748                // Child packages are installed through the parent package
16749                if (pkg.parentPackage != null) {
16750                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16751                            "Package " + pkg.packageName + " is child of package "
16752                                    + pkg.parentPackage.parentPackage + ". Child packages "
16753                                    + "can be updated only through the parent package.");
16754                    return;
16755                }
16756
16757                if (replace) {
16758                    // Prevent apps opting out from runtime permissions
16759                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16760                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16761                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16762                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16763                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16764                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16765                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16766                                        + " doesn't support runtime permissions but the old"
16767                                        + " target SDK " + oldTargetSdk + " does.");
16768                        return;
16769                    }
16770
16771                    // Prevent installing of child packages
16772                    if (oldPackage.parentPackage != null) {
16773                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16774                                "Package " + pkg.packageName + " is child of package "
16775                                        + oldPackage.parentPackage + ". Child packages "
16776                                        + "can be updated only through the parent package.");
16777                        return;
16778                    }
16779                }
16780            }
16781
16782            PackageSetting ps = mSettings.mPackages.get(pkgName);
16783            if (ps != null) {
16784                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16785
16786                // Static shared libs have same package with different versions where
16787                // we internally use a synthetic package name to allow multiple versions
16788                // of the same package, therefore we need to compare signatures against
16789                // the package setting for the latest library version.
16790                PackageSetting signatureCheckPs = ps;
16791                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16792                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16793                    if (libraryEntry != null) {
16794                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16795                    }
16796                }
16797
16798                // Quick sanity check that we're signed correctly if updating;
16799                // we'll check this again later when scanning, but we want to
16800                // bail early here before tripping over redefined permissions.
16801                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16802                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16803                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16804                                + pkg.packageName + " upgrade keys do not match the "
16805                                + "previously installed version");
16806                        return;
16807                    }
16808                } else {
16809                    try {
16810                        verifySignaturesLP(signatureCheckPs, pkg);
16811                    } catch (PackageManagerException e) {
16812                        res.setError(e.error, e.getMessage());
16813                        return;
16814                    }
16815                }
16816
16817                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16818                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16819                    systemApp = (ps.pkg.applicationInfo.flags &
16820                            ApplicationInfo.FLAG_SYSTEM) != 0;
16821                }
16822                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16823            }
16824
16825            // Check whether the newly-scanned package wants to define an already-defined perm
16826            int N = pkg.permissions.size();
16827            for (int i = N-1; i >= 0; i--) {
16828                PackageParser.Permission perm = pkg.permissions.get(i);
16829                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16830                if (bp != null) {
16831                    // If the defining package is signed with our cert, it's okay.  This
16832                    // also includes the "updating the same package" case, of course.
16833                    // "updating same package" could also involve key-rotation.
16834                    final boolean sigsOk;
16835                    if (bp.sourcePackage.equals(pkg.packageName)
16836                            && (bp.packageSetting instanceof PackageSetting)
16837                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16838                                    scanFlags))) {
16839                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16840                    } else {
16841                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16842                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16843                    }
16844                    if (!sigsOk) {
16845                        // If the owning package is the system itself, we log but allow
16846                        // install to proceed; we fail the install on all other permission
16847                        // redefinitions.
16848                        if (!bp.sourcePackage.equals("android")) {
16849                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16850                                    + pkg.packageName + " attempting to redeclare permission "
16851                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16852                            res.origPermission = perm.info.name;
16853                            res.origPackage = bp.sourcePackage;
16854                            return;
16855                        } else {
16856                            Slog.w(TAG, "Package " + pkg.packageName
16857                                    + " attempting to redeclare system permission "
16858                                    + perm.info.name + "; ignoring new declaration");
16859                            pkg.permissions.remove(i);
16860                        }
16861                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16862                        // Prevent apps to change protection level to dangerous from any other
16863                        // type as this would allow a privilege escalation where an app adds a
16864                        // normal/signature permission in other app's group and later redefines
16865                        // it as dangerous leading to the group auto-grant.
16866                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16867                                == PermissionInfo.PROTECTION_DANGEROUS) {
16868                            if (bp != null && !bp.isRuntime()) {
16869                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16870                                        + "non-runtime permission " + perm.info.name
16871                                        + " to runtime; keeping old protection level");
16872                                perm.info.protectionLevel = bp.protectionLevel;
16873                            }
16874                        }
16875                    }
16876                }
16877            }
16878        }
16879
16880        if (systemApp) {
16881            if (onExternal) {
16882                // Abort update; system app can't be replaced with app on sdcard
16883                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16884                        "Cannot install updates to system apps on sdcard");
16885                return;
16886            } else if (instantApp) {
16887                // Abort update; system app can't be replaced with an instant app
16888                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16889                        "Cannot update a system app with an instant app");
16890                return;
16891            }
16892        }
16893
16894        if (args.move != null) {
16895            // We did an in-place move, so dex is ready to roll
16896            scanFlags |= SCAN_NO_DEX;
16897            scanFlags |= SCAN_MOVE;
16898
16899            synchronized (mPackages) {
16900                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16901                if (ps == null) {
16902                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16903                            "Missing settings for moved package " + pkgName);
16904                }
16905
16906                // We moved the entire application as-is, so bring over the
16907                // previously derived ABI information.
16908                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16909                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16910            }
16911
16912        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16913            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16914            scanFlags |= SCAN_NO_DEX;
16915
16916            try {
16917                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16918                    args.abiOverride : pkg.cpuAbiOverride);
16919                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16920                        true /*extractLibs*/, mAppLib32InstallDir);
16921            } catch (PackageManagerException pme) {
16922                Slog.e(TAG, "Error deriving application ABI", pme);
16923                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16924                return;
16925            }
16926
16927            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16928            // Do not run PackageDexOptimizer through the local performDexOpt
16929            // method because `pkg` may not be in `mPackages` yet.
16930            //
16931            // Also, don't fail application installs if the dexopt step fails.
16932            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16933                    null /* instructionSets */, false /* checkProfiles */,
16934                    getCompilerFilterForReason(REASON_INSTALL),
16935                    getOrCreateCompilerPackageStats(pkg));
16936            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16937
16938            // Notify BackgroundDexOptJobService that the package has been changed.
16939            // If this is an update of a package which used to fail to compile,
16940            // BDOS will remove it from its blacklist.
16941            // TODO: Layering violation
16942            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16943        }
16944
16945        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16946            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16947            return;
16948        }
16949
16950        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16951
16952        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16953                "installPackageLI")) {
16954            if (replace) {
16955                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16956                    // Static libs have a synthetic package name containing the version
16957                    // and cannot be updated as an update would get a new package name,
16958                    // unless this is the exact same version code which is useful for
16959                    // development.
16960                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16961                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16962                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16963                                + "static-shared libs cannot be updated");
16964                        return;
16965                    }
16966                }
16967                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16968                        installerPackageName, res, args.installReason);
16969            } else {
16970                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16971                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16972            }
16973        }
16974        synchronized (mPackages) {
16975            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16976            if (ps != null) {
16977                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16978            }
16979
16980            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16981            for (int i = 0; i < childCount; i++) {
16982                PackageParser.Package childPkg = pkg.childPackages.get(i);
16983                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16984                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16985                if (childPs != null) {
16986                    childRes.newUsers = childPs.queryInstalledUsers(
16987                            sUserManager.getUserIds(), true);
16988                }
16989            }
16990
16991            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16992                updateSequenceNumberLP(pkgName, res.newUsers);
16993            }
16994        }
16995    }
16996
16997    private void startIntentFilterVerifications(int userId, boolean replacing,
16998            PackageParser.Package pkg) {
16999        if (mIntentFilterVerifierComponent == null) {
17000            Slog.w(TAG, "No IntentFilter verification will not be done as "
17001                    + "there is no IntentFilterVerifier available!");
17002            return;
17003        }
17004
17005        final int verifierUid = getPackageUid(
17006                mIntentFilterVerifierComponent.getPackageName(),
17007                MATCH_DEBUG_TRIAGED_MISSING,
17008                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17009
17010        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17011        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17012        mHandler.sendMessage(msg);
17013
17014        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17015        for (int i = 0; i < childCount; i++) {
17016            PackageParser.Package childPkg = pkg.childPackages.get(i);
17017            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17018            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17019            mHandler.sendMessage(msg);
17020        }
17021    }
17022
17023    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17024            PackageParser.Package pkg) {
17025        int size = pkg.activities.size();
17026        if (size == 0) {
17027            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17028                    "No activity, so no need to verify any IntentFilter!");
17029            return;
17030        }
17031
17032        final boolean hasDomainURLs = hasDomainURLs(pkg);
17033        if (!hasDomainURLs) {
17034            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17035                    "No domain URLs, so no need to verify any IntentFilter!");
17036            return;
17037        }
17038
17039        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17040                + " if any IntentFilter from the " + size
17041                + " Activities needs verification ...");
17042
17043        int count = 0;
17044        final String packageName = pkg.packageName;
17045
17046        synchronized (mPackages) {
17047            // If this is a new install and we see that we've already run verification for this
17048            // package, we have nothing to do: it means the state was restored from backup.
17049            if (!replacing) {
17050                IntentFilterVerificationInfo ivi =
17051                        mSettings.getIntentFilterVerificationLPr(packageName);
17052                if (ivi != null) {
17053                    if (DEBUG_DOMAIN_VERIFICATION) {
17054                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17055                                + ivi.getStatusString());
17056                    }
17057                    return;
17058                }
17059            }
17060
17061            // If any filters need to be verified, then all need to be.
17062            boolean needToVerify = false;
17063            for (PackageParser.Activity a : pkg.activities) {
17064                for (ActivityIntentInfo filter : a.intents) {
17065                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17066                        if (DEBUG_DOMAIN_VERIFICATION) {
17067                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17068                        }
17069                        needToVerify = true;
17070                        break;
17071                    }
17072                }
17073            }
17074
17075            if (needToVerify) {
17076                final int verificationId = mIntentFilterVerificationToken++;
17077                for (PackageParser.Activity a : pkg.activities) {
17078                    for (ActivityIntentInfo filter : a.intents) {
17079                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17080                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17081                                    "Verification needed for IntentFilter:" + filter.toString());
17082                            mIntentFilterVerifier.addOneIntentFilterVerification(
17083                                    verifierUid, userId, verificationId, filter, packageName);
17084                            count++;
17085                        }
17086                    }
17087                }
17088            }
17089        }
17090
17091        if (count > 0) {
17092            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17093                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17094                    +  " for userId:" + userId);
17095            mIntentFilterVerifier.startVerifications(userId);
17096        } else {
17097            if (DEBUG_DOMAIN_VERIFICATION) {
17098                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17099            }
17100        }
17101    }
17102
17103    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17104        final ComponentName cn  = filter.activity.getComponentName();
17105        final String packageName = cn.getPackageName();
17106
17107        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17108                packageName);
17109        if (ivi == null) {
17110            return true;
17111        }
17112        int status = ivi.getStatus();
17113        switch (status) {
17114            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17115            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17116                return true;
17117
17118            default:
17119                // Nothing to do
17120                return false;
17121        }
17122    }
17123
17124    private static boolean isMultiArch(ApplicationInfo info) {
17125        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17126    }
17127
17128    private static boolean isExternal(PackageParser.Package pkg) {
17129        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17130    }
17131
17132    private static boolean isExternal(PackageSetting ps) {
17133        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17134    }
17135
17136    private static boolean isSystemApp(PackageParser.Package pkg) {
17137        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17138    }
17139
17140    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17141        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17142    }
17143
17144    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17145        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17146    }
17147
17148    private static boolean isSystemApp(PackageSetting ps) {
17149        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17150    }
17151
17152    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17153        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17154    }
17155
17156    private int packageFlagsToInstallFlags(PackageSetting ps) {
17157        int installFlags = 0;
17158        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17159            // This existing package was an external ASEC install when we have
17160            // the external flag without a UUID
17161            installFlags |= PackageManager.INSTALL_EXTERNAL;
17162        }
17163        if (ps.isForwardLocked()) {
17164            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17165        }
17166        return installFlags;
17167    }
17168
17169    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17170        if (isExternal(pkg)) {
17171            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17172                return StorageManager.UUID_PRIMARY_PHYSICAL;
17173            } else {
17174                return pkg.volumeUuid;
17175            }
17176        } else {
17177            return StorageManager.UUID_PRIVATE_INTERNAL;
17178        }
17179    }
17180
17181    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17182        if (isExternal(pkg)) {
17183            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17184                return mSettings.getExternalVersion();
17185            } else {
17186                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17187            }
17188        } else {
17189            return mSettings.getInternalVersion();
17190        }
17191    }
17192
17193    private void deleteTempPackageFiles() {
17194        final FilenameFilter filter = new FilenameFilter() {
17195            public boolean accept(File dir, String name) {
17196                return name.startsWith("vmdl") && name.endsWith(".tmp");
17197            }
17198        };
17199        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17200            file.delete();
17201        }
17202    }
17203
17204    @Override
17205    public void deletePackageAsUser(String packageName, int versionCode,
17206            IPackageDeleteObserver observer, int userId, int flags) {
17207        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17208                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17209    }
17210
17211    @Override
17212    public void deletePackageVersioned(VersionedPackage versionedPackage,
17213            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17214        mContext.enforceCallingOrSelfPermission(
17215                android.Manifest.permission.DELETE_PACKAGES, null);
17216        Preconditions.checkNotNull(versionedPackage);
17217        Preconditions.checkNotNull(observer);
17218        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17219                PackageManager.VERSION_CODE_HIGHEST,
17220                Integer.MAX_VALUE, "versionCode must be >= -1");
17221
17222        final String packageName = versionedPackage.getPackageName();
17223        // TODO: We will change version code to long, so in the new API it is long
17224        final int versionCode = (int) versionedPackage.getVersionCode();
17225        final String internalPackageName;
17226        synchronized (mPackages) {
17227            // Normalize package name to handle renamed packages and static libs
17228            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17229                    // TODO: We will change version code to long, so in the new API it is long
17230                    (int) versionedPackage.getVersionCode());
17231        }
17232
17233        final int uid = Binder.getCallingUid();
17234        if (!isOrphaned(internalPackageName)
17235                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17236            try {
17237                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17238                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17239                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17240                observer.onUserActionRequired(intent);
17241            } catch (RemoteException re) {
17242            }
17243            return;
17244        }
17245        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17246        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17247        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17248            mContext.enforceCallingOrSelfPermission(
17249                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17250                    "deletePackage for user " + userId);
17251        }
17252
17253        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17254            try {
17255                observer.onPackageDeleted(packageName,
17256                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17257            } catch (RemoteException re) {
17258            }
17259            return;
17260        }
17261
17262        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17263            try {
17264                observer.onPackageDeleted(packageName,
17265                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17266            } catch (RemoteException re) {
17267            }
17268            return;
17269        }
17270
17271        if (DEBUG_REMOVE) {
17272            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17273                    + " deleteAllUsers: " + deleteAllUsers + " version="
17274                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17275                    ? "VERSION_CODE_HIGHEST" : versionCode));
17276        }
17277        // Queue up an async operation since the package deletion may take a little while.
17278        mHandler.post(new Runnable() {
17279            public void run() {
17280                mHandler.removeCallbacks(this);
17281                int returnCode;
17282                if (!deleteAllUsers) {
17283                    returnCode = deletePackageX(internalPackageName, versionCode,
17284                            userId, deleteFlags);
17285                } else {
17286                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17287                            internalPackageName, users);
17288                    // If nobody is blocking uninstall, proceed with delete for all users
17289                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17290                        returnCode = deletePackageX(internalPackageName, versionCode,
17291                                userId, deleteFlags);
17292                    } else {
17293                        // Otherwise uninstall individually for users with blockUninstalls=false
17294                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17295                        for (int userId : users) {
17296                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17297                                returnCode = deletePackageX(internalPackageName, versionCode,
17298                                        userId, userFlags);
17299                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17300                                    Slog.w(TAG, "Package delete failed for user " + userId
17301                                            + ", returnCode " + returnCode);
17302                                }
17303                            }
17304                        }
17305                        // The app has only been marked uninstalled for certain users.
17306                        // We still need to report that delete was blocked
17307                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17308                    }
17309                }
17310                try {
17311                    observer.onPackageDeleted(packageName, returnCode, null);
17312                } catch (RemoteException e) {
17313                    Log.i(TAG, "Observer no longer exists.");
17314                } //end catch
17315            } //end run
17316        });
17317    }
17318
17319    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17320        if (pkg.staticSharedLibName != null) {
17321            return pkg.manifestPackageName;
17322        }
17323        return pkg.packageName;
17324    }
17325
17326    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17327        // Handle renamed packages
17328        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17329        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17330
17331        // Is this a static library?
17332        SparseArray<SharedLibraryEntry> versionedLib =
17333                mStaticLibsByDeclaringPackage.get(packageName);
17334        if (versionedLib == null || versionedLib.size() <= 0) {
17335            return packageName;
17336        }
17337
17338        // Figure out which lib versions the caller can see
17339        SparseIntArray versionsCallerCanSee = null;
17340        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17341        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17342                && callingAppId != Process.ROOT_UID) {
17343            versionsCallerCanSee = new SparseIntArray();
17344            String libName = versionedLib.valueAt(0).info.getName();
17345            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17346            if (uidPackages != null) {
17347                for (String uidPackage : uidPackages) {
17348                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17349                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17350                    if (libIdx >= 0) {
17351                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17352                        versionsCallerCanSee.append(libVersion, libVersion);
17353                    }
17354                }
17355            }
17356        }
17357
17358        // Caller can see nothing - done
17359        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17360            return packageName;
17361        }
17362
17363        // Find the version the caller can see and the app version code
17364        SharedLibraryEntry highestVersion = null;
17365        final int versionCount = versionedLib.size();
17366        for (int i = 0; i < versionCount; i++) {
17367            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17368            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17369                    libEntry.info.getVersion()) < 0) {
17370                continue;
17371            }
17372            // TODO: We will change version code to long, so in the new API it is long
17373            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17374            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17375                if (libVersionCode == versionCode) {
17376                    return libEntry.apk;
17377                }
17378            } else if (highestVersion == null) {
17379                highestVersion = libEntry;
17380            } else if (libVersionCode  > highestVersion.info
17381                    .getDeclaringPackage().getVersionCode()) {
17382                highestVersion = libEntry;
17383            }
17384        }
17385
17386        if (highestVersion != null) {
17387            return highestVersion.apk;
17388        }
17389
17390        return packageName;
17391    }
17392
17393    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17394        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17395              || callingUid == Process.SYSTEM_UID) {
17396            return true;
17397        }
17398        final int callingUserId = UserHandle.getUserId(callingUid);
17399        // If the caller installed the pkgName, then allow it to silently uninstall.
17400        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17401            return true;
17402        }
17403
17404        // Allow package verifier to silently uninstall.
17405        if (mRequiredVerifierPackage != null &&
17406                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17407            return true;
17408        }
17409
17410        // Allow package uninstaller to silently uninstall.
17411        if (mRequiredUninstallerPackage != null &&
17412                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17413            return true;
17414        }
17415
17416        // Allow storage manager to silently uninstall.
17417        if (mStorageManagerPackage != null &&
17418                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17419            return true;
17420        }
17421        return false;
17422    }
17423
17424    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17425        int[] result = EMPTY_INT_ARRAY;
17426        for (int userId : userIds) {
17427            if (getBlockUninstallForUser(packageName, userId)) {
17428                result = ArrayUtils.appendInt(result, userId);
17429            }
17430        }
17431        return result;
17432    }
17433
17434    @Override
17435    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17436        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17437    }
17438
17439    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17440        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17441                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17442        try {
17443            if (dpm != null) {
17444                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17445                        /* callingUserOnly =*/ false);
17446                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17447                        : deviceOwnerComponentName.getPackageName();
17448                // Does the package contains the device owner?
17449                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17450                // this check is probably not needed, since DO should be registered as a device
17451                // admin on some user too. (Original bug for this: b/17657954)
17452                if (packageName.equals(deviceOwnerPackageName)) {
17453                    return true;
17454                }
17455                // Does it contain a device admin for any user?
17456                int[] users;
17457                if (userId == UserHandle.USER_ALL) {
17458                    users = sUserManager.getUserIds();
17459                } else {
17460                    users = new int[]{userId};
17461                }
17462                for (int i = 0; i < users.length; ++i) {
17463                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17464                        return true;
17465                    }
17466                }
17467            }
17468        } catch (RemoteException e) {
17469        }
17470        return false;
17471    }
17472
17473    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17474        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17475    }
17476
17477    /**
17478     *  This method is an internal method that could be get invoked either
17479     *  to delete an installed package or to clean up a failed installation.
17480     *  After deleting an installed package, a broadcast is sent to notify any
17481     *  listeners that the package has been removed. For cleaning up a failed
17482     *  installation, the broadcast is not necessary since the package's
17483     *  installation wouldn't have sent the initial broadcast either
17484     *  The key steps in deleting a package are
17485     *  deleting the package information in internal structures like mPackages,
17486     *  deleting the packages base directories through installd
17487     *  updating mSettings to reflect current status
17488     *  persisting settings for later use
17489     *  sending a broadcast if necessary
17490     */
17491    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17492        final PackageRemovedInfo info = new PackageRemovedInfo();
17493        final boolean res;
17494
17495        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17496                ? UserHandle.USER_ALL : userId;
17497
17498        if (isPackageDeviceAdmin(packageName, removeUser)) {
17499            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17500            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17501        }
17502
17503        PackageSetting uninstalledPs = null;
17504
17505        // for the uninstall-updates case and restricted profiles, remember the per-
17506        // user handle installed state
17507        int[] allUsers;
17508        synchronized (mPackages) {
17509            uninstalledPs = mSettings.mPackages.get(packageName);
17510            if (uninstalledPs == null) {
17511                Slog.w(TAG, "Not removing non-existent package " + packageName);
17512                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17513            }
17514
17515            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17516                    && uninstalledPs.versionCode != versionCode) {
17517                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17518                        + uninstalledPs.versionCode + " != " + versionCode);
17519                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17520            }
17521
17522            // Static shared libs can be declared by any package, so let us not
17523            // allow removing a package if it provides a lib others depend on.
17524            PackageParser.Package pkg = mPackages.get(packageName);
17525            if (pkg != null && pkg.staticSharedLibName != null) {
17526                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17527                        pkg.staticSharedLibVersion);
17528                if (libEntry != null) {
17529                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17530                            libEntry.info, 0, userId);
17531                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17532                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17533                                + " hosting lib " + libEntry.info.getName() + " version "
17534                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17535                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17536                    }
17537                }
17538            }
17539
17540            allUsers = sUserManager.getUserIds();
17541            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17542        }
17543
17544        final int freezeUser;
17545        if (isUpdatedSystemApp(uninstalledPs)
17546                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17547            // We're downgrading a system app, which will apply to all users, so
17548            // freeze them all during the downgrade
17549            freezeUser = UserHandle.USER_ALL;
17550        } else {
17551            freezeUser = removeUser;
17552        }
17553
17554        synchronized (mInstallLock) {
17555            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17556            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17557                    deleteFlags, "deletePackageX")) {
17558                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17559                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17560            }
17561            synchronized (mPackages) {
17562                if (res) {
17563                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17564                            info.removedUsers);
17565                    updateSequenceNumberLP(packageName, info.removedUsers);
17566                }
17567            }
17568        }
17569
17570        if (res) {
17571            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17572            info.sendPackageRemovedBroadcasts(killApp);
17573            info.sendSystemPackageUpdatedBroadcasts();
17574            info.sendSystemPackageAppearedBroadcasts();
17575        }
17576        // Force a gc here.
17577        Runtime.getRuntime().gc();
17578        // Delete the resources here after sending the broadcast to let
17579        // other processes clean up before deleting resources.
17580        if (info.args != null) {
17581            synchronized (mInstallLock) {
17582                info.args.doPostDeleteLI(true);
17583            }
17584        }
17585
17586        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17587    }
17588
17589    class PackageRemovedInfo {
17590        String removedPackage;
17591        int uid = -1;
17592        int removedAppId = -1;
17593        int[] origUsers;
17594        int[] removedUsers = null;
17595        SparseArray<Integer> installReasons;
17596        boolean isRemovedPackageSystemUpdate = false;
17597        boolean isUpdate;
17598        boolean dataRemoved;
17599        boolean removedForAllUsers;
17600        boolean isStaticSharedLib;
17601        // Clean up resources deleted packages.
17602        InstallArgs args = null;
17603        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17604        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17605
17606        void sendPackageRemovedBroadcasts(boolean killApp) {
17607            sendPackageRemovedBroadcastInternal(killApp);
17608            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17609            for (int i = 0; i < childCount; i++) {
17610                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17611                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17612            }
17613        }
17614
17615        void sendSystemPackageUpdatedBroadcasts() {
17616            if (isRemovedPackageSystemUpdate) {
17617                sendSystemPackageUpdatedBroadcastsInternal();
17618                final int childCount = (removedChildPackages != null)
17619                        ? removedChildPackages.size() : 0;
17620                for (int i = 0; i < childCount; i++) {
17621                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17622                    if (childInfo.isRemovedPackageSystemUpdate) {
17623                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17624                    }
17625                }
17626            }
17627        }
17628
17629        void sendSystemPackageAppearedBroadcasts() {
17630            final int packageCount = (appearedChildPackages != null)
17631                    ? appearedChildPackages.size() : 0;
17632            for (int i = 0; i < packageCount; i++) {
17633                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17634                sendPackageAddedForNewUsers(installedInfo.name, true,
17635                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17636            }
17637        }
17638
17639        private void sendSystemPackageUpdatedBroadcastsInternal() {
17640            Bundle extras = new Bundle(2);
17641            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17642            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17643            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17644                    extras, 0, null, null, null);
17645            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17646                    extras, 0, null, null, null);
17647            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17648                    null, 0, removedPackage, null, null);
17649        }
17650
17651        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17652            // Don't send static shared library removal broadcasts as these
17653            // libs are visible only the the apps that depend on them an one
17654            // cannot remove the library if it has a dependency.
17655            if (isStaticSharedLib) {
17656                return;
17657            }
17658            Bundle extras = new Bundle(2);
17659            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17660            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17661            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17662            if (isUpdate || isRemovedPackageSystemUpdate) {
17663                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17664            }
17665            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17666            if (removedPackage != null) {
17667                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17668                        extras, 0, null, null, removedUsers);
17669                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17670                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17671                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17672                            null, null, removedUsers);
17673                }
17674            }
17675            if (removedAppId >= 0) {
17676                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17677                        removedUsers);
17678            }
17679        }
17680    }
17681
17682    /*
17683     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17684     * flag is not set, the data directory is removed as well.
17685     * make sure this flag is set for partially installed apps. If not its meaningless to
17686     * delete a partially installed application.
17687     */
17688    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17689            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17690        String packageName = ps.name;
17691        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17692        // Retrieve object to delete permissions for shared user later on
17693        final PackageParser.Package deletedPkg;
17694        final PackageSetting deletedPs;
17695        // reader
17696        synchronized (mPackages) {
17697            deletedPkg = mPackages.get(packageName);
17698            deletedPs = mSettings.mPackages.get(packageName);
17699            if (outInfo != null) {
17700                outInfo.removedPackage = packageName;
17701                outInfo.isStaticSharedLib = deletedPkg != null
17702                        && deletedPkg.staticSharedLibName != null;
17703                outInfo.removedUsers = deletedPs != null
17704                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17705                        : null;
17706            }
17707        }
17708
17709        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17710
17711        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17712            final PackageParser.Package resolvedPkg;
17713            if (deletedPkg != null) {
17714                resolvedPkg = deletedPkg;
17715            } else {
17716                // We don't have a parsed package when it lives on an ejected
17717                // adopted storage device, so fake something together
17718                resolvedPkg = new PackageParser.Package(ps.name);
17719                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17720            }
17721            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17722                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17723            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17724            if (outInfo != null) {
17725                outInfo.dataRemoved = true;
17726            }
17727            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17728        }
17729
17730        int removedAppId = -1;
17731
17732        // writer
17733        synchronized (mPackages) {
17734            boolean installedStateChanged = false;
17735            if (deletedPs != null) {
17736                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17737                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17738                    clearDefaultBrowserIfNeeded(packageName);
17739                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17740                    removedAppId = mSettings.removePackageLPw(packageName);
17741                    if (outInfo != null) {
17742                        outInfo.removedAppId = removedAppId;
17743                    }
17744                    updatePermissionsLPw(deletedPs.name, null, 0);
17745                    if (deletedPs.sharedUser != null) {
17746                        // Remove permissions associated with package. Since runtime
17747                        // permissions are per user we have to kill the removed package
17748                        // or packages running under the shared user of the removed
17749                        // package if revoking the permissions requested only by the removed
17750                        // package is successful and this causes a change in gids.
17751                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17752                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17753                                    userId);
17754                            if (userIdToKill == UserHandle.USER_ALL
17755                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17756                                // If gids changed for this user, kill all affected packages.
17757                                mHandler.post(new Runnable() {
17758                                    @Override
17759                                    public void run() {
17760                                        // This has to happen with no lock held.
17761                                        killApplication(deletedPs.name, deletedPs.appId,
17762                                                KILL_APP_REASON_GIDS_CHANGED);
17763                                    }
17764                                });
17765                                break;
17766                            }
17767                        }
17768                    }
17769                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17770                }
17771                // make sure to preserve per-user disabled state if this removal was just
17772                // a downgrade of a system app to the factory package
17773                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17774                    if (DEBUG_REMOVE) {
17775                        Slog.d(TAG, "Propagating install state across downgrade");
17776                    }
17777                    for (int userId : allUserHandles) {
17778                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17779                        if (DEBUG_REMOVE) {
17780                            Slog.d(TAG, "    user " + userId + " => " + installed);
17781                        }
17782                        if (installed != ps.getInstalled(userId)) {
17783                            installedStateChanged = true;
17784                        }
17785                        ps.setInstalled(installed, userId);
17786                    }
17787                }
17788            }
17789            // can downgrade to reader
17790            if (writeSettings) {
17791                // Save settings now
17792                mSettings.writeLPr();
17793            }
17794            if (installedStateChanged) {
17795                mSettings.writeKernelMappingLPr(ps);
17796            }
17797        }
17798        if (removedAppId != -1) {
17799            // A user ID was deleted here. Go through all users and remove it
17800            // from KeyStore.
17801            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17802        }
17803    }
17804
17805    static boolean locationIsPrivileged(File path) {
17806        try {
17807            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17808                    .getCanonicalPath();
17809            return path.getCanonicalPath().startsWith(privilegedAppDir);
17810        } catch (IOException e) {
17811            Slog.e(TAG, "Unable to access code path " + path);
17812        }
17813        return false;
17814    }
17815
17816    /*
17817     * Tries to delete system package.
17818     */
17819    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17820            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17821            boolean writeSettings) {
17822        if (deletedPs.parentPackageName != null) {
17823            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17824            return false;
17825        }
17826
17827        final boolean applyUserRestrictions
17828                = (allUserHandles != null) && (outInfo.origUsers != null);
17829        final PackageSetting disabledPs;
17830        // Confirm if the system package has been updated
17831        // An updated system app can be deleted. This will also have to restore
17832        // the system pkg from system partition
17833        // reader
17834        synchronized (mPackages) {
17835            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17836        }
17837
17838        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17839                + " disabledPs=" + disabledPs);
17840
17841        if (disabledPs == null) {
17842            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17843            return false;
17844        } else if (DEBUG_REMOVE) {
17845            Slog.d(TAG, "Deleting system pkg from data partition");
17846        }
17847
17848        if (DEBUG_REMOVE) {
17849            if (applyUserRestrictions) {
17850                Slog.d(TAG, "Remembering install states:");
17851                for (int userId : allUserHandles) {
17852                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17853                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17854                }
17855            }
17856        }
17857
17858        // Delete the updated package
17859        outInfo.isRemovedPackageSystemUpdate = true;
17860        if (outInfo.removedChildPackages != null) {
17861            final int childCount = (deletedPs.childPackageNames != null)
17862                    ? deletedPs.childPackageNames.size() : 0;
17863            for (int i = 0; i < childCount; i++) {
17864                String childPackageName = deletedPs.childPackageNames.get(i);
17865                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17866                        .contains(childPackageName)) {
17867                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17868                            childPackageName);
17869                    if (childInfo != null) {
17870                        childInfo.isRemovedPackageSystemUpdate = true;
17871                    }
17872                }
17873            }
17874        }
17875
17876        if (disabledPs.versionCode < deletedPs.versionCode) {
17877            // Delete data for downgrades
17878            flags &= ~PackageManager.DELETE_KEEP_DATA;
17879        } else {
17880            // Preserve data by setting flag
17881            flags |= PackageManager.DELETE_KEEP_DATA;
17882        }
17883
17884        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17885                outInfo, writeSettings, disabledPs.pkg);
17886        if (!ret) {
17887            return false;
17888        }
17889
17890        // writer
17891        synchronized (mPackages) {
17892            // Reinstate the old system package
17893            enableSystemPackageLPw(disabledPs.pkg);
17894            // Remove any native libraries from the upgraded package.
17895            removeNativeBinariesLI(deletedPs);
17896        }
17897
17898        // Install the system package
17899        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17900        int parseFlags = mDefParseFlags
17901                | PackageParser.PARSE_MUST_BE_APK
17902                | PackageParser.PARSE_IS_SYSTEM
17903                | PackageParser.PARSE_IS_SYSTEM_DIR;
17904        if (locationIsPrivileged(disabledPs.codePath)) {
17905            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17906        }
17907
17908        final PackageParser.Package newPkg;
17909        try {
17910            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17911                0 /* currentTime */, null);
17912        } catch (PackageManagerException e) {
17913            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17914                    + e.getMessage());
17915            return false;
17916        }
17917
17918        try {
17919            // update shared libraries for the newly re-installed system package
17920            updateSharedLibrariesLPr(newPkg, null);
17921        } catch (PackageManagerException e) {
17922            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17923        }
17924
17925        prepareAppDataAfterInstallLIF(newPkg);
17926
17927        // writer
17928        synchronized (mPackages) {
17929            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17930
17931            // Propagate the permissions state as we do not want to drop on the floor
17932            // runtime permissions. The update permissions method below will take
17933            // care of removing obsolete permissions and grant install permissions.
17934            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17935            updatePermissionsLPw(newPkg.packageName, newPkg,
17936                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17937
17938            if (applyUserRestrictions) {
17939                boolean installedStateChanged = false;
17940                if (DEBUG_REMOVE) {
17941                    Slog.d(TAG, "Propagating install state across reinstall");
17942                }
17943                for (int userId : allUserHandles) {
17944                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17945                    if (DEBUG_REMOVE) {
17946                        Slog.d(TAG, "    user " + userId + " => " + installed);
17947                    }
17948                    if (installed != ps.getInstalled(userId)) {
17949                        installedStateChanged = true;
17950                    }
17951                    ps.setInstalled(installed, userId);
17952
17953                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17954                }
17955                // Regardless of writeSettings we need to ensure that this restriction
17956                // state propagation is persisted
17957                mSettings.writeAllUsersPackageRestrictionsLPr();
17958                if (installedStateChanged) {
17959                    mSettings.writeKernelMappingLPr(ps);
17960                }
17961            }
17962            // can downgrade to reader here
17963            if (writeSettings) {
17964                mSettings.writeLPr();
17965            }
17966        }
17967        return true;
17968    }
17969
17970    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17971            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17972            PackageRemovedInfo outInfo, boolean writeSettings,
17973            PackageParser.Package replacingPackage) {
17974        synchronized (mPackages) {
17975            if (outInfo != null) {
17976                outInfo.uid = ps.appId;
17977            }
17978
17979            if (outInfo != null && outInfo.removedChildPackages != null) {
17980                final int childCount = (ps.childPackageNames != null)
17981                        ? ps.childPackageNames.size() : 0;
17982                for (int i = 0; i < childCount; i++) {
17983                    String childPackageName = ps.childPackageNames.get(i);
17984                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17985                    if (childPs == null) {
17986                        return false;
17987                    }
17988                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17989                            childPackageName);
17990                    if (childInfo != null) {
17991                        childInfo.uid = childPs.appId;
17992                    }
17993                }
17994            }
17995        }
17996
17997        // Delete package data from internal structures and also remove data if flag is set
17998        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17999
18000        // Delete the child packages data
18001        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18002        for (int i = 0; i < childCount; i++) {
18003            PackageSetting childPs;
18004            synchronized (mPackages) {
18005                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18006            }
18007            if (childPs != null) {
18008                PackageRemovedInfo childOutInfo = (outInfo != null
18009                        && outInfo.removedChildPackages != null)
18010                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18011                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18012                        && (replacingPackage != null
18013                        && !replacingPackage.hasChildPackage(childPs.name))
18014                        ? flags & ~DELETE_KEEP_DATA : flags;
18015                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18016                        deleteFlags, writeSettings);
18017            }
18018        }
18019
18020        // Delete application code and resources only for parent packages
18021        if (ps.parentPackageName == null) {
18022            if (deleteCodeAndResources && (outInfo != null)) {
18023                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18024                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18025                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18026            }
18027        }
18028
18029        return true;
18030    }
18031
18032    @Override
18033    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18034            int userId) {
18035        mContext.enforceCallingOrSelfPermission(
18036                android.Manifest.permission.DELETE_PACKAGES, null);
18037        synchronized (mPackages) {
18038            PackageSetting ps = mSettings.mPackages.get(packageName);
18039            if (ps == null) {
18040                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18041                return false;
18042            }
18043            // Cannot block uninstall of static shared libs as they are
18044            // considered a part of the using app (emulating static linking).
18045            // Also static libs are installed always on internal storage.
18046            PackageParser.Package pkg = mPackages.get(packageName);
18047            if (pkg != null && pkg.staticSharedLibName != null) {
18048                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18049                        + " providing static shared library: " + pkg.staticSharedLibName);
18050                return false;
18051            }
18052            if (!ps.getInstalled(userId)) {
18053                // Can't block uninstall for an app that is not installed or enabled.
18054                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18055                return false;
18056            }
18057            ps.setBlockUninstall(blockUninstall, userId);
18058            mSettings.writePackageRestrictionsLPr(userId);
18059        }
18060        return true;
18061    }
18062
18063    @Override
18064    public boolean getBlockUninstallForUser(String packageName, int userId) {
18065        synchronized (mPackages) {
18066            PackageSetting ps = mSettings.mPackages.get(packageName);
18067            if (ps == null) {
18068                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18069                return false;
18070            }
18071            return ps.getBlockUninstall(userId);
18072        }
18073    }
18074
18075    @Override
18076    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18077        int callingUid = Binder.getCallingUid();
18078        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18079            throw new SecurityException(
18080                    "setRequiredForSystemUser can only be run by the system or root");
18081        }
18082        synchronized (mPackages) {
18083            PackageSetting ps = mSettings.mPackages.get(packageName);
18084            if (ps == null) {
18085                Log.w(TAG, "Package doesn't exist: " + packageName);
18086                return false;
18087            }
18088            if (systemUserApp) {
18089                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18090            } else {
18091                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18092            }
18093            mSettings.writeLPr();
18094        }
18095        return true;
18096    }
18097
18098    /*
18099     * This method handles package deletion in general
18100     */
18101    private boolean deletePackageLIF(String packageName, UserHandle user,
18102            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18103            PackageRemovedInfo outInfo, boolean writeSettings,
18104            PackageParser.Package replacingPackage) {
18105        if (packageName == null) {
18106            Slog.w(TAG, "Attempt to delete null packageName.");
18107            return false;
18108        }
18109
18110        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18111
18112        PackageSetting ps;
18113        synchronized (mPackages) {
18114            ps = mSettings.mPackages.get(packageName);
18115            if (ps == null) {
18116                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18117                return false;
18118            }
18119
18120            if (ps.parentPackageName != null && (!isSystemApp(ps)
18121                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18122                if (DEBUG_REMOVE) {
18123                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18124                            + ((user == null) ? UserHandle.USER_ALL : user));
18125                }
18126                final int removedUserId = (user != null) ? user.getIdentifier()
18127                        : UserHandle.USER_ALL;
18128                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18129                    return false;
18130                }
18131                markPackageUninstalledForUserLPw(ps, user);
18132                scheduleWritePackageRestrictionsLocked(user);
18133                return true;
18134            }
18135        }
18136
18137        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18138                && user.getIdentifier() != UserHandle.USER_ALL)) {
18139            // The caller is asking that the package only be deleted for a single
18140            // user.  To do this, we just mark its uninstalled state and delete
18141            // its data. If this is a system app, we only allow this to happen if
18142            // they have set the special DELETE_SYSTEM_APP which requests different
18143            // semantics than normal for uninstalling system apps.
18144            markPackageUninstalledForUserLPw(ps, user);
18145
18146            if (!isSystemApp(ps)) {
18147                // Do not uninstall the APK if an app should be cached
18148                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18149                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18150                    // Other user still have this package installed, so all
18151                    // we need to do is clear this user's data and save that
18152                    // it is uninstalled.
18153                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18154                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18155                        return false;
18156                    }
18157                    scheduleWritePackageRestrictionsLocked(user);
18158                    return true;
18159                } else {
18160                    // We need to set it back to 'installed' so the uninstall
18161                    // broadcasts will be sent correctly.
18162                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18163                    ps.setInstalled(true, user.getIdentifier());
18164                    mSettings.writeKernelMappingLPr(ps);
18165                }
18166            } else {
18167                // This is a system app, so we assume that the
18168                // other users still have this package installed, so all
18169                // we need to do is clear this user's data and save that
18170                // it is uninstalled.
18171                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18172                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18173                    return false;
18174                }
18175                scheduleWritePackageRestrictionsLocked(user);
18176                return true;
18177            }
18178        }
18179
18180        // If we are deleting a composite package for all users, keep track
18181        // of result for each child.
18182        if (ps.childPackageNames != null && outInfo != null) {
18183            synchronized (mPackages) {
18184                final int childCount = ps.childPackageNames.size();
18185                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18186                for (int i = 0; i < childCount; i++) {
18187                    String childPackageName = ps.childPackageNames.get(i);
18188                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18189                    childInfo.removedPackage = childPackageName;
18190                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18191                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18192                    if (childPs != null) {
18193                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18194                    }
18195                }
18196            }
18197        }
18198
18199        boolean ret = false;
18200        if (isSystemApp(ps)) {
18201            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18202            // When an updated system application is deleted we delete the existing resources
18203            // as well and fall back to existing code in system partition
18204            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18205        } else {
18206            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18207            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18208                    outInfo, writeSettings, replacingPackage);
18209        }
18210
18211        // Take a note whether we deleted the package for all users
18212        if (outInfo != null) {
18213            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18214            if (outInfo.removedChildPackages != null) {
18215                synchronized (mPackages) {
18216                    final int childCount = outInfo.removedChildPackages.size();
18217                    for (int i = 0; i < childCount; i++) {
18218                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18219                        if (childInfo != null) {
18220                            childInfo.removedForAllUsers = mPackages.get(
18221                                    childInfo.removedPackage) == null;
18222                        }
18223                    }
18224                }
18225            }
18226            // If we uninstalled an update to a system app there may be some
18227            // child packages that appeared as they are declared in the system
18228            // app but were not declared in the update.
18229            if (isSystemApp(ps)) {
18230                synchronized (mPackages) {
18231                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18232                    final int childCount = (updatedPs.childPackageNames != null)
18233                            ? updatedPs.childPackageNames.size() : 0;
18234                    for (int i = 0; i < childCount; i++) {
18235                        String childPackageName = updatedPs.childPackageNames.get(i);
18236                        if (outInfo.removedChildPackages == null
18237                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18238                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18239                            if (childPs == null) {
18240                                continue;
18241                            }
18242                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18243                            installRes.name = childPackageName;
18244                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18245                            installRes.pkg = mPackages.get(childPackageName);
18246                            installRes.uid = childPs.pkg.applicationInfo.uid;
18247                            if (outInfo.appearedChildPackages == null) {
18248                                outInfo.appearedChildPackages = new ArrayMap<>();
18249                            }
18250                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18251                        }
18252                    }
18253                }
18254            }
18255        }
18256
18257        return ret;
18258    }
18259
18260    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18261        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18262                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18263        for (int nextUserId : userIds) {
18264            if (DEBUG_REMOVE) {
18265                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18266            }
18267            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18268                    false /*installed*/,
18269                    true /*stopped*/,
18270                    true /*notLaunched*/,
18271                    false /*hidden*/,
18272                    false /*suspended*/,
18273                    false /*instantApp*/,
18274                    null /*lastDisableAppCaller*/,
18275                    null /*enabledComponents*/,
18276                    null /*disabledComponents*/,
18277                    false /*blockUninstall*/,
18278                    ps.readUserState(nextUserId).domainVerificationStatus,
18279                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18280        }
18281        mSettings.writeKernelMappingLPr(ps);
18282    }
18283
18284    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18285            PackageRemovedInfo outInfo) {
18286        final PackageParser.Package pkg;
18287        synchronized (mPackages) {
18288            pkg = mPackages.get(ps.name);
18289        }
18290
18291        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18292                : new int[] {userId};
18293        for (int nextUserId : userIds) {
18294            if (DEBUG_REMOVE) {
18295                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18296                        + nextUserId);
18297            }
18298
18299            destroyAppDataLIF(pkg, userId,
18300                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18301            destroyAppProfilesLIF(pkg, userId);
18302            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18303            schedulePackageCleaning(ps.name, nextUserId, false);
18304            synchronized (mPackages) {
18305                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18306                    scheduleWritePackageRestrictionsLocked(nextUserId);
18307                }
18308                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18309            }
18310        }
18311
18312        if (outInfo != null) {
18313            outInfo.removedPackage = ps.name;
18314            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18315            outInfo.removedAppId = ps.appId;
18316            outInfo.removedUsers = userIds;
18317        }
18318
18319        return true;
18320    }
18321
18322    private final class ClearStorageConnection implements ServiceConnection {
18323        IMediaContainerService mContainerService;
18324
18325        @Override
18326        public void onServiceConnected(ComponentName name, IBinder service) {
18327            synchronized (this) {
18328                mContainerService = IMediaContainerService.Stub
18329                        .asInterface(Binder.allowBlocking(service));
18330                notifyAll();
18331            }
18332        }
18333
18334        @Override
18335        public void onServiceDisconnected(ComponentName name) {
18336        }
18337    }
18338
18339    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18340        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18341
18342        final boolean mounted;
18343        if (Environment.isExternalStorageEmulated()) {
18344            mounted = true;
18345        } else {
18346            final String status = Environment.getExternalStorageState();
18347
18348            mounted = status.equals(Environment.MEDIA_MOUNTED)
18349                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18350        }
18351
18352        if (!mounted) {
18353            return;
18354        }
18355
18356        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18357        int[] users;
18358        if (userId == UserHandle.USER_ALL) {
18359            users = sUserManager.getUserIds();
18360        } else {
18361            users = new int[] { userId };
18362        }
18363        final ClearStorageConnection conn = new ClearStorageConnection();
18364        if (mContext.bindServiceAsUser(
18365                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18366            try {
18367                for (int curUser : users) {
18368                    long timeout = SystemClock.uptimeMillis() + 5000;
18369                    synchronized (conn) {
18370                        long now;
18371                        while (conn.mContainerService == null &&
18372                                (now = SystemClock.uptimeMillis()) < timeout) {
18373                            try {
18374                                conn.wait(timeout - now);
18375                            } catch (InterruptedException e) {
18376                            }
18377                        }
18378                    }
18379                    if (conn.mContainerService == null) {
18380                        return;
18381                    }
18382
18383                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18384                    clearDirectory(conn.mContainerService,
18385                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18386                    if (allData) {
18387                        clearDirectory(conn.mContainerService,
18388                                userEnv.buildExternalStorageAppDataDirs(packageName));
18389                        clearDirectory(conn.mContainerService,
18390                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18391                    }
18392                }
18393            } finally {
18394                mContext.unbindService(conn);
18395            }
18396        }
18397    }
18398
18399    @Override
18400    public void clearApplicationProfileData(String packageName) {
18401        enforceSystemOrRoot("Only the system can clear all profile data");
18402
18403        final PackageParser.Package pkg;
18404        synchronized (mPackages) {
18405            pkg = mPackages.get(packageName);
18406        }
18407
18408        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18409            synchronized (mInstallLock) {
18410                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18411                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18412                        true /* removeBaseMarker */);
18413            }
18414        }
18415    }
18416
18417    @Override
18418    public void clearApplicationUserData(final String packageName,
18419            final IPackageDataObserver observer, final int userId) {
18420        mContext.enforceCallingOrSelfPermission(
18421                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18422
18423        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18424                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18425
18426        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18427            throw new SecurityException("Cannot clear data for a protected package: "
18428                    + packageName);
18429        }
18430        // Queue up an async operation since the package deletion may take a little while.
18431        mHandler.post(new Runnable() {
18432            public void run() {
18433                mHandler.removeCallbacks(this);
18434                final boolean succeeded;
18435                try (PackageFreezer freezer = freezePackage(packageName,
18436                        "clearApplicationUserData")) {
18437                    synchronized (mInstallLock) {
18438                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18439                    }
18440                    clearExternalStorageDataSync(packageName, userId, true);
18441                    synchronized (mPackages) {
18442                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18443                                packageName, userId);
18444                    }
18445                }
18446                if (succeeded) {
18447                    // invoke DeviceStorageMonitor's update method to clear any notifications
18448                    DeviceStorageMonitorInternal dsm = LocalServices
18449                            .getService(DeviceStorageMonitorInternal.class);
18450                    if (dsm != null) {
18451                        dsm.checkMemory();
18452                    }
18453                }
18454                if(observer != null) {
18455                    try {
18456                        observer.onRemoveCompleted(packageName, succeeded);
18457                    } catch (RemoteException e) {
18458                        Log.i(TAG, "Observer no longer exists.");
18459                    }
18460                } //end if observer
18461            } //end run
18462        });
18463    }
18464
18465    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18466        if (packageName == null) {
18467            Slog.w(TAG, "Attempt to delete null packageName.");
18468            return false;
18469        }
18470
18471        // Try finding details about the requested package
18472        PackageParser.Package pkg;
18473        synchronized (mPackages) {
18474            pkg = mPackages.get(packageName);
18475            if (pkg == null) {
18476                final PackageSetting ps = mSettings.mPackages.get(packageName);
18477                if (ps != null) {
18478                    pkg = ps.pkg;
18479                }
18480            }
18481
18482            if (pkg == null) {
18483                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18484                return false;
18485            }
18486
18487            PackageSetting ps = (PackageSetting) pkg.mExtras;
18488            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18489        }
18490
18491        clearAppDataLIF(pkg, userId,
18492                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18493
18494        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18495        removeKeystoreDataIfNeeded(userId, appId);
18496
18497        UserManagerInternal umInternal = getUserManagerInternal();
18498        final int flags;
18499        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18500            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18501        } else if (umInternal.isUserRunning(userId)) {
18502            flags = StorageManager.FLAG_STORAGE_DE;
18503        } else {
18504            flags = 0;
18505        }
18506        prepareAppDataContentsLIF(pkg, userId, flags);
18507
18508        return true;
18509    }
18510
18511    /**
18512     * Reverts user permission state changes (permissions and flags) in
18513     * all packages for a given user.
18514     *
18515     * @param userId The device user for which to do a reset.
18516     */
18517    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18518        final int packageCount = mPackages.size();
18519        for (int i = 0; i < packageCount; i++) {
18520            PackageParser.Package pkg = mPackages.valueAt(i);
18521            PackageSetting ps = (PackageSetting) pkg.mExtras;
18522            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18523        }
18524    }
18525
18526    private void resetNetworkPolicies(int userId) {
18527        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18528    }
18529
18530    /**
18531     * Reverts user permission state changes (permissions and flags).
18532     *
18533     * @param ps The package for which to reset.
18534     * @param userId The device user for which to do a reset.
18535     */
18536    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18537            final PackageSetting ps, final int userId) {
18538        if (ps.pkg == null) {
18539            return;
18540        }
18541
18542        // These are flags that can change base on user actions.
18543        final int userSettableMask = FLAG_PERMISSION_USER_SET
18544                | FLAG_PERMISSION_USER_FIXED
18545                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18546                | FLAG_PERMISSION_REVIEW_REQUIRED;
18547
18548        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18549                | FLAG_PERMISSION_POLICY_FIXED;
18550
18551        boolean writeInstallPermissions = false;
18552        boolean writeRuntimePermissions = false;
18553
18554        final int permissionCount = ps.pkg.requestedPermissions.size();
18555        for (int i = 0; i < permissionCount; i++) {
18556            String permission = ps.pkg.requestedPermissions.get(i);
18557
18558            BasePermission bp = mSettings.mPermissions.get(permission);
18559            if (bp == null) {
18560                continue;
18561            }
18562
18563            // If shared user we just reset the state to which only this app contributed.
18564            if (ps.sharedUser != null) {
18565                boolean used = false;
18566                final int packageCount = ps.sharedUser.packages.size();
18567                for (int j = 0; j < packageCount; j++) {
18568                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18569                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18570                            && pkg.pkg.requestedPermissions.contains(permission)) {
18571                        used = true;
18572                        break;
18573                    }
18574                }
18575                if (used) {
18576                    continue;
18577                }
18578            }
18579
18580            PermissionsState permissionsState = ps.getPermissionsState();
18581
18582            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18583
18584            // Always clear the user settable flags.
18585            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18586                    bp.name) != null;
18587            // If permission review is enabled and this is a legacy app, mark the
18588            // permission as requiring a review as this is the initial state.
18589            int flags = 0;
18590            if (mPermissionReviewRequired
18591                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18592                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18593            }
18594            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18595                if (hasInstallState) {
18596                    writeInstallPermissions = true;
18597                } else {
18598                    writeRuntimePermissions = true;
18599                }
18600            }
18601
18602            // Below is only runtime permission handling.
18603            if (!bp.isRuntime()) {
18604                continue;
18605            }
18606
18607            // Never clobber system or policy.
18608            if ((oldFlags & policyOrSystemFlags) != 0) {
18609                continue;
18610            }
18611
18612            // If this permission was granted by default, make sure it is.
18613            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18614                if (permissionsState.grantRuntimePermission(bp, userId)
18615                        != PERMISSION_OPERATION_FAILURE) {
18616                    writeRuntimePermissions = true;
18617                }
18618            // If permission review is enabled the permissions for a legacy apps
18619            // are represented as constantly granted runtime ones, so don't revoke.
18620            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18621                // Otherwise, reset the permission.
18622                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18623                switch (revokeResult) {
18624                    case PERMISSION_OPERATION_SUCCESS:
18625                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18626                        writeRuntimePermissions = true;
18627                        final int appId = ps.appId;
18628                        mHandler.post(new Runnable() {
18629                            @Override
18630                            public void run() {
18631                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18632                            }
18633                        });
18634                    } break;
18635                }
18636            }
18637        }
18638
18639        // Synchronously write as we are taking permissions away.
18640        if (writeRuntimePermissions) {
18641            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18642        }
18643
18644        // Synchronously write as we are taking permissions away.
18645        if (writeInstallPermissions) {
18646            mSettings.writeLPr();
18647        }
18648    }
18649
18650    /**
18651     * Remove entries from the keystore daemon. Will only remove it if the
18652     * {@code appId} is valid.
18653     */
18654    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18655        if (appId < 0) {
18656            return;
18657        }
18658
18659        final KeyStore keyStore = KeyStore.getInstance();
18660        if (keyStore != null) {
18661            if (userId == UserHandle.USER_ALL) {
18662                for (final int individual : sUserManager.getUserIds()) {
18663                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18664                }
18665            } else {
18666                keyStore.clearUid(UserHandle.getUid(userId, appId));
18667            }
18668        } else {
18669            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18670        }
18671    }
18672
18673    @Override
18674    public void deleteApplicationCacheFiles(final String packageName,
18675            final IPackageDataObserver observer) {
18676        final int userId = UserHandle.getCallingUserId();
18677        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18678    }
18679
18680    @Override
18681    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18682            final IPackageDataObserver observer) {
18683        mContext.enforceCallingOrSelfPermission(
18684                android.Manifest.permission.DELETE_CACHE_FILES, null);
18685        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18686                /* requireFullPermission= */ true, /* checkShell= */ false,
18687                "delete application cache files");
18688
18689        final PackageParser.Package pkg;
18690        synchronized (mPackages) {
18691            pkg = mPackages.get(packageName);
18692        }
18693
18694        // Queue up an async operation since the package deletion may take a little while.
18695        mHandler.post(new Runnable() {
18696            public void run() {
18697                synchronized (mInstallLock) {
18698                    final int flags = StorageManager.FLAG_STORAGE_DE
18699                            | StorageManager.FLAG_STORAGE_CE;
18700                    // We're only clearing cache files, so we don't care if the
18701                    // app is unfrozen and still able to run
18702                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18703                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18704                }
18705                clearExternalStorageDataSync(packageName, userId, false);
18706                if (observer != null) {
18707                    try {
18708                        observer.onRemoveCompleted(packageName, true);
18709                    } catch (RemoteException e) {
18710                        Log.i(TAG, "Observer no longer exists.");
18711                    }
18712                }
18713            }
18714        });
18715    }
18716
18717    @Override
18718    public void getPackageSizeInfo(final String packageName, int userHandle,
18719            final IPackageStatsObserver observer) {
18720        mContext.enforceCallingOrSelfPermission(
18721                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18722        if (packageName == null) {
18723            throw new IllegalArgumentException("Attempt to get size of null packageName");
18724        }
18725
18726        PackageStats stats = new PackageStats(packageName, userHandle);
18727
18728        /*
18729         * Queue up an async operation since the package measurement may take a
18730         * little while.
18731         */
18732        Message msg = mHandler.obtainMessage(INIT_COPY);
18733        msg.obj = new MeasureParams(stats, observer);
18734        mHandler.sendMessage(msg);
18735    }
18736
18737    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18738        final PackageSetting ps;
18739        synchronized (mPackages) {
18740            ps = mSettings.mPackages.get(packageName);
18741            if (ps == null) {
18742                Slog.w(TAG, "Failed to find settings for " + packageName);
18743                return false;
18744            }
18745        }
18746
18747        final String[] packageNames = { packageName };
18748        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18749        final String[] codePaths = { ps.codePathString };
18750
18751        try {
18752            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18753                    ps.appId, ceDataInodes, codePaths, stats);
18754
18755            // For now, ignore code size of packages on system partition
18756            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18757                stats.codeSize = 0;
18758            }
18759
18760            // External clients expect these to be tracked separately
18761            stats.dataSize -= stats.cacheSize;
18762
18763        } catch (InstallerException e) {
18764            Slog.w(TAG, String.valueOf(e));
18765            return false;
18766        }
18767
18768        return true;
18769    }
18770
18771    private int getUidTargetSdkVersionLockedLPr(int uid) {
18772        Object obj = mSettings.getUserIdLPr(uid);
18773        if (obj instanceof SharedUserSetting) {
18774            final SharedUserSetting sus = (SharedUserSetting) obj;
18775            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18776            final Iterator<PackageSetting> it = sus.packages.iterator();
18777            while (it.hasNext()) {
18778                final PackageSetting ps = it.next();
18779                if (ps.pkg != null) {
18780                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18781                    if (v < vers) vers = v;
18782                }
18783            }
18784            return vers;
18785        } else if (obj instanceof PackageSetting) {
18786            final PackageSetting ps = (PackageSetting) obj;
18787            if (ps.pkg != null) {
18788                return ps.pkg.applicationInfo.targetSdkVersion;
18789            }
18790        }
18791        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18792    }
18793
18794    @Override
18795    public void addPreferredActivity(IntentFilter filter, int match,
18796            ComponentName[] set, ComponentName activity, int userId) {
18797        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18798                "Adding preferred");
18799    }
18800
18801    private void addPreferredActivityInternal(IntentFilter filter, int match,
18802            ComponentName[] set, ComponentName activity, boolean always, int userId,
18803            String opname) {
18804        // writer
18805        int callingUid = Binder.getCallingUid();
18806        enforceCrossUserPermission(callingUid, userId,
18807                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18808        if (filter.countActions() == 0) {
18809            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18810            return;
18811        }
18812        synchronized (mPackages) {
18813            if (mContext.checkCallingOrSelfPermission(
18814                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18815                    != PackageManager.PERMISSION_GRANTED) {
18816                if (getUidTargetSdkVersionLockedLPr(callingUid)
18817                        < Build.VERSION_CODES.FROYO) {
18818                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18819                            + callingUid);
18820                    return;
18821                }
18822                mContext.enforceCallingOrSelfPermission(
18823                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18824            }
18825
18826            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18827            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18828                    + userId + ":");
18829            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18830            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18831            scheduleWritePackageRestrictionsLocked(userId);
18832            postPreferredActivityChangedBroadcast(userId);
18833        }
18834    }
18835
18836    private void postPreferredActivityChangedBroadcast(int userId) {
18837        mHandler.post(() -> {
18838            final IActivityManager am = ActivityManager.getService();
18839            if (am == null) {
18840                return;
18841            }
18842
18843            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18844            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18845            try {
18846                am.broadcastIntent(null, intent, null, null,
18847                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18848                        null, false, false, userId);
18849            } catch (RemoteException e) {
18850            }
18851        });
18852    }
18853
18854    @Override
18855    public void replacePreferredActivity(IntentFilter filter, int match,
18856            ComponentName[] set, ComponentName activity, int userId) {
18857        if (filter.countActions() != 1) {
18858            throw new IllegalArgumentException(
18859                    "replacePreferredActivity expects filter to have only 1 action.");
18860        }
18861        if (filter.countDataAuthorities() != 0
18862                || filter.countDataPaths() != 0
18863                || filter.countDataSchemes() > 1
18864                || filter.countDataTypes() != 0) {
18865            throw new IllegalArgumentException(
18866                    "replacePreferredActivity expects filter to have no data authorities, " +
18867                    "paths, or types; and at most one scheme.");
18868        }
18869
18870        final int callingUid = Binder.getCallingUid();
18871        enforceCrossUserPermission(callingUid, userId,
18872                true /* requireFullPermission */, false /* checkShell */,
18873                "replace preferred activity");
18874        synchronized (mPackages) {
18875            if (mContext.checkCallingOrSelfPermission(
18876                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18877                    != PackageManager.PERMISSION_GRANTED) {
18878                if (getUidTargetSdkVersionLockedLPr(callingUid)
18879                        < Build.VERSION_CODES.FROYO) {
18880                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18881                            + Binder.getCallingUid());
18882                    return;
18883                }
18884                mContext.enforceCallingOrSelfPermission(
18885                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18886            }
18887
18888            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18889            if (pir != null) {
18890                // Get all of the existing entries that exactly match this filter.
18891                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18892                if (existing != null && existing.size() == 1) {
18893                    PreferredActivity cur = existing.get(0);
18894                    if (DEBUG_PREFERRED) {
18895                        Slog.i(TAG, "Checking replace of preferred:");
18896                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18897                        if (!cur.mPref.mAlways) {
18898                            Slog.i(TAG, "  -- CUR; not mAlways!");
18899                        } else {
18900                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18901                            Slog.i(TAG, "  -- CUR: mSet="
18902                                    + Arrays.toString(cur.mPref.mSetComponents));
18903                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18904                            Slog.i(TAG, "  -- NEW: mMatch="
18905                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18906                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18907                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18908                        }
18909                    }
18910                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18911                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18912                            && cur.mPref.sameSet(set)) {
18913                        // Setting the preferred activity to what it happens to be already
18914                        if (DEBUG_PREFERRED) {
18915                            Slog.i(TAG, "Replacing with same preferred activity "
18916                                    + cur.mPref.mShortComponent + " for user "
18917                                    + userId + ":");
18918                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18919                        }
18920                        return;
18921                    }
18922                }
18923
18924                if (existing != null) {
18925                    if (DEBUG_PREFERRED) {
18926                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18927                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18928                    }
18929                    for (int i = 0; i < existing.size(); i++) {
18930                        PreferredActivity pa = existing.get(i);
18931                        if (DEBUG_PREFERRED) {
18932                            Slog.i(TAG, "Removing existing preferred activity "
18933                                    + pa.mPref.mComponent + ":");
18934                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18935                        }
18936                        pir.removeFilter(pa);
18937                    }
18938                }
18939            }
18940            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18941                    "Replacing preferred");
18942        }
18943    }
18944
18945    @Override
18946    public void clearPackagePreferredActivities(String packageName) {
18947        final int uid = Binder.getCallingUid();
18948        // writer
18949        synchronized (mPackages) {
18950            PackageParser.Package pkg = mPackages.get(packageName);
18951            if (pkg == null || pkg.applicationInfo.uid != uid) {
18952                if (mContext.checkCallingOrSelfPermission(
18953                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18954                        != PackageManager.PERMISSION_GRANTED) {
18955                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18956                            < Build.VERSION_CODES.FROYO) {
18957                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18958                                + Binder.getCallingUid());
18959                        return;
18960                    }
18961                    mContext.enforceCallingOrSelfPermission(
18962                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18963                }
18964            }
18965
18966            int user = UserHandle.getCallingUserId();
18967            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18968                scheduleWritePackageRestrictionsLocked(user);
18969            }
18970        }
18971    }
18972
18973    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18974    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18975        ArrayList<PreferredActivity> removed = null;
18976        boolean changed = false;
18977        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18978            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18979            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18980            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18981                continue;
18982            }
18983            Iterator<PreferredActivity> it = pir.filterIterator();
18984            while (it.hasNext()) {
18985                PreferredActivity pa = it.next();
18986                // Mark entry for removal only if it matches the package name
18987                // and the entry is of type "always".
18988                if (packageName == null ||
18989                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18990                                && pa.mPref.mAlways)) {
18991                    if (removed == null) {
18992                        removed = new ArrayList<PreferredActivity>();
18993                    }
18994                    removed.add(pa);
18995                }
18996            }
18997            if (removed != null) {
18998                for (int j=0; j<removed.size(); j++) {
18999                    PreferredActivity pa = removed.get(j);
19000                    pir.removeFilter(pa);
19001                }
19002                changed = true;
19003            }
19004        }
19005        if (changed) {
19006            postPreferredActivityChangedBroadcast(userId);
19007        }
19008        return changed;
19009    }
19010
19011    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19012    private void clearIntentFilterVerificationsLPw(int userId) {
19013        final int packageCount = mPackages.size();
19014        for (int i = 0; i < packageCount; i++) {
19015            PackageParser.Package pkg = mPackages.valueAt(i);
19016            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19017        }
19018    }
19019
19020    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19021    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19022        if (userId == UserHandle.USER_ALL) {
19023            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19024                    sUserManager.getUserIds())) {
19025                for (int oneUserId : sUserManager.getUserIds()) {
19026                    scheduleWritePackageRestrictionsLocked(oneUserId);
19027                }
19028            }
19029        } else {
19030            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19031                scheduleWritePackageRestrictionsLocked(userId);
19032            }
19033        }
19034    }
19035
19036    void clearDefaultBrowserIfNeeded(String packageName) {
19037        for (int oneUserId : sUserManager.getUserIds()) {
19038            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19039            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19040            if (packageName.equals(defaultBrowserPackageName)) {
19041                setDefaultBrowserPackageName(null, oneUserId);
19042            }
19043        }
19044    }
19045
19046    @Override
19047    public void resetApplicationPreferences(int userId) {
19048        mContext.enforceCallingOrSelfPermission(
19049                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19050        final long identity = Binder.clearCallingIdentity();
19051        // writer
19052        try {
19053            synchronized (mPackages) {
19054                clearPackagePreferredActivitiesLPw(null, userId);
19055                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19056                // TODO: We have to reset the default SMS and Phone. This requires
19057                // significant refactoring to keep all default apps in the package
19058                // manager (cleaner but more work) or have the services provide
19059                // callbacks to the package manager to request a default app reset.
19060                applyFactoryDefaultBrowserLPw(userId);
19061                clearIntentFilterVerificationsLPw(userId);
19062                primeDomainVerificationsLPw(userId);
19063                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19064                scheduleWritePackageRestrictionsLocked(userId);
19065            }
19066            resetNetworkPolicies(userId);
19067        } finally {
19068            Binder.restoreCallingIdentity(identity);
19069        }
19070    }
19071
19072    @Override
19073    public int getPreferredActivities(List<IntentFilter> outFilters,
19074            List<ComponentName> outActivities, String packageName) {
19075
19076        int num = 0;
19077        final int userId = UserHandle.getCallingUserId();
19078        // reader
19079        synchronized (mPackages) {
19080            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19081            if (pir != null) {
19082                final Iterator<PreferredActivity> it = pir.filterIterator();
19083                while (it.hasNext()) {
19084                    final PreferredActivity pa = it.next();
19085                    if (packageName == null
19086                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19087                                    && pa.mPref.mAlways)) {
19088                        if (outFilters != null) {
19089                            outFilters.add(new IntentFilter(pa));
19090                        }
19091                        if (outActivities != null) {
19092                            outActivities.add(pa.mPref.mComponent);
19093                        }
19094                    }
19095                }
19096            }
19097        }
19098
19099        return num;
19100    }
19101
19102    @Override
19103    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19104            int userId) {
19105        int callingUid = Binder.getCallingUid();
19106        if (callingUid != Process.SYSTEM_UID) {
19107            throw new SecurityException(
19108                    "addPersistentPreferredActivity can only be run by the system");
19109        }
19110        if (filter.countActions() == 0) {
19111            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19112            return;
19113        }
19114        synchronized (mPackages) {
19115            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19116                    ":");
19117            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19118            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19119                    new PersistentPreferredActivity(filter, activity));
19120            scheduleWritePackageRestrictionsLocked(userId);
19121            postPreferredActivityChangedBroadcast(userId);
19122        }
19123    }
19124
19125    @Override
19126    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19127        int callingUid = Binder.getCallingUid();
19128        if (callingUid != Process.SYSTEM_UID) {
19129            throw new SecurityException(
19130                    "clearPackagePersistentPreferredActivities can only be run by the system");
19131        }
19132        ArrayList<PersistentPreferredActivity> removed = null;
19133        boolean changed = false;
19134        synchronized (mPackages) {
19135            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19136                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19137                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19138                        .valueAt(i);
19139                if (userId != thisUserId) {
19140                    continue;
19141                }
19142                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19143                while (it.hasNext()) {
19144                    PersistentPreferredActivity ppa = it.next();
19145                    // Mark entry for removal only if it matches the package name.
19146                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19147                        if (removed == null) {
19148                            removed = new ArrayList<PersistentPreferredActivity>();
19149                        }
19150                        removed.add(ppa);
19151                    }
19152                }
19153                if (removed != null) {
19154                    for (int j=0; j<removed.size(); j++) {
19155                        PersistentPreferredActivity ppa = removed.get(j);
19156                        ppir.removeFilter(ppa);
19157                    }
19158                    changed = true;
19159                }
19160            }
19161
19162            if (changed) {
19163                scheduleWritePackageRestrictionsLocked(userId);
19164                postPreferredActivityChangedBroadcast(userId);
19165            }
19166        }
19167    }
19168
19169    /**
19170     * Common machinery for picking apart a restored XML blob and passing
19171     * it to a caller-supplied functor to be applied to the running system.
19172     */
19173    private void restoreFromXml(XmlPullParser parser, int userId,
19174            String expectedStartTag, BlobXmlRestorer functor)
19175            throws IOException, XmlPullParserException {
19176        int type;
19177        while ((type = parser.next()) != XmlPullParser.START_TAG
19178                && type != XmlPullParser.END_DOCUMENT) {
19179        }
19180        if (type != XmlPullParser.START_TAG) {
19181            // oops didn't find a start tag?!
19182            if (DEBUG_BACKUP) {
19183                Slog.e(TAG, "Didn't find start tag during restore");
19184            }
19185            return;
19186        }
19187Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19188        // this is supposed to be TAG_PREFERRED_BACKUP
19189        if (!expectedStartTag.equals(parser.getName())) {
19190            if (DEBUG_BACKUP) {
19191                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19192            }
19193            return;
19194        }
19195
19196        // skip interfering stuff, then we're aligned with the backing implementation
19197        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19198Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19199        functor.apply(parser, userId);
19200    }
19201
19202    private interface BlobXmlRestorer {
19203        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19204    }
19205
19206    /**
19207     * Non-Binder method, support for the backup/restore mechanism: write the
19208     * full set of preferred activities in its canonical XML format.  Returns the
19209     * XML output as a byte array, or null if there is none.
19210     */
19211    @Override
19212    public byte[] getPreferredActivityBackup(int userId) {
19213        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19214            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19215        }
19216
19217        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19218        try {
19219            final XmlSerializer serializer = new FastXmlSerializer();
19220            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19221            serializer.startDocument(null, true);
19222            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19223
19224            synchronized (mPackages) {
19225                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19226            }
19227
19228            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19229            serializer.endDocument();
19230            serializer.flush();
19231        } catch (Exception e) {
19232            if (DEBUG_BACKUP) {
19233                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19234            }
19235            return null;
19236        }
19237
19238        return dataStream.toByteArray();
19239    }
19240
19241    @Override
19242    public void restorePreferredActivities(byte[] backup, int userId) {
19243        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19244            throw new SecurityException("Only the system may call restorePreferredActivities()");
19245        }
19246
19247        try {
19248            final XmlPullParser parser = Xml.newPullParser();
19249            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19250            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19251                    new BlobXmlRestorer() {
19252                        @Override
19253                        public void apply(XmlPullParser parser, int userId)
19254                                throws XmlPullParserException, IOException {
19255                            synchronized (mPackages) {
19256                                mSettings.readPreferredActivitiesLPw(parser, userId);
19257                            }
19258                        }
19259                    } );
19260        } catch (Exception e) {
19261            if (DEBUG_BACKUP) {
19262                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19263            }
19264        }
19265    }
19266
19267    /**
19268     * Non-Binder method, support for the backup/restore mechanism: write the
19269     * default browser (etc) settings in its canonical XML format.  Returns the default
19270     * browser XML representation as a byte array, or null if there is none.
19271     */
19272    @Override
19273    public byte[] getDefaultAppsBackup(int userId) {
19274        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19275            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19276        }
19277
19278        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19279        try {
19280            final XmlSerializer serializer = new FastXmlSerializer();
19281            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19282            serializer.startDocument(null, true);
19283            serializer.startTag(null, TAG_DEFAULT_APPS);
19284
19285            synchronized (mPackages) {
19286                mSettings.writeDefaultAppsLPr(serializer, userId);
19287            }
19288
19289            serializer.endTag(null, TAG_DEFAULT_APPS);
19290            serializer.endDocument();
19291            serializer.flush();
19292        } catch (Exception e) {
19293            if (DEBUG_BACKUP) {
19294                Slog.e(TAG, "Unable to write default apps for backup", e);
19295            }
19296            return null;
19297        }
19298
19299        return dataStream.toByteArray();
19300    }
19301
19302    @Override
19303    public void restoreDefaultApps(byte[] backup, int userId) {
19304        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19305            throw new SecurityException("Only the system may call restoreDefaultApps()");
19306        }
19307
19308        try {
19309            final XmlPullParser parser = Xml.newPullParser();
19310            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19311            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19312                    new BlobXmlRestorer() {
19313                        @Override
19314                        public void apply(XmlPullParser parser, int userId)
19315                                throws XmlPullParserException, IOException {
19316                            synchronized (mPackages) {
19317                                mSettings.readDefaultAppsLPw(parser, userId);
19318                            }
19319                        }
19320                    } );
19321        } catch (Exception e) {
19322            if (DEBUG_BACKUP) {
19323                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19324            }
19325        }
19326    }
19327
19328    @Override
19329    public byte[] getIntentFilterVerificationBackup(int userId) {
19330        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19331            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19332        }
19333
19334        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19335        try {
19336            final XmlSerializer serializer = new FastXmlSerializer();
19337            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19338            serializer.startDocument(null, true);
19339            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19340
19341            synchronized (mPackages) {
19342                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19343            }
19344
19345            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19346            serializer.endDocument();
19347            serializer.flush();
19348        } catch (Exception e) {
19349            if (DEBUG_BACKUP) {
19350                Slog.e(TAG, "Unable to write default apps for backup", e);
19351            }
19352            return null;
19353        }
19354
19355        return dataStream.toByteArray();
19356    }
19357
19358    @Override
19359    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19360        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19361            throw new SecurityException("Only the system may call restorePreferredActivities()");
19362        }
19363
19364        try {
19365            final XmlPullParser parser = Xml.newPullParser();
19366            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19367            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19368                    new BlobXmlRestorer() {
19369                        @Override
19370                        public void apply(XmlPullParser parser, int userId)
19371                                throws XmlPullParserException, IOException {
19372                            synchronized (mPackages) {
19373                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19374                                mSettings.writeLPr();
19375                            }
19376                        }
19377                    } );
19378        } catch (Exception e) {
19379            if (DEBUG_BACKUP) {
19380                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19381            }
19382        }
19383    }
19384
19385    @Override
19386    public byte[] getPermissionGrantBackup(int userId) {
19387        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19388            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19389        }
19390
19391        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19392        try {
19393            final XmlSerializer serializer = new FastXmlSerializer();
19394            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19395            serializer.startDocument(null, true);
19396            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19397
19398            synchronized (mPackages) {
19399                serializeRuntimePermissionGrantsLPr(serializer, userId);
19400            }
19401
19402            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19403            serializer.endDocument();
19404            serializer.flush();
19405        } catch (Exception e) {
19406            if (DEBUG_BACKUP) {
19407                Slog.e(TAG, "Unable to write default apps for backup", e);
19408            }
19409            return null;
19410        }
19411
19412        return dataStream.toByteArray();
19413    }
19414
19415    @Override
19416    public void restorePermissionGrants(byte[] backup, int userId) {
19417        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19418            throw new SecurityException("Only the system may call restorePermissionGrants()");
19419        }
19420
19421        try {
19422            final XmlPullParser parser = Xml.newPullParser();
19423            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19424            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19425                    new BlobXmlRestorer() {
19426                        @Override
19427                        public void apply(XmlPullParser parser, int userId)
19428                                throws XmlPullParserException, IOException {
19429                            synchronized (mPackages) {
19430                                processRestoredPermissionGrantsLPr(parser, userId);
19431                            }
19432                        }
19433                    } );
19434        } catch (Exception e) {
19435            if (DEBUG_BACKUP) {
19436                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19437            }
19438        }
19439    }
19440
19441    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19442            throws IOException {
19443        serializer.startTag(null, TAG_ALL_GRANTS);
19444
19445        final int N = mSettings.mPackages.size();
19446        for (int i = 0; i < N; i++) {
19447            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19448            boolean pkgGrantsKnown = false;
19449
19450            PermissionsState packagePerms = ps.getPermissionsState();
19451
19452            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19453                final int grantFlags = state.getFlags();
19454                // only look at grants that are not system/policy fixed
19455                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19456                    final boolean isGranted = state.isGranted();
19457                    // And only back up the user-twiddled state bits
19458                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19459                        final String packageName = mSettings.mPackages.keyAt(i);
19460                        if (!pkgGrantsKnown) {
19461                            serializer.startTag(null, TAG_GRANT);
19462                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19463                            pkgGrantsKnown = true;
19464                        }
19465
19466                        final boolean userSet =
19467                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19468                        final boolean userFixed =
19469                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19470                        final boolean revoke =
19471                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19472
19473                        serializer.startTag(null, TAG_PERMISSION);
19474                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19475                        if (isGranted) {
19476                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19477                        }
19478                        if (userSet) {
19479                            serializer.attribute(null, ATTR_USER_SET, "true");
19480                        }
19481                        if (userFixed) {
19482                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19483                        }
19484                        if (revoke) {
19485                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19486                        }
19487                        serializer.endTag(null, TAG_PERMISSION);
19488                    }
19489                }
19490            }
19491
19492            if (pkgGrantsKnown) {
19493                serializer.endTag(null, TAG_GRANT);
19494            }
19495        }
19496
19497        serializer.endTag(null, TAG_ALL_GRANTS);
19498    }
19499
19500    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19501            throws XmlPullParserException, IOException {
19502        String pkgName = null;
19503        int outerDepth = parser.getDepth();
19504        int type;
19505        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19506                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19507            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19508                continue;
19509            }
19510
19511            final String tagName = parser.getName();
19512            if (tagName.equals(TAG_GRANT)) {
19513                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19514                if (DEBUG_BACKUP) {
19515                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19516                }
19517            } else if (tagName.equals(TAG_PERMISSION)) {
19518
19519                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19520                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19521
19522                int newFlagSet = 0;
19523                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19524                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19525                }
19526                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19527                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19528                }
19529                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19530                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19531                }
19532                if (DEBUG_BACKUP) {
19533                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19534                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19535                }
19536                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19537                if (ps != null) {
19538                    // Already installed so we apply the grant immediately
19539                    if (DEBUG_BACKUP) {
19540                        Slog.v(TAG, "        + already installed; applying");
19541                    }
19542                    PermissionsState perms = ps.getPermissionsState();
19543                    BasePermission bp = mSettings.mPermissions.get(permName);
19544                    if (bp != null) {
19545                        if (isGranted) {
19546                            perms.grantRuntimePermission(bp, userId);
19547                        }
19548                        if (newFlagSet != 0) {
19549                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19550                        }
19551                    }
19552                } else {
19553                    // Need to wait for post-restore install to apply the grant
19554                    if (DEBUG_BACKUP) {
19555                        Slog.v(TAG, "        - not yet installed; saving for later");
19556                    }
19557                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19558                            isGranted, newFlagSet, userId);
19559                }
19560            } else {
19561                PackageManagerService.reportSettingsProblem(Log.WARN,
19562                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19563                XmlUtils.skipCurrentTag(parser);
19564            }
19565        }
19566
19567        scheduleWriteSettingsLocked();
19568        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19569    }
19570
19571    @Override
19572    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19573            int sourceUserId, int targetUserId, int flags) {
19574        mContext.enforceCallingOrSelfPermission(
19575                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19576        int callingUid = Binder.getCallingUid();
19577        enforceOwnerRights(ownerPackage, callingUid);
19578        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19579        if (intentFilter.countActions() == 0) {
19580            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19581            return;
19582        }
19583        synchronized (mPackages) {
19584            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19585                    ownerPackage, targetUserId, flags);
19586            CrossProfileIntentResolver resolver =
19587                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19588            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19589            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19590            if (existing != null) {
19591                int size = existing.size();
19592                for (int i = 0; i < size; i++) {
19593                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19594                        return;
19595                    }
19596                }
19597            }
19598            resolver.addFilter(newFilter);
19599            scheduleWritePackageRestrictionsLocked(sourceUserId);
19600        }
19601    }
19602
19603    @Override
19604    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19605        mContext.enforceCallingOrSelfPermission(
19606                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19607        int callingUid = Binder.getCallingUid();
19608        enforceOwnerRights(ownerPackage, callingUid);
19609        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19610        synchronized (mPackages) {
19611            CrossProfileIntentResolver resolver =
19612                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19613            ArraySet<CrossProfileIntentFilter> set =
19614                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19615            for (CrossProfileIntentFilter filter : set) {
19616                if (filter.getOwnerPackage().equals(ownerPackage)) {
19617                    resolver.removeFilter(filter);
19618                }
19619            }
19620            scheduleWritePackageRestrictionsLocked(sourceUserId);
19621        }
19622    }
19623
19624    // Enforcing that callingUid is owning pkg on userId
19625    private void enforceOwnerRights(String pkg, int callingUid) {
19626        // The system owns everything.
19627        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19628            return;
19629        }
19630        int callingUserId = UserHandle.getUserId(callingUid);
19631        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19632        if (pi == null) {
19633            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19634                    + callingUserId);
19635        }
19636        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19637            throw new SecurityException("Calling uid " + callingUid
19638                    + " does not own package " + pkg);
19639        }
19640    }
19641
19642    @Override
19643    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19644        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19645    }
19646
19647    private Intent getHomeIntent() {
19648        Intent intent = new Intent(Intent.ACTION_MAIN);
19649        intent.addCategory(Intent.CATEGORY_HOME);
19650        intent.addCategory(Intent.CATEGORY_DEFAULT);
19651        return intent;
19652    }
19653
19654    private IntentFilter getHomeFilter() {
19655        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19656        filter.addCategory(Intent.CATEGORY_HOME);
19657        filter.addCategory(Intent.CATEGORY_DEFAULT);
19658        return filter;
19659    }
19660
19661    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19662            int userId) {
19663        Intent intent  = getHomeIntent();
19664        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19665                PackageManager.GET_META_DATA, userId);
19666        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19667                true, false, false, userId);
19668
19669        allHomeCandidates.clear();
19670        if (list != null) {
19671            for (ResolveInfo ri : list) {
19672                allHomeCandidates.add(ri);
19673            }
19674        }
19675        return (preferred == null || preferred.activityInfo == null)
19676                ? null
19677                : new ComponentName(preferred.activityInfo.packageName,
19678                        preferred.activityInfo.name);
19679    }
19680
19681    @Override
19682    public void setHomeActivity(ComponentName comp, int userId) {
19683        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19684        getHomeActivitiesAsUser(homeActivities, userId);
19685
19686        boolean found = false;
19687
19688        final int size = homeActivities.size();
19689        final ComponentName[] set = new ComponentName[size];
19690        for (int i = 0; i < size; i++) {
19691            final ResolveInfo candidate = homeActivities.get(i);
19692            final ActivityInfo info = candidate.activityInfo;
19693            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19694            set[i] = activityName;
19695            if (!found && activityName.equals(comp)) {
19696                found = true;
19697            }
19698        }
19699        if (!found) {
19700            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19701                    + userId);
19702        }
19703        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19704                set, comp, userId);
19705    }
19706
19707    private @Nullable String getSetupWizardPackageName() {
19708        final Intent intent = new Intent(Intent.ACTION_MAIN);
19709        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19710
19711        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19712                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19713                        | MATCH_DISABLED_COMPONENTS,
19714                UserHandle.myUserId());
19715        if (matches.size() == 1) {
19716            return matches.get(0).getComponentInfo().packageName;
19717        } else {
19718            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19719                    + ": matches=" + matches);
19720            return null;
19721        }
19722    }
19723
19724    private @Nullable String getStorageManagerPackageName() {
19725        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19726
19727        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19728                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19729                        | MATCH_DISABLED_COMPONENTS,
19730                UserHandle.myUserId());
19731        if (matches.size() == 1) {
19732            return matches.get(0).getComponentInfo().packageName;
19733        } else {
19734            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19735                    + matches.size() + ": matches=" + matches);
19736            return null;
19737        }
19738    }
19739
19740    @Override
19741    public void setApplicationEnabledSetting(String appPackageName,
19742            int newState, int flags, int userId, String callingPackage) {
19743        if (!sUserManager.exists(userId)) return;
19744        if (callingPackage == null) {
19745            callingPackage = Integer.toString(Binder.getCallingUid());
19746        }
19747        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19748    }
19749
19750    @Override
19751    public void setComponentEnabledSetting(ComponentName componentName,
19752            int newState, int flags, int userId) {
19753        if (!sUserManager.exists(userId)) return;
19754        setEnabledSetting(componentName.getPackageName(),
19755                componentName.getClassName(), newState, flags, userId, null);
19756    }
19757
19758    private void setEnabledSetting(final String packageName, String className, int newState,
19759            final int flags, int userId, String callingPackage) {
19760        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19761              || newState == COMPONENT_ENABLED_STATE_ENABLED
19762              || newState == COMPONENT_ENABLED_STATE_DISABLED
19763              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19764              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19765            throw new IllegalArgumentException("Invalid new component state: "
19766                    + newState);
19767        }
19768        PackageSetting pkgSetting;
19769        final int uid = Binder.getCallingUid();
19770        final int permission;
19771        if (uid == Process.SYSTEM_UID) {
19772            permission = PackageManager.PERMISSION_GRANTED;
19773        } else {
19774            permission = mContext.checkCallingOrSelfPermission(
19775                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19776        }
19777        enforceCrossUserPermission(uid, userId,
19778                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19779        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19780        boolean sendNow = false;
19781        boolean isApp = (className == null);
19782        String componentName = isApp ? packageName : className;
19783        int packageUid = -1;
19784        ArrayList<String> components;
19785
19786        // writer
19787        synchronized (mPackages) {
19788            pkgSetting = mSettings.mPackages.get(packageName);
19789            if (pkgSetting == null) {
19790                if (className == null) {
19791                    throw new IllegalArgumentException("Unknown package: " + packageName);
19792                }
19793                throw new IllegalArgumentException(
19794                        "Unknown component: " + packageName + "/" + className);
19795            }
19796        }
19797
19798        // Limit who can change which apps
19799        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19800            // Don't allow apps that don't have permission to modify other apps
19801            if (!allowedByPermission) {
19802                throw new SecurityException(
19803                        "Permission Denial: attempt to change component state from pid="
19804                        + Binder.getCallingPid()
19805                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19806            }
19807            // Don't allow changing protected packages.
19808            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19809                throw new SecurityException("Cannot disable a protected package: " + packageName);
19810            }
19811        }
19812
19813        synchronized (mPackages) {
19814            if (uid == Process.SHELL_UID
19815                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19816                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19817                // unless it is a test package.
19818                int oldState = pkgSetting.getEnabled(userId);
19819                if (className == null
19820                    &&
19821                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19822                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19823                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19824                    &&
19825                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19826                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19827                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19828                    // ok
19829                } else {
19830                    throw new SecurityException(
19831                            "Shell cannot change component state for " + packageName + "/"
19832                            + className + " to " + newState);
19833                }
19834            }
19835            if (className == null) {
19836                // We're dealing with an application/package level state change
19837                if (pkgSetting.getEnabled(userId) == newState) {
19838                    // Nothing to do
19839                    return;
19840                }
19841                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19842                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19843                    // Don't care about who enables an app.
19844                    callingPackage = null;
19845                }
19846                pkgSetting.setEnabled(newState, userId, callingPackage);
19847                // pkgSetting.pkg.mSetEnabled = newState;
19848            } else {
19849                // We're dealing with a component level state change
19850                // First, verify that this is a valid class name.
19851                PackageParser.Package pkg = pkgSetting.pkg;
19852                if (pkg == null || !pkg.hasComponentClassName(className)) {
19853                    if (pkg != null &&
19854                            pkg.applicationInfo.targetSdkVersion >=
19855                                    Build.VERSION_CODES.JELLY_BEAN) {
19856                        throw new IllegalArgumentException("Component class " + className
19857                                + " does not exist in " + packageName);
19858                    } else {
19859                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19860                                + className + " does not exist in " + packageName);
19861                    }
19862                }
19863                switch (newState) {
19864                case COMPONENT_ENABLED_STATE_ENABLED:
19865                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19866                        return;
19867                    }
19868                    break;
19869                case COMPONENT_ENABLED_STATE_DISABLED:
19870                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19871                        return;
19872                    }
19873                    break;
19874                case COMPONENT_ENABLED_STATE_DEFAULT:
19875                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19876                        return;
19877                    }
19878                    break;
19879                default:
19880                    Slog.e(TAG, "Invalid new component state: " + newState);
19881                    return;
19882                }
19883            }
19884            scheduleWritePackageRestrictionsLocked(userId);
19885            updateSequenceNumberLP(packageName, new int[] { userId });
19886            components = mPendingBroadcasts.get(userId, packageName);
19887            final boolean newPackage = components == null;
19888            if (newPackage) {
19889                components = new ArrayList<String>();
19890            }
19891            if (!components.contains(componentName)) {
19892                components.add(componentName);
19893            }
19894            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19895                sendNow = true;
19896                // Purge entry from pending broadcast list if another one exists already
19897                // since we are sending one right away.
19898                mPendingBroadcasts.remove(userId, packageName);
19899            } else {
19900                if (newPackage) {
19901                    mPendingBroadcasts.put(userId, packageName, components);
19902                }
19903                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19904                    // Schedule a message
19905                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19906                }
19907            }
19908        }
19909
19910        long callingId = Binder.clearCallingIdentity();
19911        try {
19912            if (sendNow) {
19913                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19914                sendPackageChangedBroadcast(packageName,
19915                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19916            }
19917        } finally {
19918            Binder.restoreCallingIdentity(callingId);
19919        }
19920    }
19921
19922    @Override
19923    public void flushPackageRestrictionsAsUser(int userId) {
19924        if (!sUserManager.exists(userId)) {
19925            return;
19926        }
19927        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19928                false /* checkShell */, "flushPackageRestrictions");
19929        synchronized (mPackages) {
19930            mSettings.writePackageRestrictionsLPr(userId);
19931            mDirtyUsers.remove(userId);
19932            if (mDirtyUsers.isEmpty()) {
19933                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19934            }
19935        }
19936    }
19937
19938    private void sendPackageChangedBroadcast(String packageName,
19939            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19940        if (DEBUG_INSTALL)
19941            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19942                    + componentNames);
19943        Bundle extras = new Bundle(4);
19944        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19945        String nameList[] = new String[componentNames.size()];
19946        componentNames.toArray(nameList);
19947        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19948        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19949        extras.putInt(Intent.EXTRA_UID, packageUid);
19950        // If this is not reporting a change of the overall package, then only send it
19951        // to registered receivers.  We don't want to launch a swath of apps for every
19952        // little component state change.
19953        final int flags = !componentNames.contains(packageName)
19954                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19955        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19956                new int[] {UserHandle.getUserId(packageUid)});
19957    }
19958
19959    @Override
19960    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19961        if (!sUserManager.exists(userId)) return;
19962        final int uid = Binder.getCallingUid();
19963        final int permission = mContext.checkCallingOrSelfPermission(
19964                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19965        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19966        enforceCrossUserPermission(uid, userId,
19967                true /* requireFullPermission */, true /* checkShell */, "stop package");
19968        // writer
19969        synchronized (mPackages) {
19970            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19971                    allowedByPermission, uid, userId)) {
19972                scheduleWritePackageRestrictionsLocked(userId);
19973            }
19974        }
19975    }
19976
19977    @Override
19978    public String getInstallerPackageName(String packageName) {
19979        // reader
19980        synchronized (mPackages) {
19981            return mSettings.getInstallerPackageNameLPr(packageName);
19982        }
19983    }
19984
19985    public boolean isOrphaned(String packageName) {
19986        // reader
19987        synchronized (mPackages) {
19988            return mSettings.isOrphaned(packageName);
19989        }
19990    }
19991
19992    @Override
19993    public int getApplicationEnabledSetting(String packageName, int userId) {
19994        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19995        int uid = Binder.getCallingUid();
19996        enforceCrossUserPermission(uid, userId,
19997                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19998        // reader
19999        synchronized (mPackages) {
20000            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20001        }
20002    }
20003
20004    @Override
20005    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20006        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20007        int uid = Binder.getCallingUid();
20008        enforceCrossUserPermission(uid, userId,
20009                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20010        // reader
20011        synchronized (mPackages) {
20012            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20013        }
20014    }
20015
20016    @Override
20017    public void enterSafeMode() {
20018        enforceSystemOrRoot("Only the system can request entering safe mode");
20019
20020        if (!mSystemReady) {
20021            mSafeMode = true;
20022        }
20023    }
20024
20025    @Override
20026    public void systemReady() {
20027        mSystemReady = true;
20028
20029        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20030        // disabled after already being started.
20031        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20032                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20033
20034        // Read the compatibilty setting when the system is ready.
20035        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20036                mContext.getContentResolver(),
20037                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20038        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20039        if (DEBUG_SETTINGS) {
20040            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20041        }
20042
20043        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20044
20045        synchronized (mPackages) {
20046            // Verify that all of the preferred activity components actually
20047            // exist.  It is possible for applications to be updated and at
20048            // that point remove a previously declared activity component that
20049            // had been set as a preferred activity.  We try to clean this up
20050            // the next time we encounter that preferred activity, but it is
20051            // possible for the user flow to never be able to return to that
20052            // situation so here we do a sanity check to make sure we haven't
20053            // left any junk around.
20054            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20055            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20056                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20057                removed.clear();
20058                for (PreferredActivity pa : pir.filterSet()) {
20059                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20060                        removed.add(pa);
20061                    }
20062                }
20063                if (removed.size() > 0) {
20064                    for (int r=0; r<removed.size(); r++) {
20065                        PreferredActivity pa = removed.get(r);
20066                        Slog.w(TAG, "Removing dangling preferred activity: "
20067                                + pa.mPref.mComponent);
20068                        pir.removeFilter(pa);
20069                    }
20070                    mSettings.writePackageRestrictionsLPr(
20071                            mSettings.mPreferredActivities.keyAt(i));
20072                }
20073            }
20074
20075            for (int userId : UserManagerService.getInstance().getUserIds()) {
20076                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20077                    grantPermissionsUserIds = ArrayUtils.appendInt(
20078                            grantPermissionsUserIds, userId);
20079                }
20080            }
20081        }
20082        sUserManager.systemReady();
20083
20084        // If we upgraded grant all default permissions before kicking off.
20085        for (int userId : grantPermissionsUserIds) {
20086            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20087        }
20088
20089        // If we did not grant default permissions, we preload from this the
20090        // default permission exceptions lazily to ensure we don't hit the
20091        // disk on a new user creation.
20092        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20093            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20094        }
20095
20096        // Kick off any messages waiting for system ready
20097        if (mPostSystemReadyMessages != null) {
20098            for (Message msg : mPostSystemReadyMessages) {
20099                msg.sendToTarget();
20100            }
20101            mPostSystemReadyMessages = null;
20102        }
20103
20104        // Watch for external volumes that come and go over time
20105        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20106        storage.registerListener(mStorageListener);
20107
20108        mInstallerService.systemReady();
20109        mPackageDexOptimizer.systemReady();
20110
20111        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20112                StorageManagerInternal.class);
20113        StorageManagerInternal.addExternalStoragePolicy(
20114                new StorageManagerInternal.ExternalStorageMountPolicy() {
20115            @Override
20116            public int getMountMode(int uid, String packageName) {
20117                if (Process.isIsolated(uid)) {
20118                    return Zygote.MOUNT_EXTERNAL_NONE;
20119                }
20120                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20121                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20122                }
20123                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20124                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20125                }
20126                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20127                    return Zygote.MOUNT_EXTERNAL_READ;
20128                }
20129                return Zygote.MOUNT_EXTERNAL_WRITE;
20130            }
20131
20132            @Override
20133            public boolean hasExternalStorage(int uid, String packageName) {
20134                return true;
20135            }
20136        });
20137
20138        // Now that we're mostly running, clean up stale users and apps
20139        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20140        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20141
20142        if (mPrivappPermissionsViolations != null) {
20143            Slog.wtf(TAG,"Signature|privileged permissions not in "
20144                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20145            mPrivappPermissionsViolations = null;
20146        }
20147    }
20148
20149    @Override
20150    public boolean isSafeMode() {
20151        return mSafeMode;
20152    }
20153
20154    @Override
20155    public boolean hasSystemUidErrors() {
20156        return mHasSystemUidErrors;
20157    }
20158
20159    static String arrayToString(int[] array) {
20160        StringBuffer buf = new StringBuffer(128);
20161        buf.append('[');
20162        if (array != null) {
20163            for (int i=0; i<array.length; i++) {
20164                if (i > 0) buf.append(", ");
20165                buf.append(array[i]);
20166            }
20167        }
20168        buf.append(']');
20169        return buf.toString();
20170    }
20171
20172    static class DumpState {
20173        public static final int DUMP_LIBS = 1 << 0;
20174        public static final int DUMP_FEATURES = 1 << 1;
20175        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20176        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20177        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20178        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20179        public static final int DUMP_PERMISSIONS = 1 << 6;
20180        public static final int DUMP_PACKAGES = 1 << 7;
20181        public static final int DUMP_SHARED_USERS = 1 << 8;
20182        public static final int DUMP_MESSAGES = 1 << 9;
20183        public static final int DUMP_PROVIDERS = 1 << 10;
20184        public static final int DUMP_VERIFIERS = 1 << 11;
20185        public static final int DUMP_PREFERRED = 1 << 12;
20186        public static final int DUMP_PREFERRED_XML = 1 << 13;
20187        public static final int DUMP_KEYSETS = 1 << 14;
20188        public static final int DUMP_VERSION = 1 << 15;
20189        public static final int DUMP_INSTALLS = 1 << 16;
20190        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20191        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20192        public static final int DUMP_FROZEN = 1 << 19;
20193        public static final int DUMP_DEXOPT = 1 << 20;
20194        public static final int DUMP_COMPILER_STATS = 1 << 21;
20195
20196        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20197
20198        private int mTypes;
20199
20200        private int mOptions;
20201
20202        private boolean mTitlePrinted;
20203
20204        private SharedUserSetting mSharedUser;
20205
20206        public boolean isDumping(int type) {
20207            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20208                return true;
20209            }
20210
20211            return (mTypes & type) != 0;
20212        }
20213
20214        public void setDump(int type) {
20215            mTypes |= type;
20216        }
20217
20218        public boolean isOptionEnabled(int option) {
20219            return (mOptions & option) != 0;
20220        }
20221
20222        public void setOptionEnabled(int option) {
20223            mOptions |= option;
20224        }
20225
20226        public boolean onTitlePrinted() {
20227            final boolean printed = mTitlePrinted;
20228            mTitlePrinted = true;
20229            return printed;
20230        }
20231
20232        public boolean getTitlePrinted() {
20233            return mTitlePrinted;
20234        }
20235
20236        public void setTitlePrinted(boolean enabled) {
20237            mTitlePrinted = enabled;
20238        }
20239
20240        public SharedUserSetting getSharedUser() {
20241            return mSharedUser;
20242        }
20243
20244        public void setSharedUser(SharedUserSetting user) {
20245            mSharedUser = user;
20246        }
20247    }
20248
20249    @Override
20250    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20251            FileDescriptor err, String[] args, ShellCallback callback,
20252            ResultReceiver resultReceiver) {
20253        (new PackageManagerShellCommand(this)).exec(
20254                this, in, out, err, args, callback, resultReceiver);
20255    }
20256
20257    @Override
20258    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20259        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20260                != PackageManager.PERMISSION_GRANTED) {
20261            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20262                    + Binder.getCallingPid()
20263                    + ", uid=" + Binder.getCallingUid()
20264                    + " without permission "
20265                    + android.Manifest.permission.DUMP);
20266            return;
20267        }
20268
20269        DumpState dumpState = new DumpState();
20270        boolean fullPreferred = false;
20271        boolean checkin = false;
20272
20273        String packageName = null;
20274        ArraySet<String> permissionNames = null;
20275
20276        int opti = 0;
20277        while (opti < args.length) {
20278            String opt = args[opti];
20279            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20280                break;
20281            }
20282            opti++;
20283
20284            if ("-a".equals(opt)) {
20285                // Right now we only know how to print all.
20286            } else if ("-h".equals(opt)) {
20287                pw.println("Package manager dump options:");
20288                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20289                pw.println("    --checkin: dump for a checkin");
20290                pw.println("    -f: print details of intent filters");
20291                pw.println("    -h: print this help");
20292                pw.println("  cmd may be one of:");
20293                pw.println("    l[ibraries]: list known shared libraries");
20294                pw.println("    f[eatures]: list device features");
20295                pw.println("    k[eysets]: print known keysets");
20296                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20297                pw.println("    perm[issions]: dump permissions");
20298                pw.println("    permission [name ...]: dump declaration and use of given permission");
20299                pw.println("    pref[erred]: print preferred package settings");
20300                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20301                pw.println("    prov[iders]: dump content providers");
20302                pw.println("    p[ackages]: dump installed packages");
20303                pw.println("    s[hared-users]: dump shared user IDs");
20304                pw.println("    m[essages]: print collected runtime messages");
20305                pw.println("    v[erifiers]: print package verifier info");
20306                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20307                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20308                pw.println("    version: print database version info");
20309                pw.println("    write: write current settings now");
20310                pw.println("    installs: details about install sessions");
20311                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20312                pw.println("    dexopt: dump dexopt state");
20313                pw.println("    compiler-stats: dump compiler statistics");
20314                pw.println("    <package.name>: info about given package");
20315                return;
20316            } else if ("--checkin".equals(opt)) {
20317                checkin = true;
20318            } else if ("-f".equals(opt)) {
20319                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20320            } else {
20321                pw.println("Unknown argument: " + opt + "; use -h for help");
20322            }
20323        }
20324
20325        // Is the caller requesting to dump a particular piece of data?
20326        if (opti < args.length) {
20327            String cmd = args[opti];
20328            opti++;
20329            // Is this a package name?
20330            if ("android".equals(cmd) || cmd.contains(".")) {
20331                packageName = cmd;
20332                // When dumping a single package, we always dump all of its
20333                // filter information since the amount of data will be reasonable.
20334                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20335            } else if ("check-permission".equals(cmd)) {
20336                if (opti >= args.length) {
20337                    pw.println("Error: check-permission missing permission argument");
20338                    return;
20339                }
20340                String perm = args[opti];
20341                opti++;
20342                if (opti >= args.length) {
20343                    pw.println("Error: check-permission missing package argument");
20344                    return;
20345                }
20346
20347                String pkg = args[opti];
20348                opti++;
20349                int user = UserHandle.getUserId(Binder.getCallingUid());
20350                if (opti < args.length) {
20351                    try {
20352                        user = Integer.parseInt(args[opti]);
20353                    } catch (NumberFormatException e) {
20354                        pw.println("Error: check-permission user argument is not a number: "
20355                                + args[opti]);
20356                        return;
20357                    }
20358                }
20359
20360                // Normalize package name to handle renamed packages and static libs
20361                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20362
20363                pw.println(checkPermission(perm, pkg, user));
20364                return;
20365            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20366                dumpState.setDump(DumpState.DUMP_LIBS);
20367            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20368                dumpState.setDump(DumpState.DUMP_FEATURES);
20369            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20370                if (opti >= args.length) {
20371                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20372                            | DumpState.DUMP_SERVICE_RESOLVERS
20373                            | DumpState.DUMP_RECEIVER_RESOLVERS
20374                            | DumpState.DUMP_CONTENT_RESOLVERS);
20375                } else {
20376                    while (opti < args.length) {
20377                        String name = args[opti];
20378                        if ("a".equals(name) || "activity".equals(name)) {
20379                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20380                        } else if ("s".equals(name) || "service".equals(name)) {
20381                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20382                        } else if ("r".equals(name) || "receiver".equals(name)) {
20383                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20384                        } else if ("c".equals(name) || "content".equals(name)) {
20385                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20386                        } else {
20387                            pw.println("Error: unknown resolver table type: " + name);
20388                            return;
20389                        }
20390                        opti++;
20391                    }
20392                }
20393            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20394                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20395            } else if ("permission".equals(cmd)) {
20396                if (opti >= args.length) {
20397                    pw.println("Error: permission requires permission name");
20398                    return;
20399                }
20400                permissionNames = new ArraySet<>();
20401                while (opti < args.length) {
20402                    permissionNames.add(args[opti]);
20403                    opti++;
20404                }
20405                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20406                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20407            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20408                dumpState.setDump(DumpState.DUMP_PREFERRED);
20409            } else if ("preferred-xml".equals(cmd)) {
20410                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20411                if (opti < args.length && "--full".equals(args[opti])) {
20412                    fullPreferred = true;
20413                    opti++;
20414                }
20415            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20416                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20417            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20418                dumpState.setDump(DumpState.DUMP_PACKAGES);
20419            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20420                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20421            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20422                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20423            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20424                dumpState.setDump(DumpState.DUMP_MESSAGES);
20425            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20426                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20427            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20428                    || "intent-filter-verifiers".equals(cmd)) {
20429                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20430            } else if ("version".equals(cmd)) {
20431                dumpState.setDump(DumpState.DUMP_VERSION);
20432            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20433                dumpState.setDump(DumpState.DUMP_KEYSETS);
20434            } else if ("installs".equals(cmd)) {
20435                dumpState.setDump(DumpState.DUMP_INSTALLS);
20436            } else if ("frozen".equals(cmd)) {
20437                dumpState.setDump(DumpState.DUMP_FROZEN);
20438            } else if ("dexopt".equals(cmd)) {
20439                dumpState.setDump(DumpState.DUMP_DEXOPT);
20440            } else if ("compiler-stats".equals(cmd)) {
20441                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20442            } else if ("write".equals(cmd)) {
20443                synchronized (mPackages) {
20444                    mSettings.writeLPr();
20445                    pw.println("Settings written.");
20446                    return;
20447                }
20448            }
20449        }
20450
20451        if (checkin) {
20452            pw.println("vers,1");
20453        }
20454
20455        // reader
20456        synchronized (mPackages) {
20457            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20458                if (!checkin) {
20459                    if (dumpState.onTitlePrinted())
20460                        pw.println();
20461                    pw.println("Database versions:");
20462                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20463                }
20464            }
20465
20466            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20467                if (!checkin) {
20468                    if (dumpState.onTitlePrinted())
20469                        pw.println();
20470                    pw.println("Verifiers:");
20471                    pw.print("  Required: ");
20472                    pw.print(mRequiredVerifierPackage);
20473                    pw.print(" (uid=");
20474                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20475                            UserHandle.USER_SYSTEM));
20476                    pw.println(")");
20477                } else if (mRequiredVerifierPackage != null) {
20478                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20479                    pw.print(",");
20480                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20481                            UserHandle.USER_SYSTEM));
20482                }
20483            }
20484
20485            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20486                    packageName == null) {
20487                if (mIntentFilterVerifierComponent != null) {
20488                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20489                    if (!checkin) {
20490                        if (dumpState.onTitlePrinted())
20491                            pw.println();
20492                        pw.println("Intent Filter Verifier:");
20493                        pw.print("  Using: ");
20494                        pw.print(verifierPackageName);
20495                        pw.print(" (uid=");
20496                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20497                                UserHandle.USER_SYSTEM));
20498                        pw.println(")");
20499                    } else if (verifierPackageName != null) {
20500                        pw.print("ifv,"); pw.print(verifierPackageName);
20501                        pw.print(",");
20502                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20503                                UserHandle.USER_SYSTEM));
20504                    }
20505                } else {
20506                    pw.println();
20507                    pw.println("No Intent Filter Verifier available!");
20508                }
20509            }
20510
20511            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20512                boolean printedHeader = false;
20513                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20514                while (it.hasNext()) {
20515                    String libName = it.next();
20516                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20517                    if (versionedLib == null) {
20518                        continue;
20519                    }
20520                    final int versionCount = versionedLib.size();
20521                    for (int i = 0; i < versionCount; i++) {
20522                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20523                        if (!checkin) {
20524                            if (!printedHeader) {
20525                                if (dumpState.onTitlePrinted())
20526                                    pw.println();
20527                                pw.println("Libraries:");
20528                                printedHeader = true;
20529                            }
20530                            pw.print("  ");
20531                        } else {
20532                            pw.print("lib,");
20533                        }
20534                        pw.print(libEntry.info.getName());
20535                        if (libEntry.info.isStatic()) {
20536                            pw.print(" version=" + libEntry.info.getVersion());
20537                        }
20538                        if (!checkin) {
20539                            pw.print(" -> ");
20540                        }
20541                        if (libEntry.path != null) {
20542                            pw.print(" (jar) ");
20543                            pw.print(libEntry.path);
20544                        } else {
20545                            pw.print(" (apk) ");
20546                            pw.print(libEntry.apk);
20547                        }
20548                        pw.println();
20549                    }
20550                }
20551            }
20552
20553            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20554                if (dumpState.onTitlePrinted())
20555                    pw.println();
20556                if (!checkin) {
20557                    pw.println("Features:");
20558                }
20559
20560                synchronized (mAvailableFeatures) {
20561                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20562                        if (checkin) {
20563                            pw.print("feat,");
20564                            pw.print(feat.name);
20565                            pw.print(",");
20566                            pw.println(feat.version);
20567                        } else {
20568                            pw.print("  ");
20569                            pw.print(feat.name);
20570                            if (feat.version > 0) {
20571                                pw.print(" version=");
20572                                pw.print(feat.version);
20573                            }
20574                            pw.println();
20575                        }
20576                    }
20577                }
20578            }
20579
20580            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20581                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20582                        : "Activity Resolver Table:", "  ", packageName,
20583                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20584                    dumpState.setTitlePrinted(true);
20585                }
20586            }
20587            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20588                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20589                        : "Receiver Resolver Table:", "  ", packageName,
20590                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20591                    dumpState.setTitlePrinted(true);
20592                }
20593            }
20594            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20595                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20596                        : "Service Resolver Table:", "  ", packageName,
20597                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20598                    dumpState.setTitlePrinted(true);
20599                }
20600            }
20601            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20602                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20603                        : "Provider Resolver Table:", "  ", packageName,
20604                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20605                    dumpState.setTitlePrinted(true);
20606                }
20607            }
20608
20609            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20610                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20611                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20612                    int user = mSettings.mPreferredActivities.keyAt(i);
20613                    if (pir.dump(pw,
20614                            dumpState.getTitlePrinted()
20615                                ? "\nPreferred Activities User " + user + ":"
20616                                : "Preferred Activities User " + user + ":", "  ",
20617                            packageName, true, false)) {
20618                        dumpState.setTitlePrinted(true);
20619                    }
20620                }
20621            }
20622
20623            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20624                pw.flush();
20625                FileOutputStream fout = new FileOutputStream(fd);
20626                BufferedOutputStream str = new BufferedOutputStream(fout);
20627                XmlSerializer serializer = new FastXmlSerializer();
20628                try {
20629                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20630                    serializer.startDocument(null, true);
20631                    serializer.setFeature(
20632                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20633                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20634                    serializer.endDocument();
20635                    serializer.flush();
20636                } catch (IllegalArgumentException e) {
20637                    pw.println("Failed writing: " + e);
20638                } catch (IllegalStateException e) {
20639                    pw.println("Failed writing: " + e);
20640                } catch (IOException e) {
20641                    pw.println("Failed writing: " + e);
20642                }
20643            }
20644
20645            if (!checkin
20646                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20647                    && packageName == null) {
20648                pw.println();
20649                int count = mSettings.mPackages.size();
20650                if (count == 0) {
20651                    pw.println("No applications!");
20652                    pw.println();
20653                } else {
20654                    final String prefix = "  ";
20655                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20656                    if (allPackageSettings.size() == 0) {
20657                        pw.println("No domain preferred apps!");
20658                        pw.println();
20659                    } else {
20660                        pw.println("App verification status:");
20661                        pw.println();
20662                        count = 0;
20663                        for (PackageSetting ps : allPackageSettings) {
20664                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20665                            if (ivi == null || ivi.getPackageName() == null) continue;
20666                            pw.println(prefix + "Package: " + ivi.getPackageName());
20667                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20668                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20669                            pw.println();
20670                            count++;
20671                        }
20672                        if (count == 0) {
20673                            pw.println(prefix + "No app verification established.");
20674                            pw.println();
20675                        }
20676                        for (int userId : sUserManager.getUserIds()) {
20677                            pw.println("App linkages for user " + userId + ":");
20678                            pw.println();
20679                            count = 0;
20680                            for (PackageSetting ps : allPackageSettings) {
20681                                final long status = ps.getDomainVerificationStatusForUser(userId);
20682                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20683                                        && !DEBUG_DOMAIN_VERIFICATION) {
20684                                    continue;
20685                                }
20686                                pw.println(prefix + "Package: " + ps.name);
20687                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20688                                String statusStr = IntentFilterVerificationInfo.
20689                                        getStatusStringFromValue(status);
20690                                pw.println(prefix + "Status:  " + statusStr);
20691                                pw.println();
20692                                count++;
20693                            }
20694                            if (count == 0) {
20695                                pw.println(prefix + "No configured app linkages.");
20696                                pw.println();
20697                            }
20698                        }
20699                    }
20700                }
20701            }
20702
20703            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20704                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20705                if (packageName == null && permissionNames == null) {
20706                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20707                        if (iperm == 0) {
20708                            if (dumpState.onTitlePrinted())
20709                                pw.println();
20710                            pw.println("AppOp Permissions:");
20711                        }
20712                        pw.print("  AppOp Permission ");
20713                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20714                        pw.println(":");
20715                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20716                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20717                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20718                        }
20719                    }
20720                }
20721            }
20722
20723            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20724                boolean printedSomething = false;
20725                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20726                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20727                        continue;
20728                    }
20729                    if (!printedSomething) {
20730                        if (dumpState.onTitlePrinted())
20731                            pw.println();
20732                        pw.println("Registered ContentProviders:");
20733                        printedSomething = true;
20734                    }
20735                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20736                    pw.print("    "); pw.println(p.toString());
20737                }
20738                printedSomething = false;
20739                for (Map.Entry<String, PackageParser.Provider> entry :
20740                        mProvidersByAuthority.entrySet()) {
20741                    PackageParser.Provider p = entry.getValue();
20742                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20743                        continue;
20744                    }
20745                    if (!printedSomething) {
20746                        if (dumpState.onTitlePrinted())
20747                            pw.println();
20748                        pw.println("ContentProvider Authorities:");
20749                        printedSomething = true;
20750                    }
20751                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20752                    pw.print("    "); pw.println(p.toString());
20753                    if (p.info != null && p.info.applicationInfo != null) {
20754                        final String appInfo = p.info.applicationInfo.toString();
20755                        pw.print("      applicationInfo="); pw.println(appInfo);
20756                    }
20757                }
20758            }
20759
20760            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20761                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20762            }
20763
20764            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20765                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20766            }
20767
20768            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20769                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20770            }
20771
20772            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20773                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20774            }
20775
20776            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20777                // XXX should handle packageName != null by dumping only install data that
20778                // the given package is involved with.
20779                if (dumpState.onTitlePrinted()) pw.println();
20780                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20781            }
20782
20783            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20784                // XXX should handle packageName != null by dumping only install data that
20785                // the given package is involved with.
20786                if (dumpState.onTitlePrinted()) pw.println();
20787
20788                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20789                ipw.println();
20790                ipw.println("Frozen packages:");
20791                ipw.increaseIndent();
20792                if (mFrozenPackages.size() == 0) {
20793                    ipw.println("(none)");
20794                } else {
20795                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20796                        ipw.println(mFrozenPackages.valueAt(i));
20797                    }
20798                }
20799                ipw.decreaseIndent();
20800            }
20801
20802            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20803                if (dumpState.onTitlePrinted()) pw.println();
20804                dumpDexoptStateLPr(pw, packageName);
20805            }
20806
20807            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20808                if (dumpState.onTitlePrinted()) pw.println();
20809                dumpCompilerStatsLPr(pw, packageName);
20810            }
20811
20812            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20813                if (dumpState.onTitlePrinted()) pw.println();
20814                mSettings.dumpReadMessagesLPr(pw, dumpState);
20815
20816                pw.println();
20817                pw.println("Package warning messages:");
20818                BufferedReader in = null;
20819                String line = null;
20820                try {
20821                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20822                    while ((line = in.readLine()) != null) {
20823                        if (line.contains("ignored: updated version")) continue;
20824                        pw.println(line);
20825                    }
20826                } catch (IOException ignored) {
20827                } finally {
20828                    IoUtils.closeQuietly(in);
20829                }
20830            }
20831
20832            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20833                BufferedReader in = null;
20834                String line = null;
20835                try {
20836                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20837                    while ((line = in.readLine()) != null) {
20838                        if (line.contains("ignored: updated version")) continue;
20839                        pw.print("msg,");
20840                        pw.println(line);
20841                    }
20842                } catch (IOException ignored) {
20843                } finally {
20844                    IoUtils.closeQuietly(in);
20845                }
20846            }
20847        }
20848    }
20849
20850    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20851        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20852        ipw.println();
20853        ipw.println("Dexopt state:");
20854        ipw.increaseIndent();
20855        Collection<PackageParser.Package> packages = null;
20856        if (packageName != null) {
20857            PackageParser.Package targetPackage = mPackages.get(packageName);
20858            if (targetPackage != null) {
20859                packages = Collections.singletonList(targetPackage);
20860            } else {
20861                ipw.println("Unable to find package: " + packageName);
20862                return;
20863            }
20864        } else {
20865            packages = mPackages.values();
20866        }
20867
20868        for (PackageParser.Package pkg : packages) {
20869            ipw.println("[" + pkg.packageName + "]");
20870            ipw.increaseIndent();
20871            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20872            ipw.decreaseIndent();
20873        }
20874    }
20875
20876    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20877        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20878        ipw.println();
20879        ipw.println("Compiler stats:");
20880        ipw.increaseIndent();
20881        Collection<PackageParser.Package> packages = null;
20882        if (packageName != null) {
20883            PackageParser.Package targetPackage = mPackages.get(packageName);
20884            if (targetPackage != null) {
20885                packages = Collections.singletonList(targetPackage);
20886            } else {
20887                ipw.println("Unable to find package: " + packageName);
20888                return;
20889            }
20890        } else {
20891            packages = mPackages.values();
20892        }
20893
20894        for (PackageParser.Package pkg : packages) {
20895            ipw.println("[" + pkg.packageName + "]");
20896            ipw.increaseIndent();
20897
20898            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20899            if (stats == null) {
20900                ipw.println("(No recorded stats)");
20901            } else {
20902                stats.dump(ipw);
20903            }
20904            ipw.decreaseIndent();
20905        }
20906    }
20907
20908    private String dumpDomainString(String packageName) {
20909        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20910                .getList();
20911        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20912
20913        ArraySet<String> result = new ArraySet<>();
20914        if (iviList.size() > 0) {
20915            for (IntentFilterVerificationInfo ivi : iviList) {
20916                for (String host : ivi.getDomains()) {
20917                    result.add(host);
20918                }
20919            }
20920        }
20921        if (filters != null && filters.size() > 0) {
20922            for (IntentFilter filter : filters) {
20923                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20924                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20925                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20926                    result.addAll(filter.getHostsList());
20927                }
20928            }
20929        }
20930
20931        StringBuilder sb = new StringBuilder(result.size() * 16);
20932        for (String domain : result) {
20933            if (sb.length() > 0) sb.append(" ");
20934            sb.append(domain);
20935        }
20936        return sb.toString();
20937    }
20938
20939    // ------- apps on sdcard specific code -------
20940    static final boolean DEBUG_SD_INSTALL = false;
20941
20942    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20943
20944    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20945
20946    private boolean mMediaMounted = false;
20947
20948    static String getEncryptKey() {
20949        try {
20950            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20951                    SD_ENCRYPTION_KEYSTORE_NAME);
20952            if (sdEncKey == null) {
20953                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20954                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20955                if (sdEncKey == null) {
20956                    Slog.e(TAG, "Failed to create encryption keys");
20957                    return null;
20958                }
20959            }
20960            return sdEncKey;
20961        } catch (NoSuchAlgorithmException nsae) {
20962            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20963            return null;
20964        } catch (IOException ioe) {
20965            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20966            return null;
20967        }
20968    }
20969
20970    /*
20971     * Update media status on PackageManager.
20972     */
20973    @Override
20974    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20975        int callingUid = Binder.getCallingUid();
20976        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20977            throw new SecurityException("Media status can only be updated by the system");
20978        }
20979        // reader; this apparently protects mMediaMounted, but should probably
20980        // be a different lock in that case.
20981        synchronized (mPackages) {
20982            Log.i(TAG, "Updating external media status from "
20983                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20984                    + (mediaStatus ? "mounted" : "unmounted"));
20985            if (DEBUG_SD_INSTALL)
20986                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20987                        + ", mMediaMounted=" + mMediaMounted);
20988            if (mediaStatus == mMediaMounted) {
20989                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20990                        : 0, -1);
20991                mHandler.sendMessage(msg);
20992                return;
20993            }
20994            mMediaMounted = mediaStatus;
20995        }
20996        // Queue up an async operation since the package installation may take a
20997        // little while.
20998        mHandler.post(new Runnable() {
20999            public void run() {
21000                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21001            }
21002        });
21003    }
21004
21005    /**
21006     * Called by StorageManagerService when the initial ASECs to scan are available.
21007     * Should block until all the ASEC containers are finished being scanned.
21008     */
21009    public void scanAvailableAsecs() {
21010        updateExternalMediaStatusInner(true, false, false);
21011    }
21012
21013    /*
21014     * Collect information of applications on external media, map them against
21015     * existing containers and update information based on current mount status.
21016     * Please note that we always have to report status if reportStatus has been
21017     * set to true especially when unloading packages.
21018     */
21019    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21020            boolean externalStorage) {
21021        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21022        int[] uidArr = EmptyArray.INT;
21023
21024        final String[] list = PackageHelper.getSecureContainerList();
21025        if (ArrayUtils.isEmpty(list)) {
21026            Log.i(TAG, "No secure containers found");
21027        } else {
21028            // Process list of secure containers and categorize them
21029            // as active or stale based on their package internal state.
21030
21031            // reader
21032            synchronized (mPackages) {
21033                for (String cid : list) {
21034                    // Leave stages untouched for now; installer service owns them
21035                    if (PackageInstallerService.isStageName(cid)) continue;
21036
21037                    if (DEBUG_SD_INSTALL)
21038                        Log.i(TAG, "Processing container " + cid);
21039                    String pkgName = getAsecPackageName(cid);
21040                    if (pkgName == null) {
21041                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21042                        continue;
21043                    }
21044                    if (DEBUG_SD_INSTALL)
21045                        Log.i(TAG, "Looking for pkg : " + pkgName);
21046
21047                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21048                    if (ps == null) {
21049                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21050                        continue;
21051                    }
21052
21053                    /*
21054                     * Skip packages that are not external if we're unmounting
21055                     * external storage.
21056                     */
21057                    if (externalStorage && !isMounted && !isExternal(ps)) {
21058                        continue;
21059                    }
21060
21061                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21062                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21063                    // The package status is changed only if the code path
21064                    // matches between settings and the container id.
21065                    if (ps.codePathString != null
21066                            && ps.codePathString.startsWith(args.getCodePath())) {
21067                        if (DEBUG_SD_INSTALL) {
21068                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21069                                    + " at code path: " + ps.codePathString);
21070                        }
21071
21072                        // We do have a valid package installed on sdcard
21073                        processCids.put(args, ps.codePathString);
21074                        final int uid = ps.appId;
21075                        if (uid != -1) {
21076                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21077                        }
21078                    } else {
21079                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21080                                + ps.codePathString);
21081                    }
21082                }
21083            }
21084
21085            Arrays.sort(uidArr);
21086        }
21087
21088        // Process packages with valid entries.
21089        if (isMounted) {
21090            if (DEBUG_SD_INSTALL)
21091                Log.i(TAG, "Loading packages");
21092            loadMediaPackages(processCids, uidArr, externalStorage);
21093            startCleaningPackages();
21094            mInstallerService.onSecureContainersAvailable();
21095        } else {
21096            if (DEBUG_SD_INSTALL)
21097                Log.i(TAG, "Unloading packages");
21098            unloadMediaPackages(processCids, uidArr, reportStatus);
21099        }
21100    }
21101
21102    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21103            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21104        final int size = infos.size();
21105        final String[] packageNames = new String[size];
21106        final int[] packageUids = new int[size];
21107        for (int i = 0; i < size; i++) {
21108            final ApplicationInfo info = infos.get(i);
21109            packageNames[i] = info.packageName;
21110            packageUids[i] = info.uid;
21111        }
21112        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21113                finishedReceiver);
21114    }
21115
21116    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21117            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21118        sendResourcesChangedBroadcast(mediaStatus, replacing,
21119                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21120    }
21121
21122    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21123            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21124        int size = pkgList.length;
21125        if (size > 0) {
21126            // Send broadcasts here
21127            Bundle extras = new Bundle();
21128            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21129            if (uidArr != null) {
21130                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21131            }
21132            if (replacing) {
21133                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21134            }
21135            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21136                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21137            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21138        }
21139    }
21140
21141   /*
21142     * Look at potentially valid container ids from processCids If package
21143     * information doesn't match the one on record or package scanning fails,
21144     * the cid is added to list of removeCids. We currently don't delete stale
21145     * containers.
21146     */
21147    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21148            boolean externalStorage) {
21149        ArrayList<String> pkgList = new ArrayList<String>();
21150        Set<AsecInstallArgs> keys = processCids.keySet();
21151
21152        for (AsecInstallArgs args : keys) {
21153            String codePath = processCids.get(args);
21154            if (DEBUG_SD_INSTALL)
21155                Log.i(TAG, "Loading container : " + args.cid);
21156            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21157            try {
21158                // Make sure there are no container errors first.
21159                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21160                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21161                            + " when installing from sdcard");
21162                    continue;
21163                }
21164                // Check code path here.
21165                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21166                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21167                            + " does not match one in settings " + codePath);
21168                    continue;
21169                }
21170                // Parse package
21171                int parseFlags = mDefParseFlags;
21172                if (args.isExternalAsec()) {
21173                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21174                }
21175                if (args.isFwdLocked()) {
21176                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21177                }
21178
21179                synchronized (mInstallLock) {
21180                    PackageParser.Package pkg = null;
21181                    try {
21182                        // Sadly we don't know the package name yet to freeze it
21183                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21184                                SCAN_IGNORE_FROZEN, 0, null);
21185                    } catch (PackageManagerException e) {
21186                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21187                    }
21188                    // Scan the package
21189                    if (pkg != null) {
21190                        /*
21191                         * TODO why is the lock being held? doPostInstall is
21192                         * called in other places without the lock. This needs
21193                         * to be straightened out.
21194                         */
21195                        // writer
21196                        synchronized (mPackages) {
21197                            retCode = PackageManager.INSTALL_SUCCEEDED;
21198                            pkgList.add(pkg.packageName);
21199                            // Post process args
21200                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21201                                    pkg.applicationInfo.uid);
21202                        }
21203                    } else {
21204                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21205                    }
21206                }
21207
21208            } finally {
21209                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21210                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21211                }
21212            }
21213        }
21214        // writer
21215        synchronized (mPackages) {
21216            // If the platform SDK has changed since the last time we booted,
21217            // we need to re-grant app permission to catch any new ones that
21218            // appear. This is really a hack, and means that apps can in some
21219            // cases get permissions that the user didn't initially explicitly
21220            // allow... it would be nice to have some better way to handle
21221            // this situation.
21222            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21223                    : mSettings.getInternalVersion();
21224            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21225                    : StorageManager.UUID_PRIVATE_INTERNAL;
21226
21227            int updateFlags = UPDATE_PERMISSIONS_ALL;
21228            if (ver.sdkVersion != mSdkVersion) {
21229                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21230                        + mSdkVersion + "; regranting permissions for external");
21231                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21232            }
21233            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21234
21235            // Yay, everything is now upgraded
21236            ver.forceCurrent();
21237
21238            // can downgrade to reader
21239            // Persist settings
21240            mSettings.writeLPr();
21241        }
21242        // Send a broadcast to let everyone know we are done processing
21243        if (pkgList.size() > 0) {
21244            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21245        }
21246    }
21247
21248   /*
21249     * Utility method to unload a list of specified containers
21250     */
21251    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21252        // Just unmount all valid containers.
21253        for (AsecInstallArgs arg : cidArgs) {
21254            synchronized (mInstallLock) {
21255                arg.doPostDeleteLI(false);
21256           }
21257       }
21258   }
21259
21260    /*
21261     * Unload packages mounted on external media. This involves deleting package
21262     * data from internal structures, sending broadcasts about disabled packages,
21263     * gc'ing to free up references, unmounting all secure containers
21264     * corresponding to packages on external media, and posting a
21265     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21266     * that we always have to post this message if status has been requested no
21267     * matter what.
21268     */
21269    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21270            final boolean reportStatus) {
21271        if (DEBUG_SD_INSTALL)
21272            Log.i(TAG, "unloading media packages");
21273        ArrayList<String> pkgList = new ArrayList<String>();
21274        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21275        final Set<AsecInstallArgs> keys = processCids.keySet();
21276        for (AsecInstallArgs args : keys) {
21277            String pkgName = args.getPackageName();
21278            if (DEBUG_SD_INSTALL)
21279                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21280            // Delete package internally
21281            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21282            synchronized (mInstallLock) {
21283                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21284                final boolean res;
21285                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21286                        "unloadMediaPackages")) {
21287                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21288                            null);
21289                }
21290                if (res) {
21291                    pkgList.add(pkgName);
21292                } else {
21293                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21294                    failedList.add(args);
21295                }
21296            }
21297        }
21298
21299        // reader
21300        synchronized (mPackages) {
21301            // We didn't update the settings after removing each package;
21302            // write them now for all packages.
21303            mSettings.writeLPr();
21304        }
21305
21306        // We have to absolutely send UPDATED_MEDIA_STATUS only
21307        // after confirming that all the receivers processed the ordered
21308        // broadcast when packages get disabled, force a gc to clean things up.
21309        // and unload all the containers.
21310        if (pkgList.size() > 0) {
21311            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21312                    new IIntentReceiver.Stub() {
21313                public void performReceive(Intent intent, int resultCode, String data,
21314                        Bundle extras, boolean ordered, boolean sticky,
21315                        int sendingUser) throws RemoteException {
21316                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21317                            reportStatus ? 1 : 0, 1, keys);
21318                    mHandler.sendMessage(msg);
21319                }
21320            });
21321        } else {
21322            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21323                    keys);
21324            mHandler.sendMessage(msg);
21325        }
21326    }
21327
21328    private void loadPrivatePackages(final VolumeInfo vol) {
21329        mHandler.post(new Runnable() {
21330            @Override
21331            public void run() {
21332                loadPrivatePackagesInner(vol);
21333            }
21334        });
21335    }
21336
21337    private void loadPrivatePackagesInner(VolumeInfo vol) {
21338        final String volumeUuid = vol.fsUuid;
21339        if (TextUtils.isEmpty(volumeUuid)) {
21340            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21341            return;
21342        }
21343
21344        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21345        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21346        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21347
21348        final VersionInfo ver;
21349        final List<PackageSetting> packages;
21350        synchronized (mPackages) {
21351            ver = mSettings.findOrCreateVersion(volumeUuid);
21352            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21353        }
21354
21355        for (PackageSetting ps : packages) {
21356            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21357            synchronized (mInstallLock) {
21358                final PackageParser.Package pkg;
21359                try {
21360                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21361                    loaded.add(pkg.applicationInfo);
21362
21363                } catch (PackageManagerException e) {
21364                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21365                }
21366
21367                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21368                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21369                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21370                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21371                }
21372            }
21373        }
21374
21375        // Reconcile app data for all started/unlocked users
21376        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21377        final UserManager um = mContext.getSystemService(UserManager.class);
21378        UserManagerInternal umInternal = getUserManagerInternal();
21379        for (UserInfo user : um.getUsers()) {
21380            final int flags;
21381            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21382                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21383            } else if (umInternal.isUserRunning(user.id)) {
21384                flags = StorageManager.FLAG_STORAGE_DE;
21385            } else {
21386                continue;
21387            }
21388
21389            try {
21390                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21391                synchronized (mInstallLock) {
21392                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21393                }
21394            } catch (IllegalStateException e) {
21395                // Device was probably ejected, and we'll process that event momentarily
21396                Slog.w(TAG, "Failed to prepare storage: " + e);
21397            }
21398        }
21399
21400        synchronized (mPackages) {
21401            int updateFlags = UPDATE_PERMISSIONS_ALL;
21402            if (ver.sdkVersion != mSdkVersion) {
21403                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21404                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21405                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21406            }
21407            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21408
21409            // Yay, everything is now upgraded
21410            ver.forceCurrent();
21411
21412            mSettings.writeLPr();
21413        }
21414
21415        for (PackageFreezer freezer : freezers) {
21416            freezer.close();
21417        }
21418
21419        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21420        sendResourcesChangedBroadcast(true, false, loaded, null);
21421    }
21422
21423    private void unloadPrivatePackages(final VolumeInfo vol) {
21424        mHandler.post(new Runnable() {
21425            @Override
21426            public void run() {
21427                unloadPrivatePackagesInner(vol);
21428            }
21429        });
21430    }
21431
21432    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21433        final String volumeUuid = vol.fsUuid;
21434        if (TextUtils.isEmpty(volumeUuid)) {
21435            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21436            return;
21437        }
21438
21439        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21440        synchronized (mInstallLock) {
21441        synchronized (mPackages) {
21442            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21443            for (PackageSetting ps : packages) {
21444                if (ps.pkg == null) continue;
21445
21446                final ApplicationInfo info = ps.pkg.applicationInfo;
21447                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21448                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21449
21450                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21451                        "unloadPrivatePackagesInner")) {
21452                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21453                            false, null)) {
21454                        unloaded.add(info);
21455                    } else {
21456                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21457                    }
21458                }
21459
21460                // Try very hard to release any references to this package
21461                // so we don't risk the system server being killed due to
21462                // open FDs
21463                AttributeCache.instance().removePackage(ps.name);
21464            }
21465
21466            mSettings.writeLPr();
21467        }
21468        }
21469
21470        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21471        sendResourcesChangedBroadcast(false, false, unloaded, null);
21472
21473        // Try very hard to release any references to this path so we don't risk
21474        // the system server being killed due to open FDs
21475        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21476
21477        for (int i = 0; i < 3; i++) {
21478            System.gc();
21479            System.runFinalization();
21480        }
21481    }
21482
21483    private void assertPackageKnown(String volumeUuid, String packageName)
21484            throws PackageManagerException {
21485        synchronized (mPackages) {
21486            // Normalize package name to handle renamed packages
21487            packageName = normalizePackageNameLPr(packageName);
21488
21489            final PackageSetting ps = mSettings.mPackages.get(packageName);
21490            if (ps == null) {
21491                throw new PackageManagerException("Package " + packageName + " is unknown");
21492            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21493                throw new PackageManagerException(
21494                        "Package " + packageName + " found on unknown volume " + volumeUuid
21495                                + "; expected volume " + ps.volumeUuid);
21496            }
21497        }
21498    }
21499
21500    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21501            throws PackageManagerException {
21502        synchronized (mPackages) {
21503            // Normalize package name to handle renamed packages
21504            packageName = normalizePackageNameLPr(packageName);
21505
21506            final PackageSetting ps = mSettings.mPackages.get(packageName);
21507            if (ps == null) {
21508                throw new PackageManagerException("Package " + packageName + " is unknown");
21509            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21510                throw new PackageManagerException(
21511                        "Package " + packageName + " found on unknown volume " + volumeUuid
21512                                + "; expected volume " + ps.volumeUuid);
21513            } else if (!ps.getInstalled(userId)) {
21514                throw new PackageManagerException(
21515                        "Package " + packageName + " not installed for user " + userId);
21516            }
21517        }
21518    }
21519
21520    private List<String> collectAbsoluteCodePaths() {
21521        synchronized (mPackages) {
21522            List<String> codePaths = new ArrayList<>();
21523            final int packageCount = mSettings.mPackages.size();
21524            for (int i = 0; i < packageCount; i++) {
21525                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21526                codePaths.add(ps.codePath.getAbsolutePath());
21527            }
21528            return codePaths;
21529        }
21530    }
21531
21532    /**
21533     * Examine all apps present on given mounted volume, and destroy apps that
21534     * aren't expected, either due to uninstallation or reinstallation on
21535     * another volume.
21536     */
21537    private void reconcileApps(String volumeUuid) {
21538        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21539        List<File> filesToDelete = null;
21540
21541        final File[] files = FileUtils.listFilesOrEmpty(
21542                Environment.getDataAppDirectory(volumeUuid));
21543        for (File file : files) {
21544            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21545                    && !PackageInstallerService.isStageName(file.getName());
21546            if (!isPackage) {
21547                // Ignore entries which are not packages
21548                continue;
21549            }
21550
21551            String absolutePath = file.getAbsolutePath();
21552
21553            boolean pathValid = false;
21554            final int absoluteCodePathCount = absoluteCodePaths.size();
21555            for (int i = 0; i < absoluteCodePathCount; i++) {
21556                String absoluteCodePath = absoluteCodePaths.get(i);
21557                if (absolutePath.startsWith(absoluteCodePath)) {
21558                    pathValid = true;
21559                    break;
21560                }
21561            }
21562
21563            if (!pathValid) {
21564                if (filesToDelete == null) {
21565                    filesToDelete = new ArrayList<>();
21566                }
21567                filesToDelete.add(file);
21568            }
21569        }
21570
21571        if (filesToDelete != null) {
21572            final int fileToDeleteCount = filesToDelete.size();
21573            for (int i = 0; i < fileToDeleteCount; i++) {
21574                File fileToDelete = filesToDelete.get(i);
21575                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21576                synchronized (mInstallLock) {
21577                    removeCodePathLI(fileToDelete);
21578                }
21579            }
21580        }
21581    }
21582
21583    /**
21584     * Reconcile all app data for the given user.
21585     * <p>
21586     * Verifies that directories exist and that ownership and labeling is
21587     * correct for all installed apps on all mounted volumes.
21588     */
21589    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21590        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21591        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21592            final String volumeUuid = vol.getFsUuid();
21593            synchronized (mInstallLock) {
21594                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21595            }
21596        }
21597    }
21598
21599    /**
21600     * Reconcile all app data on given mounted volume.
21601     * <p>
21602     * Destroys app data that isn't expected, either due to uninstallation or
21603     * reinstallation on another volume.
21604     * <p>
21605     * Verifies that directories exist and that ownership and labeling is
21606     * correct for all installed apps.
21607     */
21608    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21609            boolean migrateAppData) {
21610        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21611                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21612
21613        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21614        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21615
21616        // First look for stale data that doesn't belong, and check if things
21617        // have changed since we did our last restorecon
21618        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21619            if (StorageManager.isFileEncryptedNativeOrEmulated()
21620                    && !StorageManager.isUserKeyUnlocked(userId)) {
21621                throw new RuntimeException(
21622                        "Yikes, someone asked us to reconcile CE storage while " + userId
21623                                + " was still locked; this would have caused massive data loss!");
21624            }
21625
21626            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21627            for (File file : files) {
21628                final String packageName = file.getName();
21629                try {
21630                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21631                } catch (PackageManagerException e) {
21632                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21633                    try {
21634                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21635                                StorageManager.FLAG_STORAGE_CE, 0);
21636                    } catch (InstallerException e2) {
21637                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21638                    }
21639                }
21640            }
21641        }
21642        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21643            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21644            for (File file : files) {
21645                final String packageName = file.getName();
21646                try {
21647                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21648                } catch (PackageManagerException e) {
21649                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21650                    try {
21651                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21652                                StorageManager.FLAG_STORAGE_DE, 0);
21653                    } catch (InstallerException e2) {
21654                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21655                    }
21656                }
21657            }
21658        }
21659
21660        // Ensure that data directories are ready to roll for all packages
21661        // installed for this volume and user
21662        final List<PackageSetting> packages;
21663        synchronized (mPackages) {
21664            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21665        }
21666        int preparedCount = 0;
21667        for (PackageSetting ps : packages) {
21668            final String packageName = ps.name;
21669            if (ps.pkg == null) {
21670                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21671                // TODO: might be due to legacy ASEC apps; we should circle back
21672                // and reconcile again once they're scanned
21673                continue;
21674            }
21675
21676            if (ps.getInstalled(userId)) {
21677                prepareAppDataLIF(ps.pkg, userId, flags);
21678
21679                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21680                    // We may have just shuffled around app data directories, so
21681                    // prepare them one more time
21682                    prepareAppDataLIF(ps.pkg, userId, flags);
21683                }
21684
21685                preparedCount++;
21686            }
21687        }
21688
21689        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21690    }
21691
21692    /**
21693     * Prepare app data for the given app just after it was installed or
21694     * upgraded. This method carefully only touches users that it's installed
21695     * for, and it forces a restorecon to handle any seinfo changes.
21696     * <p>
21697     * Verifies that directories exist and that ownership and labeling is
21698     * correct for all installed apps. If there is an ownership mismatch, it
21699     * will try recovering system apps by wiping data; third-party app data is
21700     * left intact.
21701     * <p>
21702     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21703     */
21704    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21705        final PackageSetting ps;
21706        synchronized (mPackages) {
21707            ps = mSettings.mPackages.get(pkg.packageName);
21708            mSettings.writeKernelMappingLPr(ps);
21709        }
21710
21711        final UserManager um = mContext.getSystemService(UserManager.class);
21712        UserManagerInternal umInternal = getUserManagerInternal();
21713        for (UserInfo user : um.getUsers()) {
21714            final int flags;
21715            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21716                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21717            } else if (umInternal.isUserRunning(user.id)) {
21718                flags = StorageManager.FLAG_STORAGE_DE;
21719            } else {
21720                continue;
21721            }
21722
21723            if (ps.getInstalled(user.id)) {
21724                // TODO: when user data is locked, mark that we're still dirty
21725                prepareAppDataLIF(pkg, user.id, flags);
21726            }
21727        }
21728    }
21729
21730    /**
21731     * Prepare app data for the given app.
21732     * <p>
21733     * Verifies that directories exist and that ownership and labeling is
21734     * correct for all installed apps. If there is an ownership mismatch, this
21735     * will try recovering system apps by wiping data; third-party app data is
21736     * left intact.
21737     */
21738    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21739        if (pkg == null) {
21740            Slog.wtf(TAG, "Package was null!", new Throwable());
21741            return;
21742        }
21743        prepareAppDataLeafLIF(pkg, userId, flags);
21744        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21745        for (int i = 0; i < childCount; i++) {
21746            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21747        }
21748    }
21749
21750    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21751        if (DEBUG_APP_DATA) {
21752            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21753                    + Integer.toHexString(flags));
21754        }
21755
21756        final String volumeUuid = pkg.volumeUuid;
21757        final String packageName = pkg.packageName;
21758        final ApplicationInfo app = pkg.applicationInfo;
21759        final int appId = UserHandle.getAppId(app.uid);
21760
21761        Preconditions.checkNotNull(app.seInfo);
21762
21763        long ceDataInode = -1;
21764        try {
21765            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21766                    appId, app.seInfo, app.targetSdkVersion);
21767        } catch (InstallerException e) {
21768            if (app.isSystemApp()) {
21769                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21770                        + ", but trying to recover: " + e);
21771                destroyAppDataLeafLIF(pkg, userId, flags);
21772                try {
21773                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21774                            appId, app.seInfo, app.targetSdkVersion);
21775                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21776                } catch (InstallerException e2) {
21777                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21778                }
21779            } else {
21780                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21781            }
21782        }
21783
21784        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21785            // TODO: mark this structure as dirty so we persist it!
21786            synchronized (mPackages) {
21787                final PackageSetting ps = mSettings.mPackages.get(packageName);
21788                if (ps != null) {
21789                    ps.setCeDataInode(ceDataInode, userId);
21790                }
21791            }
21792        }
21793
21794        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21795    }
21796
21797    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21798        if (pkg == null) {
21799            Slog.wtf(TAG, "Package was null!", new Throwable());
21800            return;
21801        }
21802        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21803        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21804        for (int i = 0; i < childCount; i++) {
21805            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21806        }
21807    }
21808
21809    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21810        final String volumeUuid = pkg.volumeUuid;
21811        final String packageName = pkg.packageName;
21812        final ApplicationInfo app = pkg.applicationInfo;
21813
21814        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21815            // Create a native library symlink only if we have native libraries
21816            // and if the native libraries are 32 bit libraries. We do not provide
21817            // this symlink for 64 bit libraries.
21818            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21819                final String nativeLibPath = app.nativeLibraryDir;
21820                try {
21821                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21822                            nativeLibPath, userId);
21823                } catch (InstallerException e) {
21824                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21825                }
21826            }
21827        }
21828    }
21829
21830    /**
21831     * For system apps on non-FBE devices, this method migrates any existing
21832     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21833     * requested by the app.
21834     */
21835    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21836        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21837                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21838            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21839                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21840            try {
21841                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21842                        storageTarget);
21843            } catch (InstallerException e) {
21844                logCriticalInfo(Log.WARN,
21845                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21846            }
21847            return true;
21848        } else {
21849            return false;
21850        }
21851    }
21852
21853    public PackageFreezer freezePackage(String packageName, String killReason) {
21854        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21855    }
21856
21857    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21858        return new PackageFreezer(packageName, userId, killReason);
21859    }
21860
21861    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21862            String killReason) {
21863        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21864    }
21865
21866    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21867            String killReason) {
21868        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21869            return new PackageFreezer();
21870        } else {
21871            return freezePackage(packageName, userId, killReason);
21872        }
21873    }
21874
21875    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21876            String killReason) {
21877        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21878    }
21879
21880    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21881            String killReason) {
21882        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21883            return new PackageFreezer();
21884        } else {
21885            return freezePackage(packageName, userId, killReason);
21886        }
21887    }
21888
21889    /**
21890     * Class that freezes and kills the given package upon creation, and
21891     * unfreezes it upon closing. This is typically used when doing surgery on
21892     * app code/data to prevent the app from running while you're working.
21893     */
21894    private class PackageFreezer implements AutoCloseable {
21895        private final String mPackageName;
21896        private final PackageFreezer[] mChildren;
21897
21898        private final boolean mWeFroze;
21899
21900        private final AtomicBoolean mClosed = new AtomicBoolean();
21901        private final CloseGuard mCloseGuard = CloseGuard.get();
21902
21903        /**
21904         * Create and return a stub freezer that doesn't actually do anything,
21905         * typically used when someone requested
21906         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21907         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21908         */
21909        public PackageFreezer() {
21910            mPackageName = null;
21911            mChildren = null;
21912            mWeFroze = false;
21913            mCloseGuard.open("close");
21914        }
21915
21916        public PackageFreezer(String packageName, int userId, String killReason) {
21917            synchronized (mPackages) {
21918                mPackageName = packageName;
21919                mWeFroze = mFrozenPackages.add(mPackageName);
21920
21921                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21922                if (ps != null) {
21923                    killApplication(ps.name, ps.appId, userId, killReason);
21924                }
21925
21926                final PackageParser.Package p = mPackages.get(packageName);
21927                if (p != null && p.childPackages != null) {
21928                    final int N = p.childPackages.size();
21929                    mChildren = new PackageFreezer[N];
21930                    for (int i = 0; i < N; i++) {
21931                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21932                                userId, killReason);
21933                    }
21934                } else {
21935                    mChildren = null;
21936                }
21937            }
21938            mCloseGuard.open("close");
21939        }
21940
21941        @Override
21942        protected void finalize() throws Throwable {
21943            try {
21944                mCloseGuard.warnIfOpen();
21945                close();
21946            } finally {
21947                super.finalize();
21948            }
21949        }
21950
21951        @Override
21952        public void close() {
21953            mCloseGuard.close();
21954            if (mClosed.compareAndSet(false, true)) {
21955                synchronized (mPackages) {
21956                    if (mWeFroze) {
21957                        mFrozenPackages.remove(mPackageName);
21958                    }
21959
21960                    if (mChildren != null) {
21961                        for (PackageFreezer freezer : mChildren) {
21962                            freezer.close();
21963                        }
21964                    }
21965                }
21966            }
21967        }
21968    }
21969
21970    /**
21971     * Verify that given package is currently frozen.
21972     */
21973    private void checkPackageFrozen(String packageName) {
21974        synchronized (mPackages) {
21975            if (!mFrozenPackages.contains(packageName)) {
21976                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21977            }
21978        }
21979    }
21980
21981    @Override
21982    public int movePackage(final String packageName, final String volumeUuid) {
21983        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21984
21985        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21986        final int moveId = mNextMoveId.getAndIncrement();
21987        mHandler.post(new Runnable() {
21988            @Override
21989            public void run() {
21990                try {
21991                    movePackageInternal(packageName, volumeUuid, moveId, user);
21992                } catch (PackageManagerException e) {
21993                    Slog.w(TAG, "Failed to move " + packageName, e);
21994                    mMoveCallbacks.notifyStatusChanged(moveId,
21995                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21996                }
21997            }
21998        });
21999        return moveId;
22000    }
22001
22002    private void movePackageInternal(final String packageName, final String volumeUuid,
22003            final int moveId, UserHandle user) throws PackageManagerException {
22004        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22005        final PackageManager pm = mContext.getPackageManager();
22006
22007        final boolean currentAsec;
22008        final String currentVolumeUuid;
22009        final File codeFile;
22010        final String installerPackageName;
22011        final String packageAbiOverride;
22012        final int appId;
22013        final String seinfo;
22014        final String label;
22015        final int targetSdkVersion;
22016        final PackageFreezer freezer;
22017        final int[] installedUserIds;
22018
22019        // reader
22020        synchronized (mPackages) {
22021            final PackageParser.Package pkg = mPackages.get(packageName);
22022            final PackageSetting ps = mSettings.mPackages.get(packageName);
22023            if (pkg == null || ps == null) {
22024                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22025            }
22026
22027            if (pkg.applicationInfo.isSystemApp()) {
22028                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22029                        "Cannot move system application");
22030            }
22031
22032            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22033            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22034                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22035            if (isInternalStorage && !allow3rdPartyOnInternal) {
22036                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22037                        "3rd party apps are not allowed on internal storage");
22038            }
22039
22040            if (pkg.applicationInfo.isExternalAsec()) {
22041                currentAsec = true;
22042                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22043            } else if (pkg.applicationInfo.isForwardLocked()) {
22044                currentAsec = true;
22045                currentVolumeUuid = "forward_locked";
22046            } else {
22047                currentAsec = false;
22048                currentVolumeUuid = ps.volumeUuid;
22049
22050                final File probe = new File(pkg.codePath);
22051                final File probeOat = new File(probe, "oat");
22052                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22053                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22054                            "Move only supported for modern cluster style installs");
22055                }
22056            }
22057
22058            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22059                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22060                        "Package already moved to " + volumeUuid);
22061            }
22062            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22063                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22064                        "Device admin cannot be moved");
22065            }
22066
22067            if (mFrozenPackages.contains(packageName)) {
22068                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22069                        "Failed to move already frozen package");
22070            }
22071
22072            codeFile = new File(pkg.codePath);
22073            installerPackageName = ps.installerPackageName;
22074            packageAbiOverride = ps.cpuAbiOverrideString;
22075            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22076            seinfo = pkg.applicationInfo.seInfo;
22077            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22078            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22079            freezer = freezePackage(packageName, "movePackageInternal");
22080            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22081        }
22082
22083        final Bundle extras = new Bundle();
22084        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22085        extras.putString(Intent.EXTRA_TITLE, label);
22086        mMoveCallbacks.notifyCreated(moveId, extras);
22087
22088        int installFlags;
22089        final boolean moveCompleteApp;
22090        final File measurePath;
22091
22092        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22093            installFlags = INSTALL_INTERNAL;
22094            moveCompleteApp = !currentAsec;
22095            measurePath = Environment.getDataAppDirectory(volumeUuid);
22096        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22097            installFlags = INSTALL_EXTERNAL;
22098            moveCompleteApp = false;
22099            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22100        } else {
22101            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22102            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22103                    || !volume.isMountedWritable()) {
22104                freezer.close();
22105                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22106                        "Move location not mounted private volume");
22107            }
22108
22109            Preconditions.checkState(!currentAsec);
22110
22111            installFlags = INSTALL_INTERNAL;
22112            moveCompleteApp = true;
22113            measurePath = Environment.getDataAppDirectory(volumeUuid);
22114        }
22115
22116        final PackageStats stats = new PackageStats(null, -1);
22117        synchronized (mInstaller) {
22118            for (int userId : installedUserIds) {
22119                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22120                    freezer.close();
22121                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22122                            "Failed to measure package size");
22123                }
22124            }
22125        }
22126
22127        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22128                + stats.dataSize);
22129
22130        final long startFreeBytes = measurePath.getFreeSpace();
22131        final long sizeBytes;
22132        if (moveCompleteApp) {
22133            sizeBytes = stats.codeSize + stats.dataSize;
22134        } else {
22135            sizeBytes = stats.codeSize;
22136        }
22137
22138        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22139            freezer.close();
22140            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22141                    "Not enough free space to move");
22142        }
22143
22144        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22145
22146        final CountDownLatch installedLatch = new CountDownLatch(1);
22147        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22148            @Override
22149            public void onUserActionRequired(Intent intent) throws RemoteException {
22150                throw new IllegalStateException();
22151            }
22152
22153            @Override
22154            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22155                    Bundle extras) throws RemoteException {
22156                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22157                        + PackageManager.installStatusToString(returnCode, msg));
22158
22159                installedLatch.countDown();
22160                freezer.close();
22161
22162                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22163                switch (status) {
22164                    case PackageInstaller.STATUS_SUCCESS:
22165                        mMoveCallbacks.notifyStatusChanged(moveId,
22166                                PackageManager.MOVE_SUCCEEDED);
22167                        break;
22168                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22169                        mMoveCallbacks.notifyStatusChanged(moveId,
22170                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22171                        break;
22172                    default:
22173                        mMoveCallbacks.notifyStatusChanged(moveId,
22174                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22175                        break;
22176                }
22177            }
22178        };
22179
22180        final MoveInfo move;
22181        if (moveCompleteApp) {
22182            // Kick off a thread to report progress estimates
22183            new Thread() {
22184                @Override
22185                public void run() {
22186                    while (true) {
22187                        try {
22188                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22189                                break;
22190                            }
22191                        } catch (InterruptedException ignored) {
22192                        }
22193
22194                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22195                        final int progress = 10 + (int) MathUtils.constrain(
22196                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22197                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22198                    }
22199                }
22200            }.start();
22201
22202            final String dataAppName = codeFile.getName();
22203            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22204                    dataAppName, appId, seinfo, targetSdkVersion);
22205        } else {
22206            move = null;
22207        }
22208
22209        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22210
22211        final Message msg = mHandler.obtainMessage(INIT_COPY);
22212        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22213        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22214                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22215                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22216                PackageManager.INSTALL_REASON_UNKNOWN);
22217        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22218        msg.obj = params;
22219
22220        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22221                System.identityHashCode(msg.obj));
22222        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22223                System.identityHashCode(msg.obj));
22224
22225        mHandler.sendMessage(msg);
22226    }
22227
22228    @Override
22229    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22230        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22231
22232        final int realMoveId = mNextMoveId.getAndIncrement();
22233        final Bundle extras = new Bundle();
22234        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22235        mMoveCallbacks.notifyCreated(realMoveId, extras);
22236
22237        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22238            @Override
22239            public void onCreated(int moveId, Bundle extras) {
22240                // Ignored
22241            }
22242
22243            @Override
22244            public void onStatusChanged(int moveId, int status, long estMillis) {
22245                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22246            }
22247        };
22248
22249        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22250        storage.setPrimaryStorageUuid(volumeUuid, callback);
22251        return realMoveId;
22252    }
22253
22254    @Override
22255    public int getMoveStatus(int moveId) {
22256        mContext.enforceCallingOrSelfPermission(
22257                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22258        return mMoveCallbacks.mLastStatus.get(moveId);
22259    }
22260
22261    @Override
22262    public void registerMoveCallback(IPackageMoveObserver callback) {
22263        mContext.enforceCallingOrSelfPermission(
22264                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22265        mMoveCallbacks.register(callback);
22266    }
22267
22268    @Override
22269    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22270        mContext.enforceCallingOrSelfPermission(
22271                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22272        mMoveCallbacks.unregister(callback);
22273    }
22274
22275    @Override
22276    public boolean setInstallLocation(int loc) {
22277        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22278                null);
22279        if (getInstallLocation() == loc) {
22280            return true;
22281        }
22282        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22283                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22284            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22285                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22286            return true;
22287        }
22288        return false;
22289   }
22290
22291    @Override
22292    public int getInstallLocation() {
22293        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22294                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22295                PackageHelper.APP_INSTALL_AUTO);
22296    }
22297
22298    /** Called by UserManagerService */
22299    void cleanUpUser(UserManagerService userManager, int userHandle) {
22300        synchronized (mPackages) {
22301            mDirtyUsers.remove(userHandle);
22302            mUserNeedsBadging.delete(userHandle);
22303            mSettings.removeUserLPw(userHandle);
22304            mPendingBroadcasts.remove(userHandle);
22305            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22306            removeUnusedPackagesLPw(userManager, userHandle);
22307        }
22308    }
22309
22310    /**
22311     * We're removing userHandle and would like to remove any downloaded packages
22312     * that are no longer in use by any other user.
22313     * @param userHandle the user being removed
22314     */
22315    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22316        final boolean DEBUG_CLEAN_APKS = false;
22317        int [] users = userManager.getUserIds();
22318        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22319        while (psit.hasNext()) {
22320            PackageSetting ps = psit.next();
22321            if (ps.pkg == null) {
22322                continue;
22323            }
22324            final String packageName = ps.pkg.packageName;
22325            // Skip over if system app
22326            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22327                continue;
22328            }
22329            if (DEBUG_CLEAN_APKS) {
22330                Slog.i(TAG, "Checking package " + packageName);
22331            }
22332            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22333            if (keep) {
22334                if (DEBUG_CLEAN_APKS) {
22335                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22336                }
22337            } else {
22338                for (int i = 0; i < users.length; i++) {
22339                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22340                        keep = true;
22341                        if (DEBUG_CLEAN_APKS) {
22342                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22343                                    + users[i]);
22344                        }
22345                        break;
22346                    }
22347                }
22348            }
22349            if (!keep) {
22350                if (DEBUG_CLEAN_APKS) {
22351                    Slog.i(TAG, "  Removing package " + packageName);
22352                }
22353                mHandler.post(new Runnable() {
22354                    public void run() {
22355                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22356                                userHandle, 0);
22357                    } //end run
22358                });
22359            }
22360        }
22361    }
22362
22363    /** Called by UserManagerService */
22364    void createNewUser(int userId, String[] disallowedPackages) {
22365        synchronized (mInstallLock) {
22366            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22367        }
22368        synchronized (mPackages) {
22369            scheduleWritePackageRestrictionsLocked(userId);
22370            scheduleWritePackageListLocked(userId);
22371            applyFactoryDefaultBrowserLPw(userId);
22372            primeDomainVerificationsLPw(userId);
22373        }
22374    }
22375
22376    void onNewUserCreated(final int userId) {
22377        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22378        // If permission review for legacy apps is required, we represent
22379        // dagerous permissions for such apps as always granted runtime
22380        // permissions to keep per user flag state whether review is needed.
22381        // Hence, if a new user is added we have to propagate dangerous
22382        // permission grants for these legacy apps.
22383        if (mPermissionReviewRequired) {
22384            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22385                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22386        }
22387    }
22388
22389    @Override
22390    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22391        mContext.enforceCallingOrSelfPermission(
22392                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22393                "Only package verification agents can read the verifier device identity");
22394
22395        synchronized (mPackages) {
22396            return mSettings.getVerifierDeviceIdentityLPw();
22397        }
22398    }
22399
22400    @Override
22401    public void setPermissionEnforced(String permission, boolean enforced) {
22402        // TODO: Now that we no longer change GID for storage, this should to away.
22403        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22404                "setPermissionEnforced");
22405        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22406            synchronized (mPackages) {
22407                if (mSettings.mReadExternalStorageEnforced == null
22408                        || mSettings.mReadExternalStorageEnforced != enforced) {
22409                    mSettings.mReadExternalStorageEnforced = enforced;
22410                    mSettings.writeLPr();
22411                }
22412            }
22413            // kill any non-foreground processes so we restart them and
22414            // grant/revoke the GID.
22415            final IActivityManager am = ActivityManager.getService();
22416            if (am != null) {
22417                final long token = Binder.clearCallingIdentity();
22418                try {
22419                    am.killProcessesBelowForeground("setPermissionEnforcement");
22420                } catch (RemoteException e) {
22421                } finally {
22422                    Binder.restoreCallingIdentity(token);
22423                }
22424            }
22425        } else {
22426            throw new IllegalArgumentException("No selective enforcement for " + permission);
22427        }
22428    }
22429
22430    @Override
22431    @Deprecated
22432    public boolean isPermissionEnforced(String permission) {
22433        return true;
22434    }
22435
22436    @Override
22437    public boolean isStorageLow() {
22438        final long token = Binder.clearCallingIdentity();
22439        try {
22440            final DeviceStorageMonitorInternal
22441                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22442            if (dsm != null) {
22443                return dsm.isMemoryLow();
22444            } else {
22445                return false;
22446            }
22447        } finally {
22448            Binder.restoreCallingIdentity(token);
22449        }
22450    }
22451
22452    @Override
22453    public IPackageInstaller getPackageInstaller() {
22454        return mInstallerService;
22455    }
22456
22457    private boolean userNeedsBadging(int userId) {
22458        int index = mUserNeedsBadging.indexOfKey(userId);
22459        if (index < 0) {
22460            final UserInfo userInfo;
22461            final long token = Binder.clearCallingIdentity();
22462            try {
22463                userInfo = sUserManager.getUserInfo(userId);
22464            } finally {
22465                Binder.restoreCallingIdentity(token);
22466            }
22467            final boolean b;
22468            if (userInfo != null && userInfo.isManagedProfile()) {
22469                b = true;
22470            } else {
22471                b = false;
22472            }
22473            mUserNeedsBadging.put(userId, b);
22474            return b;
22475        }
22476        return mUserNeedsBadging.valueAt(index);
22477    }
22478
22479    @Override
22480    public KeySet getKeySetByAlias(String packageName, String alias) {
22481        if (packageName == null || alias == null) {
22482            return null;
22483        }
22484        synchronized(mPackages) {
22485            final PackageParser.Package pkg = mPackages.get(packageName);
22486            if (pkg == null) {
22487                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22488                throw new IllegalArgumentException("Unknown package: " + packageName);
22489            }
22490            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22491            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22492        }
22493    }
22494
22495    @Override
22496    public KeySet getSigningKeySet(String packageName) {
22497        if (packageName == null) {
22498            return null;
22499        }
22500        synchronized(mPackages) {
22501            final PackageParser.Package pkg = mPackages.get(packageName);
22502            if (pkg == null) {
22503                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22504                throw new IllegalArgumentException("Unknown package: " + packageName);
22505            }
22506            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22507                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22508                throw new SecurityException("May not access signing KeySet of other apps.");
22509            }
22510            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22511            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22512        }
22513    }
22514
22515    @Override
22516    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22517        if (packageName == null || ks == null) {
22518            return false;
22519        }
22520        synchronized(mPackages) {
22521            final PackageParser.Package pkg = mPackages.get(packageName);
22522            if (pkg == null) {
22523                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22524                throw new IllegalArgumentException("Unknown package: " + packageName);
22525            }
22526            IBinder ksh = ks.getToken();
22527            if (ksh instanceof KeySetHandle) {
22528                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22529                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22530            }
22531            return false;
22532        }
22533    }
22534
22535    @Override
22536    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22537        if (packageName == null || ks == null) {
22538            return false;
22539        }
22540        synchronized(mPackages) {
22541            final PackageParser.Package pkg = mPackages.get(packageName);
22542            if (pkg == null) {
22543                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22544                throw new IllegalArgumentException("Unknown package: " + packageName);
22545            }
22546            IBinder ksh = ks.getToken();
22547            if (ksh instanceof KeySetHandle) {
22548                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22549                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22550            }
22551            return false;
22552        }
22553    }
22554
22555    private void deletePackageIfUnusedLPr(final String packageName) {
22556        PackageSetting ps = mSettings.mPackages.get(packageName);
22557        if (ps == null) {
22558            return;
22559        }
22560        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22561            // TODO Implement atomic delete if package is unused
22562            // It is currently possible that the package will be deleted even if it is installed
22563            // after this method returns.
22564            mHandler.post(new Runnable() {
22565                public void run() {
22566                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22567                            0, PackageManager.DELETE_ALL_USERS);
22568                }
22569            });
22570        }
22571    }
22572
22573    /**
22574     * Check and throw if the given before/after packages would be considered a
22575     * downgrade.
22576     */
22577    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22578            throws PackageManagerException {
22579        if (after.versionCode < before.mVersionCode) {
22580            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22581                    "Update version code " + after.versionCode + " is older than current "
22582                    + before.mVersionCode);
22583        } else if (after.versionCode == before.mVersionCode) {
22584            if (after.baseRevisionCode < before.baseRevisionCode) {
22585                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22586                        "Update base revision code " + after.baseRevisionCode
22587                        + " is older than current " + before.baseRevisionCode);
22588            }
22589
22590            if (!ArrayUtils.isEmpty(after.splitNames)) {
22591                for (int i = 0; i < after.splitNames.length; i++) {
22592                    final String splitName = after.splitNames[i];
22593                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22594                    if (j != -1) {
22595                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22596                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22597                                    "Update split " + splitName + " revision code "
22598                                    + after.splitRevisionCodes[i] + " is older than current "
22599                                    + before.splitRevisionCodes[j]);
22600                        }
22601                    }
22602                }
22603            }
22604        }
22605    }
22606
22607    private static class MoveCallbacks extends Handler {
22608        private static final int MSG_CREATED = 1;
22609        private static final int MSG_STATUS_CHANGED = 2;
22610
22611        private final RemoteCallbackList<IPackageMoveObserver>
22612                mCallbacks = new RemoteCallbackList<>();
22613
22614        private final SparseIntArray mLastStatus = new SparseIntArray();
22615
22616        public MoveCallbacks(Looper looper) {
22617            super(looper);
22618        }
22619
22620        public void register(IPackageMoveObserver callback) {
22621            mCallbacks.register(callback);
22622        }
22623
22624        public void unregister(IPackageMoveObserver callback) {
22625            mCallbacks.unregister(callback);
22626        }
22627
22628        @Override
22629        public void handleMessage(Message msg) {
22630            final SomeArgs args = (SomeArgs) msg.obj;
22631            final int n = mCallbacks.beginBroadcast();
22632            for (int i = 0; i < n; i++) {
22633                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22634                try {
22635                    invokeCallback(callback, msg.what, args);
22636                } catch (RemoteException ignored) {
22637                }
22638            }
22639            mCallbacks.finishBroadcast();
22640            args.recycle();
22641        }
22642
22643        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22644                throws RemoteException {
22645            switch (what) {
22646                case MSG_CREATED: {
22647                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22648                    break;
22649                }
22650                case MSG_STATUS_CHANGED: {
22651                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22652                    break;
22653                }
22654            }
22655        }
22656
22657        private void notifyCreated(int moveId, Bundle extras) {
22658            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22659
22660            final SomeArgs args = SomeArgs.obtain();
22661            args.argi1 = moveId;
22662            args.arg2 = extras;
22663            obtainMessage(MSG_CREATED, args).sendToTarget();
22664        }
22665
22666        private void notifyStatusChanged(int moveId, int status) {
22667            notifyStatusChanged(moveId, status, -1);
22668        }
22669
22670        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22671            Slog.v(TAG, "Move " + moveId + " status " + status);
22672
22673            final SomeArgs args = SomeArgs.obtain();
22674            args.argi1 = moveId;
22675            args.argi2 = status;
22676            args.arg3 = estMillis;
22677            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22678
22679            synchronized (mLastStatus) {
22680                mLastStatus.put(moveId, status);
22681            }
22682        }
22683    }
22684
22685    private final static class OnPermissionChangeListeners extends Handler {
22686        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22687
22688        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22689                new RemoteCallbackList<>();
22690
22691        public OnPermissionChangeListeners(Looper looper) {
22692            super(looper);
22693        }
22694
22695        @Override
22696        public void handleMessage(Message msg) {
22697            switch (msg.what) {
22698                case MSG_ON_PERMISSIONS_CHANGED: {
22699                    final int uid = msg.arg1;
22700                    handleOnPermissionsChanged(uid);
22701                } break;
22702            }
22703        }
22704
22705        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22706            mPermissionListeners.register(listener);
22707
22708        }
22709
22710        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22711            mPermissionListeners.unregister(listener);
22712        }
22713
22714        public void onPermissionsChanged(int uid) {
22715            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22716                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22717            }
22718        }
22719
22720        private void handleOnPermissionsChanged(int uid) {
22721            final int count = mPermissionListeners.beginBroadcast();
22722            try {
22723                for (int i = 0; i < count; i++) {
22724                    IOnPermissionsChangeListener callback = mPermissionListeners
22725                            .getBroadcastItem(i);
22726                    try {
22727                        callback.onPermissionsChanged(uid);
22728                    } catch (RemoteException e) {
22729                        Log.e(TAG, "Permission listener is dead", e);
22730                    }
22731                }
22732            } finally {
22733                mPermissionListeners.finishBroadcast();
22734            }
22735        }
22736    }
22737
22738    private class PackageManagerInternalImpl extends PackageManagerInternal {
22739        @Override
22740        public void setLocationPackagesProvider(PackagesProvider provider) {
22741            synchronized (mPackages) {
22742                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22743            }
22744        }
22745
22746        @Override
22747        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22748            synchronized (mPackages) {
22749                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22750            }
22751        }
22752
22753        @Override
22754        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22755            synchronized (mPackages) {
22756                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22757            }
22758        }
22759
22760        @Override
22761        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22762            synchronized (mPackages) {
22763                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22764            }
22765        }
22766
22767        @Override
22768        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22769            synchronized (mPackages) {
22770                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22771            }
22772        }
22773
22774        @Override
22775        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22776            synchronized (mPackages) {
22777                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22778            }
22779        }
22780
22781        @Override
22782        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22783            synchronized (mPackages) {
22784                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22785                        packageName, userId);
22786            }
22787        }
22788
22789        @Override
22790        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22791            synchronized (mPackages) {
22792                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22793                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22794                        packageName, userId);
22795            }
22796        }
22797
22798        @Override
22799        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22800            synchronized (mPackages) {
22801                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22802                        packageName, userId);
22803            }
22804        }
22805
22806        @Override
22807        public void setKeepUninstalledPackages(final List<String> packageList) {
22808            Preconditions.checkNotNull(packageList);
22809            List<String> removedFromList = null;
22810            synchronized (mPackages) {
22811                if (mKeepUninstalledPackages != null) {
22812                    final int packagesCount = mKeepUninstalledPackages.size();
22813                    for (int i = 0; i < packagesCount; i++) {
22814                        String oldPackage = mKeepUninstalledPackages.get(i);
22815                        if (packageList != null && packageList.contains(oldPackage)) {
22816                            continue;
22817                        }
22818                        if (removedFromList == null) {
22819                            removedFromList = new ArrayList<>();
22820                        }
22821                        removedFromList.add(oldPackage);
22822                    }
22823                }
22824                mKeepUninstalledPackages = new ArrayList<>(packageList);
22825                if (removedFromList != null) {
22826                    final int removedCount = removedFromList.size();
22827                    for (int i = 0; i < removedCount; i++) {
22828                        deletePackageIfUnusedLPr(removedFromList.get(i));
22829                    }
22830                }
22831            }
22832        }
22833
22834        @Override
22835        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22836            synchronized (mPackages) {
22837                // If we do not support permission review, done.
22838                if (!mPermissionReviewRequired) {
22839                    return false;
22840                }
22841
22842                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22843                if (packageSetting == null) {
22844                    return false;
22845                }
22846
22847                // Permission review applies only to apps not supporting the new permission model.
22848                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22849                    return false;
22850                }
22851
22852                // Legacy apps have the permission and get user consent on launch.
22853                PermissionsState permissionsState = packageSetting.getPermissionsState();
22854                return permissionsState.isPermissionReviewRequired(userId);
22855            }
22856        }
22857
22858        @Override
22859        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22860            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22861        }
22862
22863        @Override
22864        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22865                int userId) {
22866            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22867        }
22868
22869        @Override
22870        public void setDeviceAndProfileOwnerPackages(
22871                int deviceOwnerUserId, String deviceOwnerPackage,
22872                SparseArray<String> profileOwnerPackages) {
22873            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22874                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22875        }
22876
22877        @Override
22878        public boolean isPackageDataProtected(int userId, String packageName) {
22879            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22880        }
22881
22882        @Override
22883        public boolean isPackageEphemeral(int userId, String packageName) {
22884            synchronized (mPackages) {
22885                final PackageSetting ps = mSettings.mPackages.get(packageName);
22886                return ps != null ? ps.getInstantApp(userId) : false;
22887            }
22888        }
22889
22890        @Override
22891        public boolean wasPackageEverLaunched(String packageName, int userId) {
22892            synchronized (mPackages) {
22893                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22894            }
22895        }
22896
22897        @Override
22898        public void grantRuntimePermission(String packageName, String name, int userId,
22899                boolean overridePolicy) {
22900            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22901                    overridePolicy);
22902        }
22903
22904        @Override
22905        public void revokeRuntimePermission(String packageName, String name, int userId,
22906                boolean overridePolicy) {
22907            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22908                    overridePolicy);
22909        }
22910
22911        @Override
22912        public String getNameForUid(int uid) {
22913            return PackageManagerService.this.getNameForUid(uid);
22914        }
22915
22916        @Override
22917        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22918                Intent origIntent, String resolvedType, Intent launchIntent,
22919                String callingPackage, int userId) {
22920            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22921                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22922        }
22923
22924        @Override
22925        public void grantEphemeralAccess(int userId, Intent intent,
22926                int targetAppId, int ephemeralAppId) {
22927            synchronized (mPackages) {
22928                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22929                        targetAppId, ephemeralAppId);
22930            }
22931        }
22932
22933        @Override
22934        public void pruneInstantApps() {
22935            synchronized (mPackages) {
22936                mInstantAppRegistry.pruneInstantAppsLPw();
22937            }
22938        }
22939
22940        @Override
22941        public String getSetupWizardPackageName() {
22942            return mSetupWizardPackage;
22943        }
22944
22945        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22946            if (policy != null) {
22947                mExternalSourcesPolicy = policy;
22948            }
22949        }
22950
22951        @Override
22952        public boolean isPackagePersistent(String packageName) {
22953            synchronized (mPackages) {
22954                PackageParser.Package pkg = mPackages.get(packageName);
22955                return pkg != null
22956                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22957                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22958                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22959                        : false;
22960            }
22961        }
22962
22963        @Override
22964        public List<PackageInfo> getOverlayPackages(int userId) {
22965            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22966            synchronized (mPackages) {
22967                for (PackageParser.Package p : mPackages.values()) {
22968                    if (p.mOverlayTarget != null) {
22969                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22970                        if (pkg != null) {
22971                            overlayPackages.add(pkg);
22972                        }
22973                    }
22974                }
22975            }
22976            return overlayPackages;
22977        }
22978
22979        @Override
22980        public List<String> getTargetPackageNames(int userId) {
22981            List<String> targetPackages = new ArrayList<>();
22982            synchronized (mPackages) {
22983                for (PackageParser.Package p : mPackages.values()) {
22984                    if (p.mOverlayTarget == null) {
22985                        targetPackages.add(p.packageName);
22986                    }
22987                }
22988            }
22989            return targetPackages;
22990        }
22991
22992
22993        @Override
22994        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
22995                List<String> overlayPackageNames) {
22996            // TODO: implement when we integrate OMS properly
22997            return false;
22998        }
22999    }
23000
23001    @Override
23002    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23003        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23004        synchronized (mPackages) {
23005            final long identity = Binder.clearCallingIdentity();
23006            try {
23007                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23008                        packageNames, userId);
23009            } finally {
23010                Binder.restoreCallingIdentity(identity);
23011            }
23012        }
23013    }
23014
23015    @Override
23016    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23017        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23018        synchronized (mPackages) {
23019            final long identity = Binder.clearCallingIdentity();
23020            try {
23021                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23022                        packageNames, userId);
23023            } finally {
23024                Binder.restoreCallingIdentity(identity);
23025            }
23026        }
23027    }
23028
23029    private static void enforceSystemOrPhoneCaller(String tag) {
23030        int callingUid = Binder.getCallingUid();
23031        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23032            throw new SecurityException(
23033                    "Cannot call " + tag + " from UID " + callingUid);
23034        }
23035    }
23036
23037    boolean isHistoricalPackageUsageAvailable() {
23038        return mPackageUsage.isHistoricalPackageUsageAvailable();
23039    }
23040
23041    /**
23042     * Return a <b>copy</b> of the collection of packages known to the package manager.
23043     * @return A copy of the values of mPackages.
23044     */
23045    Collection<PackageParser.Package> getPackages() {
23046        synchronized (mPackages) {
23047            return new ArrayList<>(mPackages.values());
23048        }
23049    }
23050
23051    /**
23052     * Logs process start information (including base APK hash) to the security log.
23053     * @hide
23054     */
23055    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23056            String apkFile, int pid) {
23057        if (!SecurityLog.isLoggingEnabled()) {
23058            return;
23059        }
23060        Bundle data = new Bundle();
23061        data.putLong("startTimestamp", System.currentTimeMillis());
23062        data.putString("processName", processName);
23063        data.putInt("uid", uid);
23064        data.putString("seinfo", seinfo);
23065        data.putString("apkFile", apkFile);
23066        data.putInt("pid", pid);
23067        Message msg = mProcessLoggingHandler.obtainMessage(
23068                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23069        msg.setData(data);
23070        mProcessLoggingHandler.sendMessage(msg);
23071    }
23072
23073    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23074        return mCompilerStats.getPackageStats(pkgName);
23075    }
23076
23077    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23078        return getOrCreateCompilerPackageStats(pkg.packageName);
23079    }
23080
23081    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23082        return mCompilerStats.getOrCreatePackageStats(pkgName);
23083    }
23084
23085    public void deleteCompilerPackageStats(String pkgName) {
23086        mCompilerStats.deletePackageStats(pkgName);
23087    }
23088
23089    @Override
23090    public int getInstallReason(String packageName, int userId) {
23091        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23092                true /* requireFullPermission */, false /* checkShell */,
23093                "get install reason");
23094        synchronized (mPackages) {
23095            final PackageSetting ps = mSettings.mPackages.get(packageName);
23096            if (ps != null) {
23097                return ps.getInstallReason(userId);
23098            }
23099        }
23100        return PackageManager.INSTALL_REASON_UNKNOWN;
23101    }
23102
23103    @Override
23104    public boolean canRequestPackageInstalls(String packageName, int userId) {
23105        int callingUid = Binder.getCallingUid();
23106        int uid = getPackageUid(packageName, 0, userId);
23107        if (callingUid != uid && callingUid != Process.ROOT_UID
23108                && callingUid != Process.SYSTEM_UID) {
23109            throw new SecurityException(
23110                    "Caller uid " + callingUid + " does not own package " + packageName);
23111        }
23112        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23113        if (info == null) {
23114            return false;
23115        }
23116        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23117            throw new UnsupportedOperationException(
23118                    "Operation only supported on apps targeting Android O or higher");
23119        }
23120        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23121        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23122        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23123            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23124        }
23125        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23126            return false;
23127        }
23128        if (mExternalSourcesPolicy != null) {
23129            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23130            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23131                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23132            }
23133        }
23134        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23135    }
23136}
23137