PackageManagerService.java revision e730ae877a24d44f5b3db096f08b0a2d7399aa2d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.BackgroundDexOptJobService;
264import com.android.server.DeviceIdleController;
265import com.android.server.EventLogTags;
266import com.android.server.FgThread;
267import com.android.server.IntentResolver;
268import com.android.server.LocalServices;
269import com.android.server.LockGuard;
270import com.android.server.ServiceThread;
271import com.android.server.SystemConfig;
272import com.android.server.SystemServerInitThreadPool;
273import com.android.server.Watchdog;
274import com.android.server.net.NetworkPolicyManagerInternal;
275import com.android.server.pm.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
300import java.io.FileNotFoundException;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
398    private static final boolean DISABLE_EPHEMERAL_APPS = false;
399    private static final boolean HIDE_EPHEMERAL_APIS = false;
400
401    private static final boolean ENABLE_FREE_CACHE_V2 =
402            SystemProperties.getBoolean("fw.free_cache_v2", true);
403
404    private static final int RADIO_UID = Process.PHONE_UID;
405    private static final int LOG_UID = Process.LOG_UID;
406    private static final int NFC_UID = Process.NFC_UID;
407    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
408    private static final int SHELL_UID = Process.SHELL_UID;
409
410    // Cap the size of permission trees that 3rd party apps can define
411    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
412
413    // Suffix used during package installation when copying/moving
414    // package apks to install directory.
415    private static final String INSTALL_PACKAGE_SUFFIX = "-";
416
417    static final int SCAN_NO_DEX = 1<<1;
418    static final int SCAN_FORCE_DEX = 1<<2;
419    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
420    static final int SCAN_NEW_INSTALL = 1<<4;
421    static final int SCAN_UPDATE_TIME = 1<<5;
422    static final int SCAN_BOOTING = 1<<6;
423    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
424    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
425    static final int SCAN_REPLACING = 1<<9;
426    static final int SCAN_REQUIRE_KNOWN = 1<<10;
427    static final int SCAN_MOVE = 1<<11;
428    static final int SCAN_INITIAL = 1<<12;
429    static final int SCAN_CHECK_ONLY = 1<<13;
430    static final int SCAN_DONT_KILL_APP = 1<<14;
431    static final int SCAN_IGNORE_FROZEN = 1<<15;
432    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
433    static final int SCAN_AS_INSTANT_APP = 1<<17;
434    static final int SCAN_AS_FULL_APP = 1<<18;
435    /** Should not be with the scan flags */
436    static final int FLAGS_REMOVE_CHATTY = 1<<31;
437
438    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
439
440    private static final int[] EMPTY_INT_ARRAY = new int[0];
441
442    /**
443     * Timeout (in milliseconds) after which the watchdog should declare that
444     * our handler thread is wedged.  The usual default for such things is one
445     * minute but we sometimes do very lengthy I/O operations on this thread,
446     * such as installing multi-gigabyte applications, so ours needs to be longer.
447     */
448    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
449
450    /**
451     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
452     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
453     * settings entry if available, otherwise we use the hardcoded default.  If it's been
454     * more than this long since the last fstrim, we force one during the boot sequence.
455     *
456     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
457     * one gets run at the next available charging+idle time.  This final mandatory
458     * no-fstrim check kicks in only of the other scheduling criteria is never met.
459     */
460    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
461
462    /**
463     * Whether verification is enabled by default.
464     */
465    private static final boolean DEFAULT_VERIFY_ENABLE = true;
466
467    /**
468     * The default maximum time to wait for the verification agent to return in
469     * milliseconds.
470     */
471    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
472
473    /**
474     * The default response for package verification timeout.
475     *
476     * This can be either PackageManager.VERIFICATION_ALLOW or
477     * PackageManager.VERIFICATION_REJECT.
478     */
479    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
480
481    static final String PLATFORM_PACKAGE_NAME = "android";
482
483    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
484
485    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
486            DEFAULT_CONTAINER_PACKAGE,
487            "com.android.defcontainer.DefaultContainerService");
488
489    private static final String KILL_APP_REASON_GIDS_CHANGED =
490            "permission grant or revoke changed gids";
491
492    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
493            "permissions revoked";
494
495    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
496
497    private static final String PACKAGE_SCHEME = "package";
498
499    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
500
501    /** Permission grant: not grant the permission. */
502    private static final int GRANT_DENIED = 1;
503
504    /** Permission grant: grant the permission as an install permission. */
505    private static final int GRANT_INSTALL = 2;
506
507    /** Permission grant: grant the permission as a runtime one. */
508    private static final int GRANT_RUNTIME = 3;
509
510    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
511    private static final int GRANT_UPGRADE = 4;
512
513    /** Canonical intent used to identify what counts as a "web browser" app */
514    private static final Intent sBrowserIntent;
515    static {
516        sBrowserIntent = new Intent();
517        sBrowserIntent.setAction(Intent.ACTION_VIEW);
518        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
519        sBrowserIntent.setData(Uri.parse("http:"));
520    }
521
522    /**
523     * The set of all protected actions [i.e. those actions for which a high priority
524     * intent filter is disallowed].
525     */
526    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
527    static {
528        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
531        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
532    }
533
534    // Compilation reasons.
535    public static final int REASON_FIRST_BOOT = 0;
536    public static final int REASON_BOOT = 1;
537    public static final int REASON_INSTALL = 2;
538    public static final int REASON_BACKGROUND_DEXOPT = 3;
539    public static final int REASON_AB_OTA = 4;
540    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
541    public static final int REASON_SHARED_APK = 6;
542    public static final int REASON_FORCED_DEXOPT = 7;
543    public static final int REASON_CORE_APP = 8;
544
545    public static final int REASON_LAST = REASON_CORE_APP;
546
547    /** All dangerous permission names in the same order as the events in MetricsEvent */
548    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
549            Manifest.permission.READ_CALENDAR,
550            Manifest.permission.WRITE_CALENDAR,
551            Manifest.permission.CAMERA,
552            Manifest.permission.READ_CONTACTS,
553            Manifest.permission.WRITE_CONTACTS,
554            Manifest.permission.GET_ACCOUNTS,
555            Manifest.permission.ACCESS_FINE_LOCATION,
556            Manifest.permission.ACCESS_COARSE_LOCATION,
557            Manifest.permission.RECORD_AUDIO,
558            Manifest.permission.READ_PHONE_STATE,
559            Manifest.permission.CALL_PHONE,
560            Manifest.permission.READ_CALL_LOG,
561            Manifest.permission.WRITE_CALL_LOG,
562            Manifest.permission.ADD_VOICEMAIL,
563            Manifest.permission.USE_SIP,
564            Manifest.permission.PROCESS_OUTGOING_CALLS,
565            Manifest.permission.READ_CELL_BROADCASTS,
566            Manifest.permission.BODY_SENSORS,
567            Manifest.permission.SEND_SMS,
568            Manifest.permission.RECEIVE_SMS,
569            Manifest.permission.READ_SMS,
570            Manifest.permission.RECEIVE_WAP_PUSH,
571            Manifest.permission.RECEIVE_MMS,
572            Manifest.permission.READ_EXTERNAL_STORAGE,
573            Manifest.permission.WRITE_EXTERNAL_STORAGE,
574            Manifest.permission.READ_PHONE_NUMBER,
575            Manifest.permission.ANSWER_PHONE_CALLS);
576
577
578    /**
579     * Version number for the package parser cache. Increment this whenever the format or
580     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
581     */
582    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
583
584    /**
585     * Whether the package parser cache is enabled.
586     */
587    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
588
589    final ServiceThread mHandlerThread;
590
591    final PackageHandler mHandler;
592
593    private final ProcessLoggingHandler mProcessLoggingHandler;
594
595    /**
596     * Messages for {@link #mHandler} that need to wait for system ready before
597     * being dispatched.
598     */
599    private ArrayList<Message> mPostSystemReadyMessages;
600
601    final int mSdkVersion = Build.VERSION.SDK_INT;
602
603    final Context mContext;
604    final boolean mFactoryTest;
605    final boolean mOnlyCore;
606    final DisplayMetrics mMetrics;
607    final int mDefParseFlags;
608    final String[] mSeparateProcesses;
609    final boolean mIsUpgrade;
610    final boolean mIsPreNUpgrade;
611    final boolean mIsPreNMR1Upgrade;
612
613    @GuardedBy("mPackages")
614    private boolean mDexOptDialogShown;
615
616    /** The location for ASEC container files on internal storage. */
617    final String mAsecInternalPath;
618
619    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
620    // LOCK HELD.  Can be called with mInstallLock held.
621    @GuardedBy("mInstallLock")
622    final Installer mInstaller;
623
624    /** Directory where installed third-party apps stored */
625    final File mAppInstallDir;
626
627    /**
628     * Directory to which applications installed internally have their
629     * 32 bit native libraries copied.
630     */
631    private File mAppLib32InstallDir;
632
633    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
634    // apps.
635    final File mDrmAppPrivateInstallDir;
636
637    // ----------------------------------------------------------------
638
639    // Lock for state used when installing and doing other long running
640    // operations.  Methods that must be called with this lock held have
641    // the suffix "LI".
642    final Object mInstallLock = new Object();
643
644    // ----------------------------------------------------------------
645
646    // Keys are String (package name), values are Package.  This also serves
647    // as the lock for the global state.  Methods that must be called with
648    // this lock held have the prefix "LP".
649    @GuardedBy("mPackages")
650    final ArrayMap<String, PackageParser.Package> mPackages =
651            new ArrayMap<String, PackageParser.Package>();
652
653    final ArrayMap<String, Set<String>> mKnownCodebase =
654            new ArrayMap<String, Set<String>>();
655
656    // List of APK paths to load for each user and package. This data is never
657    // persisted by the package manager. Instead, the overlay manager will
658    // ensure the data is up-to-date in runtime.
659    @GuardedBy("mPackages")
660    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
661        new SparseArray<ArrayMap<String, ArrayList<String>>>();
662
663    /**
664     * Tracks new system packages [received in an OTA] that we expect to
665     * find updated user-installed versions. Keys are package name, values
666     * are package location.
667     */
668    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
669    /**
670     * Tracks high priority intent filters for protected actions. During boot, certain
671     * filter actions are protected and should never be allowed to have a high priority
672     * intent filter for them. However, there is one, and only one exception -- the
673     * setup wizard. It must be able to define a high priority intent filter for these
674     * actions to ensure there are no escapes from the wizard. We need to delay processing
675     * of these during boot as we need to look at all of the system packages in order
676     * to know which component is the setup wizard.
677     */
678    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
679    /**
680     * Whether or not processing protected filters should be deferred.
681     */
682    private boolean mDeferProtectedFilters = true;
683
684    /**
685     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
686     */
687    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
688    /**
689     * Whether or not system app permissions should be promoted from install to runtime.
690     */
691    boolean mPromoteSystemApps;
692
693    @GuardedBy("mPackages")
694    final Settings mSettings;
695
696    /**
697     * Set of package names that are currently "frozen", which means active
698     * surgery is being done on the code/data for that package. The platform
699     * will refuse to launch frozen packages to avoid race conditions.
700     *
701     * @see PackageFreezer
702     */
703    @GuardedBy("mPackages")
704    final ArraySet<String> mFrozenPackages = new ArraySet<>();
705
706    final ProtectedPackages mProtectedPackages;
707
708    boolean mFirstBoot;
709
710    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
711
712    // System configuration read by SystemConfig.
713    final int[] mGlobalGids;
714    final SparseArray<ArraySet<String>> mSystemPermissions;
715    @GuardedBy("mAvailableFeatures")
716    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
717
718    // If mac_permissions.xml was found for seinfo labeling.
719    boolean mFoundPolicyFile;
720
721    private final InstantAppRegistry mInstantAppRegistry;
722
723    @GuardedBy("mPackages")
724    int mChangedPackagesSequenceNumber;
725    /**
726     * List of changed [installed, removed or updated] packages.
727     * mapping from user id -> sequence number -> package name
728     */
729    @GuardedBy("mPackages")
730    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
731    /**
732     * The sequence number of the last change to a package.
733     * mapping from user id -> package name -> sequence number
734     */
735    @GuardedBy("mPackages")
736    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
737
738    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
739        @Override public boolean hasFeature(String feature) {
740            return PackageManagerService.this.hasSystemFeature(feature, 0);
741        }
742    };
743
744    public static final class SharedLibraryEntry {
745        public final String path;
746        public final String apk;
747        public final SharedLibraryInfo info;
748
749        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
750                String declaringPackageName, int declaringPackageVersionCode) {
751            path = _path;
752            apk = _apk;
753            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
754                    declaringPackageName, declaringPackageVersionCode), null);
755        }
756    }
757
758    // Currently known shared libraries.
759    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
760    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
761            new ArrayMap<>();
762
763    // All available activities, for your resolving pleasure.
764    final ActivityIntentResolver mActivities =
765            new ActivityIntentResolver();
766
767    // All available receivers, for your resolving pleasure.
768    final ActivityIntentResolver mReceivers =
769            new ActivityIntentResolver();
770
771    // All available services, for your resolving pleasure.
772    final ServiceIntentResolver mServices = new ServiceIntentResolver();
773
774    // All available providers, for your resolving pleasure.
775    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
776
777    // Mapping from provider base names (first directory in content URI codePath)
778    // to the provider information.
779    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
780            new ArrayMap<String, PackageParser.Provider>();
781
782    // Mapping from instrumentation class names to info about them.
783    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
784            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
785
786    // Mapping from permission names to info about them.
787    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
788            new ArrayMap<String, PackageParser.PermissionGroup>();
789
790    // Packages whose data we have transfered into another package, thus
791    // should no longer exist.
792    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
793
794    // Broadcast actions that are only available to the system.
795    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
796
797    /** List of packages waiting for verification. */
798    final SparseArray<PackageVerificationState> mPendingVerification
799            = new SparseArray<PackageVerificationState>();
800
801    /** Set of packages associated with each app op permission. */
802    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
803
804    final PackageInstallerService mInstallerService;
805
806    private final PackageDexOptimizer mPackageDexOptimizer;
807    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
808    // is used by other apps).
809    private final DexManager mDexManager;
810
811    private AtomicInteger mNextMoveId = new AtomicInteger();
812    private final MoveCallbacks mMoveCallbacks;
813
814    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
815
816    // Cache of users who need badging.
817    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
818
819    /** Token for keys in mPendingVerification. */
820    private int mPendingVerificationToken = 0;
821
822    volatile boolean mSystemReady;
823    volatile boolean mSafeMode;
824    volatile boolean mHasSystemUidErrors;
825
826    ApplicationInfo mAndroidApplication;
827    final ActivityInfo mResolveActivity = new ActivityInfo();
828    final ResolveInfo mResolveInfo = new ResolveInfo();
829    ComponentName mResolveComponentName;
830    PackageParser.Package mPlatformPackage;
831    ComponentName mCustomResolverComponentName;
832
833    boolean mResolverReplaced = false;
834
835    private final @Nullable ComponentName mIntentFilterVerifierComponent;
836    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
837
838    private int mIntentFilterVerificationToken = 0;
839
840    /** The service connection to the ephemeral resolver */
841    final EphemeralResolverConnection mInstantAppResolverConnection;
842
843    /** Component used to install ephemeral applications */
844    ComponentName mInstantAppInstallerComponent;
845    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
846    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
847
848    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
849            = new SparseArray<IntentFilterVerificationState>();
850
851    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
852
853    // List of packages names to keep cached, even if they are uninstalled for all users
854    private List<String> mKeepUninstalledPackages;
855
856    private UserManagerInternal mUserManagerInternal;
857
858    private DeviceIdleController.LocalService mDeviceIdleController;
859
860    private File mCacheDir;
861
862    private ArraySet<String> mPrivappPermissionsViolations;
863
864    private Future<?> mPrepareAppDataFuture;
865
866    private static class IFVerificationParams {
867        PackageParser.Package pkg;
868        boolean replacing;
869        int userId;
870        int verifierUid;
871
872        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
873                int _userId, int _verifierUid) {
874            pkg = _pkg;
875            replacing = _replacing;
876            userId = _userId;
877            replacing = _replacing;
878            verifierUid = _verifierUid;
879        }
880    }
881
882    private interface IntentFilterVerifier<T extends IntentFilter> {
883        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
884                                               T filter, String packageName);
885        void startVerifications(int userId);
886        void receiveVerificationResponse(int verificationId);
887    }
888
889    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
890        private Context mContext;
891        private ComponentName mIntentFilterVerifierComponent;
892        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
893
894        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
895            mContext = context;
896            mIntentFilterVerifierComponent = verifierComponent;
897        }
898
899        private String getDefaultScheme() {
900            return IntentFilter.SCHEME_HTTPS;
901        }
902
903        @Override
904        public void startVerifications(int userId) {
905            // Launch verifications requests
906            int count = mCurrentIntentFilterVerifications.size();
907            for (int n=0; n<count; n++) {
908                int verificationId = mCurrentIntentFilterVerifications.get(n);
909                final IntentFilterVerificationState ivs =
910                        mIntentFilterVerificationStates.get(verificationId);
911
912                String packageName = ivs.getPackageName();
913
914                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
915                final int filterCount = filters.size();
916                ArraySet<String> domainsSet = new ArraySet<>();
917                for (int m=0; m<filterCount; m++) {
918                    PackageParser.ActivityIntentInfo filter = filters.get(m);
919                    domainsSet.addAll(filter.getHostsList());
920                }
921                synchronized (mPackages) {
922                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
923                            packageName, domainsSet) != null) {
924                        scheduleWriteSettingsLocked();
925                    }
926                }
927                sendVerificationRequest(userId, verificationId, ivs);
928            }
929            mCurrentIntentFilterVerifications.clear();
930        }
931
932        private void sendVerificationRequest(int userId, int verificationId,
933                IntentFilterVerificationState ivs) {
934
935            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
936            verificationIntent.putExtra(
937                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
938                    verificationId);
939            verificationIntent.putExtra(
940                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
941                    getDefaultScheme());
942            verificationIntent.putExtra(
943                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
944                    ivs.getHostsString());
945            verificationIntent.putExtra(
946                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
947                    ivs.getPackageName());
948            verificationIntent.setComponent(mIntentFilterVerifierComponent);
949            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
950
951            UserHandle user = new UserHandle(userId);
952            mContext.sendBroadcastAsUser(verificationIntent, user);
953            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
954                    "Sending IntentFilter verification broadcast");
955        }
956
957        public void receiveVerificationResponse(int verificationId) {
958            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
959
960            final boolean verified = ivs.isVerified();
961
962            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
963            final int count = filters.size();
964            if (DEBUG_DOMAIN_VERIFICATION) {
965                Slog.i(TAG, "Received verification response " + verificationId
966                        + " for " + count + " filters, verified=" + verified);
967            }
968            for (int n=0; n<count; n++) {
969                PackageParser.ActivityIntentInfo filter = filters.get(n);
970                filter.setVerified(verified);
971
972                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
973                        + " verified with result:" + verified + " and hosts:"
974                        + ivs.getHostsString());
975            }
976
977            mIntentFilterVerificationStates.remove(verificationId);
978
979            final String packageName = ivs.getPackageName();
980            IntentFilterVerificationInfo ivi = null;
981
982            synchronized (mPackages) {
983                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
984            }
985            if (ivi == null) {
986                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
987                        + verificationId + " packageName:" + packageName);
988                return;
989            }
990            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
991                    "Updating IntentFilterVerificationInfo for package " + packageName
992                            +" verificationId:" + verificationId);
993
994            synchronized (mPackages) {
995                if (verified) {
996                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
997                } else {
998                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
999                }
1000                scheduleWriteSettingsLocked();
1001
1002                final int userId = ivs.getUserId();
1003                if (userId != UserHandle.USER_ALL) {
1004                    final int userStatus =
1005                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1006
1007                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1008                    boolean needUpdate = false;
1009
1010                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1011                    // already been set by the User thru the Disambiguation dialog
1012                    switch (userStatus) {
1013                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1014                            if (verified) {
1015                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1016                            } else {
1017                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1018                            }
1019                            needUpdate = true;
1020                            break;
1021
1022                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1023                            if (verified) {
1024                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1025                                needUpdate = true;
1026                            }
1027                            break;
1028
1029                        default:
1030                            // Nothing to do
1031                    }
1032
1033                    if (needUpdate) {
1034                        mSettings.updateIntentFilterVerificationStatusLPw(
1035                                packageName, updatedStatus, userId);
1036                        scheduleWritePackageRestrictionsLocked(userId);
1037                    }
1038                }
1039            }
1040        }
1041
1042        @Override
1043        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1044                    ActivityIntentInfo filter, String packageName) {
1045            if (!hasValidDomains(filter)) {
1046                return false;
1047            }
1048            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1049            if (ivs == null) {
1050                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1051                        packageName);
1052            }
1053            if (DEBUG_DOMAIN_VERIFICATION) {
1054                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1055            }
1056            ivs.addFilter(filter);
1057            return true;
1058        }
1059
1060        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1061                int userId, int verificationId, String packageName) {
1062            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1063                    verifierUid, userId, packageName);
1064            ivs.setPendingState();
1065            synchronized (mPackages) {
1066                mIntentFilterVerificationStates.append(verificationId, ivs);
1067                mCurrentIntentFilterVerifications.add(verificationId);
1068            }
1069            return ivs;
1070        }
1071    }
1072
1073    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1074        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1075                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1076                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1077    }
1078
1079    // Set of pending broadcasts for aggregating enable/disable of components.
1080    static class PendingPackageBroadcasts {
1081        // for each user id, a map of <package name -> components within that package>
1082        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1083
1084        public PendingPackageBroadcasts() {
1085            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1086        }
1087
1088        public ArrayList<String> get(int userId, String packageName) {
1089            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1090            return packages.get(packageName);
1091        }
1092
1093        public void put(int userId, String packageName, ArrayList<String> components) {
1094            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1095            packages.put(packageName, components);
1096        }
1097
1098        public void remove(int userId, String packageName) {
1099            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1100            if (packages != null) {
1101                packages.remove(packageName);
1102            }
1103        }
1104
1105        public void remove(int userId) {
1106            mUidMap.remove(userId);
1107        }
1108
1109        public int userIdCount() {
1110            return mUidMap.size();
1111        }
1112
1113        public int userIdAt(int n) {
1114            return mUidMap.keyAt(n);
1115        }
1116
1117        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1118            return mUidMap.get(userId);
1119        }
1120
1121        public int size() {
1122            // total number of pending broadcast entries across all userIds
1123            int num = 0;
1124            for (int i = 0; i< mUidMap.size(); i++) {
1125                num += mUidMap.valueAt(i).size();
1126            }
1127            return num;
1128        }
1129
1130        public void clear() {
1131            mUidMap.clear();
1132        }
1133
1134        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1135            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1136            if (map == null) {
1137                map = new ArrayMap<String, ArrayList<String>>();
1138                mUidMap.put(userId, map);
1139            }
1140            return map;
1141        }
1142    }
1143    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1144
1145    // Service Connection to remote media container service to copy
1146    // package uri's from external media onto secure containers
1147    // or internal storage.
1148    private IMediaContainerService mContainerService = null;
1149
1150    static final int SEND_PENDING_BROADCAST = 1;
1151    static final int MCS_BOUND = 3;
1152    static final int END_COPY = 4;
1153    static final int INIT_COPY = 5;
1154    static final int MCS_UNBIND = 6;
1155    static final int START_CLEANING_PACKAGE = 7;
1156    static final int FIND_INSTALL_LOC = 8;
1157    static final int POST_INSTALL = 9;
1158    static final int MCS_RECONNECT = 10;
1159    static final int MCS_GIVE_UP = 11;
1160    static final int UPDATED_MEDIA_STATUS = 12;
1161    static final int WRITE_SETTINGS = 13;
1162    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1163    static final int PACKAGE_VERIFIED = 15;
1164    static final int CHECK_PENDING_VERIFICATION = 16;
1165    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1166    static final int INTENT_FILTER_VERIFIED = 18;
1167    static final int WRITE_PACKAGE_LIST = 19;
1168    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1169
1170    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1171
1172    // Delay time in millisecs
1173    static final int BROADCAST_DELAY = 10 * 1000;
1174
1175    static UserManagerService sUserManager;
1176
1177    // Stores a list of users whose package restrictions file needs to be updated
1178    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1179
1180    final private DefaultContainerConnection mDefContainerConn =
1181            new DefaultContainerConnection();
1182    class DefaultContainerConnection implements ServiceConnection {
1183        public void onServiceConnected(ComponentName name, IBinder service) {
1184            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1185            final IMediaContainerService imcs = IMediaContainerService.Stub
1186                    .asInterface(Binder.allowBlocking(service));
1187            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1188        }
1189
1190        public void onServiceDisconnected(ComponentName name) {
1191            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1192        }
1193    }
1194
1195    // Recordkeeping of restore-after-install operations that are currently in flight
1196    // between the Package Manager and the Backup Manager
1197    static class PostInstallData {
1198        public InstallArgs args;
1199        public PackageInstalledInfo res;
1200
1201        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1202            args = _a;
1203            res = _r;
1204        }
1205    }
1206
1207    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1208    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1209
1210    // XML tags for backup/restore of various bits of state
1211    private static final String TAG_PREFERRED_BACKUP = "pa";
1212    private static final String TAG_DEFAULT_APPS = "da";
1213    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1214
1215    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1216    private static final String TAG_ALL_GRANTS = "rt-grants";
1217    private static final String TAG_GRANT = "grant";
1218    private static final String ATTR_PACKAGE_NAME = "pkg";
1219
1220    private static final String TAG_PERMISSION = "perm";
1221    private static final String ATTR_PERMISSION_NAME = "name";
1222    private static final String ATTR_IS_GRANTED = "g";
1223    private static final String ATTR_USER_SET = "set";
1224    private static final String ATTR_USER_FIXED = "fixed";
1225    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1226
1227    // System/policy permission grants are not backed up
1228    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1229            FLAG_PERMISSION_POLICY_FIXED
1230            | FLAG_PERMISSION_SYSTEM_FIXED
1231            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1232
1233    // And we back up these user-adjusted states
1234    private static final int USER_RUNTIME_GRANT_MASK =
1235            FLAG_PERMISSION_USER_SET
1236            | FLAG_PERMISSION_USER_FIXED
1237            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1238
1239    final @Nullable String mRequiredVerifierPackage;
1240    final @NonNull String mRequiredInstallerPackage;
1241    final @NonNull String mRequiredUninstallerPackage;
1242    final @Nullable String mSetupWizardPackage;
1243    final @Nullable String mStorageManagerPackage;
1244    final @NonNull String mServicesSystemSharedLibraryPackageName;
1245    final @NonNull String mSharedSystemSharedLibraryPackageName;
1246
1247    final boolean mPermissionReviewRequired;
1248
1249    private final PackageUsage mPackageUsage = new PackageUsage();
1250    private final CompilerStats mCompilerStats = new CompilerStats();
1251
1252    class PackageHandler extends Handler {
1253        private boolean mBound = false;
1254        final ArrayList<HandlerParams> mPendingInstalls =
1255            new ArrayList<HandlerParams>();
1256
1257        private boolean connectToService() {
1258            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1259                    " DefaultContainerService");
1260            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1261            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1263                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1264                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1265                mBound = true;
1266                return true;
1267            }
1268            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1269            return false;
1270        }
1271
1272        private void disconnectService() {
1273            mContainerService = null;
1274            mBound = false;
1275            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1276            mContext.unbindService(mDefContainerConn);
1277            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1278        }
1279
1280        PackageHandler(Looper looper) {
1281            super(looper);
1282        }
1283
1284        public void handleMessage(Message msg) {
1285            try {
1286                doHandleMessage(msg);
1287            } finally {
1288                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1289            }
1290        }
1291
1292        void doHandleMessage(Message msg) {
1293            switch (msg.what) {
1294                case INIT_COPY: {
1295                    HandlerParams params = (HandlerParams) msg.obj;
1296                    int idx = mPendingInstalls.size();
1297                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1298                    // If a bind was already initiated we dont really
1299                    // need to do anything. The pending install
1300                    // will be processed later on.
1301                    if (!mBound) {
1302                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1303                                System.identityHashCode(mHandler));
1304                        // If this is the only one pending we might
1305                        // have to bind to the service again.
1306                        if (!connectToService()) {
1307                            Slog.e(TAG, "Failed to bind to media container service");
1308                            params.serviceError();
1309                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1310                                    System.identityHashCode(mHandler));
1311                            if (params.traceMethod != null) {
1312                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1313                                        params.traceCookie);
1314                            }
1315                            return;
1316                        } else {
1317                            // Once we bind to the service, the first
1318                            // pending request will be processed.
1319                            mPendingInstalls.add(idx, params);
1320                        }
1321                    } else {
1322                        mPendingInstalls.add(idx, params);
1323                        // Already bound to the service. Just make
1324                        // sure we trigger off processing the first request.
1325                        if (idx == 0) {
1326                            mHandler.sendEmptyMessage(MCS_BOUND);
1327                        }
1328                    }
1329                    break;
1330                }
1331                case MCS_BOUND: {
1332                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1333                    if (msg.obj != null) {
1334                        mContainerService = (IMediaContainerService) msg.obj;
1335                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1336                                System.identityHashCode(mHandler));
1337                    }
1338                    if (mContainerService == null) {
1339                        if (!mBound) {
1340                            // Something seriously wrong since we are not bound and we are not
1341                            // waiting for connection. Bail out.
1342                            Slog.e(TAG, "Cannot bind to media container service");
1343                            for (HandlerParams params : mPendingInstalls) {
1344                                // Indicate service bind error
1345                                params.serviceError();
1346                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1347                                        System.identityHashCode(params));
1348                                if (params.traceMethod != null) {
1349                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1350                                            params.traceMethod, params.traceCookie);
1351                                }
1352                                return;
1353                            }
1354                            mPendingInstalls.clear();
1355                        } else {
1356                            Slog.w(TAG, "Waiting to connect to media container service");
1357                        }
1358                    } else if (mPendingInstalls.size() > 0) {
1359                        HandlerParams params = mPendingInstalls.get(0);
1360                        if (params != null) {
1361                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1362                                    System.identityHashCode(params));
1363                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1364                            if (params.startCopy()) {
1365                                // We are done...  look for more work or to
1366                                // go idle.
1367                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1368                                        "Checking for more work or unbind...");
1369                                // Delete pending install
1370                                if (mPendingInstalls.size() > 0) {
1371                                    mPendingInstalls.remove(0);
1372                                }
1373                                if (mPendingInstalls.size() == 0) {
1374                                    if (mBound) {
1375                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1376                                                "Posting delayed MCS_UNBIND");
1377                                        removeMessages(MCS_UNBIND);
1378                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1379                                        // Unbind after a little delay, to avoid
1380                                        // continual thrashing.
1381                                        sendMessageDelayed(ubmsg, 10000);
1382                                    }
1383                                } else {
1384                                    // There are more pending requests in queue.
1385                                    // Just post MCS_BOUND message to trigger processing
1386                                    // of next pending install.
1387                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1388                                            "Posting MCS_BOUND for next work");
1389                                    mHandler.sendEmptyMessage(MCS_BOUND);
1390                                }
1391                            }
1392                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1393                        }
1394                    } else {
1395                        // Should never happen ideally.
1396                        Slog.w(TAG, "Empty queue");
1397                    }
1398                    break;
1399                }
1400                case MCS_RECONNECT: {
1401                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1402                    if (mPendingInstalls.size() > 0) {
1403                        if (mBound) {
1404                            disconnectService();
1405                        }
1406                        if (!connectToService()) {
1407                            Slog.e(TAG, "Failed to bind to media container service");
1408                            for (HandlerParams params : mPendingInstalls) {
1409                                // Indicate service bind error
1410                                params.serviceError();
1411                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1412                                        System.identityHashCode(params));
1413                            }
1414                            mPendingInstalls.clear();
1415                        }
1416                    }
1417                    break;
1418                }
1419                case MCS_UNBIND: {
1420                    // If there is no actual work left, then time to unbind.
1421                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1422
1423                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1424                        if (mBound) {
1425                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1426
1427                            disconnectService();
1428                        }
1429                    } else if (mPendingInstalls.size() > 0) {
1430                        // There are more pending requests in queue.
1431                        // Just post MCS_BOUND message to trigger processing
1432                        // of next pending install.
1433                        mHandler.sendEmptyMessage(MCS_BOUND);
1434                    }
1435
1436                    break;
1437                }
1438                case MCS_GIVE_UP: {
1439                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1440                    HandlerParams params = mPendingInstalls.remove(0);
1441                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1442                            System.identityHashCode(params));
1443                    break;
1444                }
1445                case SEND_PENDING_BROADCAST: {
1446                    String packages[];
1447                    ArrayList<String> components[];
1448                    int size = 0;
1449                    int uids[];
1450                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1451                    synchronized (mPackages) {
1452                        if (mPendingBroadcasts == null) {
1453                            return;
1454                        }
1455                        size = mPendingBroadcasts.size();
1456                        if (size <= 0) {
1457                            // Nothing to be done. Just return
1458                            return;
1459                        }
1460                        packages = new String[size];
1461                        components = new ArrayList[size];
1462                        uids = new int[size];
1463                        int i = 0;  // filling out the above arrays
1464
1465                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1466                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1467                            Iterator<Map.Entry<String, ArrayList<String>>> it
1468                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1469                                            .entrySet().iterator();
1470                            while (it.hasNext() && i < size) {
1471                                Map.Entry<String, ArrayList<String>> ent = it.next();
1472                                packages[i] = ent.getKey();
1473                                components[i] = ent.getValue();
1474                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1475                                uids[i] = (ps != null)
1476                                        ? UserHandle.getUid(packageUserId, ps.appId)
1477                                        : -1;
1478                                i++;
1479                            }
1480                        }
1481                        size = i;
1482                        mPendingBroadcasts.clear();
1483                    }
1484                    // Send broadcasts
1485                    for (int i = 0; i < size; i++) {
1486                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                    break;
1490                }
1491                case START_CLEANING_PACKAGE: {
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1493                    final String packageName = (String)msg.obj;
1494                    final int userId = msg.arg1;
1495                    final boolean andCode = msg.arg2 != 0;
1496                    synchronized (mPackages) {
1497                        if (userId == UserHandle.USER_ALL) {
1498                            int[] users = sUserManager.getUserIds();
1499                            for (int user : users) {
1500                                mSettings.addPackageToCleanLPw(
1501                                        new PackageCleanItem(user, packageName, andCode));
1502                            }
1503                        } else {
1504                            mSettings.addPackageToCleanLPw(
1505                                    new PackageCleanItem(userId, packageName, andCode));
1506                        }
1507                    }
1508                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1509                    startCleaningPackages();
1510                } break;
1511                case POST_INSTALL: {
1512                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1513
1514                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1515                    final boolean didRestore = (msg.arg2 != 0);
1516                    mRunningInstalls.delete(msg.arg1);
1517
1518                    if (data != null) {
1519                        InstallArgs args = data.args;
1520                        PackageInstalledInfo parentRes = data.res;
1521
1522                        final boolean grantPermissions = (args.installFlags
1523                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1524                        final boolean killApp = (args.installFlags
1525                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1526                        final String[] grantedPermissions = args.installGrantPermissions;
1527
1528                        // Handle the parent package
1529                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1530                                grantedPermissions, didRestore, args.installerPackageName,
1531                                args.observer);
1532
1533                        // Handle the child packages
1534                        final int childCount = (parentRes.addedChildPackages != null)
1535                                ? parentRes.addedChildPackages.size() : 0;
1536                        for (int i = 0; i < childCount; i++) {
1537                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1538                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1539                                    grantedPermissions, false, args.installerPackageName,
1540                                    args.observer);
1541                        }
1542
1543                        // Log tracing if needed
1544                        if (args.traceMethod != null) {
1545                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1546                                    args.traceCookie);
1547                        }
1548                    } else {
1549                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1550                    }
1551
1552                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1553                } break;
1554                case UPDATED_MEDIA_STATUS: {
1555                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1556                    boolean reportStatus = msg.arg1 == 1;
1557                    boolean doGc = msg.arg2 == 1;
1558                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1559                    if (doGc) {
1560                        // Force a gc to clear up stale containers.
1561                        Runtime.getRuntime().gc();
1562                    }
1563                    if (msg.obj != null) {
1564                        @SuppressWarnings("unchecked")
1565                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1566                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1567                        // Unload containers
1568                        unloadAllContainers(args);
1569                    }
1570                    if (reportStatus) {
1571                        try {
1572                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1573                                    "Invoking StorageManagerService call back");
1574                            PackageHelper.getStorageManager().finishMediaUpdate();
1575                        } catch (RemoteException e) {
1576                            Log.e(TAG, "StorageManagerService not running?");
1577                        }
1578                    }
1579                } break;
1580                case WRITE_SETTINGS: {
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1582                    synchronized (mPackages) {
1583                        removeMessages(WRITE_SETTINGS);
1584                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1585                        mSettings.writeLPr();
1586                        mDirtyUsers.clear();
1587                    }
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1589                } break;
1590                case WRITE_PACKAGE_RESTRICTIONS: {
1591                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1592                    synchronized (mPackages) {
1593                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1594                        for (int userId : mDirtyUsers) {
1595                            mSettings.writePackageRestrictionsLPr(userId);
1596                        }
1597                        mDirtyUsers.clear();
1598                    }
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1600                } break;
1601                case WRITE_PACKAGE_LIST: {
1602                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603                    synchronized (mPackages) {
1604                        removeMessages(WRITE_PACKAGE_LIST);
1605                        mSettings.writePackageListLPr(msg.arg1);
1606                    }
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1608                } break;
1609                case CHECK_PENDING_VERIFICATION: {
1610                    final int verificationId = msg.arg1;
1611                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1612
1613                    if ((state != null) && !state.timeoutExtended()) {
1614                        final InstallArgs args = state.getInstallArgs();
1615                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1616
1617                        Slog.i(TAG, "Verification timed out for " + originUri);
1618                        mPendingVerification.remove(verificationId);
1619
1620                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1621
1622                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1623                            Slog.i(TAG, "Continuing with installation of " + originUri);
1624                            state.setVerifierResponse(Binder.getCallingUid(),
1625                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1626                            broadcastPackageVerified(verificationId, originUri,
1627                                    PackageManager.VERIFICATION_ALLOW,
1628                                    state.getInstallArgs().getUser());
1629                            try {
1630                                ret = args.copyApk(mContainerService, true);
1631                            } catch (RemoteException e) {
1632                                Slog.e(TAG, "Could not contact the ContainerService");
1633                            }
1634                        } else {
1635                            broadcastPackageVerified(verificationId, originUri,
1636                                    PackageManager.VERIFICATION_REJECT,
1637                                    state.getInstallArgs().getUser());
1638                        }
1639
1640                        Trace.asyncTraceEnd(
1641                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1642
1643                        processPendingInstall(args, ret);
1644                        mHandler.sendEmptyMessage(MCS_UNBIND);
1645                    }
1646                    break;
1647                }
1648                case PACKAGE_VERIFIED: {
1649                    final int verificationId = msg.arg1;
1650
1651                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1652                    if (state == null) {
1653                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1654                        break;
1655                    }
1656
1657                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1658
1659                    state.setVerifierResponse(response.callerUid, response.code);
1660
1661                    if (state.isVerificationComplete()) {
1662                        mPendingVerification.remove(verificationId);
1663
1664                        final InstallArgs args = state.getInstallArgs();
1665                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1666
1667                        int ret;
1668                        if (state.isInstallAllowed()) {
1669                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1670                            broadcastPackageVerified(verificationId, originUri,
1671                                    response.code, state.getInstallArgs().getUser());
1672                            try {
1673                                ret = args.copyApk(mContainerService, true);
1674                            } catch (RemoteException e) {
1675                                Slog.e(TAG, "Could not contact the ContainerService");
1676                            }
1677                        } else {
1678                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1679                        }
1680
1681                        Trace.asyncTraceEnd(
1682                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1683
1684                        processPendingInstall(args, ret);
1685                        mHandler.sendEmptyMessage(MCS_UNBIND);
1686                    }
1687
1688                    break;
1689                }
1690                case START_INTENT_FILTER_VERIFICATIONS: {
1691                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1692                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1693                            params.replacing, params.pkg);
1694                    break;
1695                }
1696                case INTENT_FILTER_VERIFIED: {
1697                    final int verificationId = msg.arg1;
1698
1699                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1700                            verificationId);
1701                    if (state == null) {
1702                        Slog.w(TAG, "Invalid IntentFilter verification token "
1703                                + verificationId + " received");
1704                        break;
1705                    }
1706
1707                    final int userId = state.getUserId();
1708
1709                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1710                            "Processing IntentFilter verification with token:"
1711                            + verificationId + " and userId:" + userId);
1712
1713                    final IntentFilterVerificationResponse response =
1714                            (IntentFilterVerificationResponse) msg.obj;
1715
1716                    state.setVerifierResponse(response.callerUid, response.code);
1717
1718                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1719                            "IntentFilter verification with token:" + verificationId
1720                            + " and userId:" + userId
1721                            + " is settings verifier response with response code:"
1722                            + response.code);
1723
1724                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1725                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1726                                + response.getFailedDomainsString());
1727                    }
1728
1729                    if (state.isVerificationComplete()) {
1730                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1731                    } else {
1732                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1733                                "IntentFilter verification with token:" + verificationId
1734                                + " was not said to be complete");
1735                    }
1736
1737                    break;
1738                }
1739                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1740                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1741                            mInstantAppResolverConnection,
1742                            (InstantAppRequest) msg.obj,
1743                            mInstantAppInstallerActivity,
1744                            mHandler);
1745                }
1746            }
1747        }
1748    }
1749
1750    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1751            boolean killApp, String[] grantedPermissions,
1752            boolean launchedForRestore, String installerPackage,
1753            IPackageInstallObserver2 installObserver) {
1754        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1755            // Send the removed broadcasts
1756            if (res.removedInfo != null) {
1757                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1758            }
1759
1760            // Now that we successfully installed the package, grant runtime
1761            // permissions if requested before broadcasting the install. Also
1762            // for legacy apps in permission review mode we clear the permission
1763            // review flag which is used to emulate runtime permissions for
1764            // legacy apps.
1765            if (grantPermissions) {
1766                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1767            }
1768
1769            final boolean update = res.removedInfo != null
1770                    && res.removedInfo.removedPackage != null;
1771
1772            // If this is the first time we have child packages for a disabled privileged
1773            // app that had no children, we grant requested runtime permissions to the new
1774            // children if the parent on the system image had them already granted.
1775            if (res.pkg.parentPackage != null) {
1776                synchronized (mPackages) {
1777                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1778                }
1779            }
1780
1781            synchronized (mPackages) {
1782                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1783            }
1784
1785            final String packageName = res.pkg.applicationInfo.packageName;
1786
1787            // Determine the set of users who are adding this package for
1788            // the first time vs. those who are seeing an update.
1789            int[] firstUsers = EMPTY_INT_ARRAY;
1790            int[] updateUsers = EMPTY_INT_ARRAY;
1791            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1792            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1793            for (int newUser : res.newUsers) {
1794                if (ps.getInstantApp(newUser)) {
1795                    continue;
1796                }
1797                if (allNewUsers) {
1798                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1799                    continue;
1800                }
1801                boolean isNew = true;
1802                for (int origUser : res.origUsers) {
1803                    if (origUser == newUser) {
1804                        isNew = false;
1805                        break;
1806                    }
1807                }
1808                if (isNew) {
1809                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1810                } else {
1811                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1812                }
1813            }
1814
1815            // Send installed broadcasts if the package is not a static shared lib.
1816            if (res.pkg.staticSharedLibName == null) {
1817                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1818
1819                // Send added for users that see the package for the first time
1820                // sendPackageAddedForNewUsers also deals with system apps
1821                int appId = UserHandle.getAppId(res.uid);
1822                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1823                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1824
1825                // Send added for users that don't see the package for the first time
1826                Bundle extras = new Bundle(1);
1827                extras.putInt(Intent.EXTRA_UID, res.uid);
1828                if (update) {
1829                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1830                }
1831                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1832                        extras, 0 /*flags*/, null /*targetPackage*/,
1833                        null /*finishedReceiver*/, updateUsers);
1834
1835                // Send replaced for users that don't see the package for the first time
1836                if (update) {
1837                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1838                            packageName, extras, 0 /*flags*/,
1839                            null /*targetPackage*/, null /*finishedReceiver*/,
1840                            updateUsers);
1841                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1842                            null /*package*/, null /*extras*/, 0 /*flags*/,
1843                            packageName /*targetPackage*/,
1844                            null /*finishedReceiver*/, updateUsers);
1845                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1846                    // First-install and we did a restore, so we're responsible for the
1847                    // first-launch broadcast.
1848                    if (DEBUG_BACKUP) {
1849                        Slog.i(TAG, "Post-restore of " + packageName
1850                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1851                    }
1852                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1853                }
1854
1855                // Send broadcast package appeared if forward locked/external for all users
1856                // treat asec-hosted packages like removable media on upgrade
1857                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1858                    if (DEBUG_INSTALL) {
1859                        Slog.i(TAG, "upgrading pkg " + res.pkg
1860                                + " is ASEC-hosted -> AVAILABLE");
1861                    }
1862                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1863                    ArrayList<String> pkgList = new ArrayList<>(1);
1864                    pkgList.add(packageName);
1865                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1866                }
1867            }
1868
1869            // Work that needs to happen on first install within each user
1870            if (firstUsers != null && firstUsers.length > 0) {
1871                synchronized (mPackages) {
1872                    for (int userId : firstUsers) {
1873                        // If this app is a browser and it's newly-installed for some
1874                        // users, clear any default-browser state in those users. The
1875                        // app's nature doesn't depend on the user, so we can just check
1876                        // its browser nature in any user and generalize.
1877                        if (packageIsBrowser(packageName, userId)) {
1878                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1879                        }
1880
1881                        // We may also need to apply pending (restored) runtime
1882                        // permission grants within these users.
1883                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1884                    }
1885                }
1886            }
1887
1888            // Log current value of "unknown sources" setting
1889            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1890                    getUnknownSourcesSettings());
1891
1892            // Force a gc to clear up things
1893            Runtime.getRuntime().gc();
1894
1895            // Remove the replaced package's older resources safely now
1896            // We delete after a gc for applications  on sdcard.
1897            if (res.removedInfo != null && res.removedInfo.args != null) {
1898                synchronized (mInstallLock) {
1899                    res.removedInfo.args.doPostDeleteLI(true);
1900                }
1901            }
1902
1903            // Notify DexManager that the package was installed for new users.
1904            // The updated users should already be indexed and the package code paths
1905            // should not change.
1906            // Don't notify the manager for ephemeral apps as they are not expected to
1907            // survive long enough to benefit of background optimizations.
1908            for (int userId : firstUsers) {
1909                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1910                mDexManager.notifyPackageInstalled(info, userId);
1911            }
1912        }
1913
1914        // If someone is watching installs - notify them
1915        if (installObserver != null) {
1916            try {
1917                Bundle extras = extrasForInstallResult(res);
1918                installObserver.onPackageInstalled(res.name, res.returnCode,
1919                        res.returnMsg, extras);
1920            } catch (RemoteException e) {
1921                Slog.i(TAG, "Observer no longer exists.");
1922            }
1923        }
1924    }
1925
1926    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1927            PackageParser.Package pkg) {
1928        if (pkg.parentPackage == null) {
1929            return;
1930        }
1931        if (pkg.requestedPermissions == null) {
1932            return;
1933        }
1934        final PackageSetting disabledSysParentPs = mSettings
1935                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1936        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1937                || !disabledSysParentPs.isPrivileged()
1938                || (disabledSysParentPs.childPackageNames != null
1939                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1940            return;
1941        }
1942        final int[] allUserIds = sUserManager.getUserIds();
1943        final int permCount = pkg.requestedPermissions.size();
1944        for (int i = 0; i < permCount; i++) {
1945            String permission = pkg.requestedPermissions.get(i);
1946            BasePermission bp = mSettings.mPermissions.get(permission);
1947            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1948                continue;
1949            }
1950            for (int userId : allUserIds) {
1951                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1952                        permission, userId)) {
1953                    grantRuntimePermission(pkg.packageName, permission, userId);
1954                }
1955            }
1956        }
1957    }
1958
1959    private StorageEventListener mStorageListener = new StorageEventListener() {
1960        @Override
1961        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1962            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1963                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1964                    final String volumeUuid = vol.getFsUuid();
1965
1966                    // Clean up any users or apps that were removed or recreated
1967                    // while this volume was missing
1968                    sUserManager.reconcileUsers(volumeUuid);
1969                    reconcileApps(volumeUuid);
1970
1971                    // Clean up any install sessions that expired or were
1972                    // cancelled while this volume was missing
1973                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1974
1975                    loadPrivatePackages(vol);
1976
1977                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1978                    unloadPrivatePackages(vol);
1979                }
1980            }
1981
1982            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1983                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1984                    updateExternalMediaStatus(true, false);
1985                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1986                    updateExternalMediaStatus(false, false);
1987                }
1988            }
1989        }
1990
1991        @Override
1992        public void onVolumeForgotten(String fsUuid) {
1993            if (TextUtils.isEmpty(fsUuid)) {
1994                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1995                return;
1996            }
1997
1998            // Remove any apps installed on the forgotten volume
1999            synchronized (mPackages) {
2000                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2001                for (PackageSetting ps : packages) {
2002                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2003                    deletePackageVersioned(new VersionedPackage(ps.name,
2004                            PackageManager.VERSION_CODE_HIGHEST),
2005                            new LegacyPackageDeleteObserver(null).getBinder(),
2006                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2007                    // Try very hard to release any references to this package
2008                    // so we don't risk the system server being killed due to
2009                    // open FDs
2010                    AttributeCache.instance().removePackage(ps.name);
2011                }
2012
2013                mSettings.onVolumeForgotten(fsUuid);
2014                mSettings.writeLPr();
2015            }
2016        }
2017    };
2018
2019    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2020            String[] grantedPermissions) {
2021        for (int userId : userIds) {
2022            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2023        }
2024    }
2025
2026    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2027            String[] grantedPermissions) {
2028        SettingBase sb = (SettingBase) pkg.mExtras;
2029        if (sb == null) {
2030            return;
2031        }
2032
2033        PermissionsState permissionsState = sb.getPermissionsState();
2034
2035        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2036                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2037
2038        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2039                >= Build.VERSION_CODES.M;
2040
2041        for (String permission : pkg.requestedPermissions) {
2042            final BasePermission bp;
2043            synchronized (mPackages) {
2044                bp = mSettings.mPermissions.get(permission);
2045            }
2046            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2047                    && (grantedPermissions == null
2048                           || ArrayUtils.contains(grantedPermissions, permission))) {
2049                final int flags = permissionsState.getPermissionFlags(permission, userId);
2050                if (supportsRuntimePermissions) {
2051                    // Installer cannot change immutable permissions.
2052                    if ((flags & immutableFlags) == 0) {
2053                        grantRuntimePermission(pkg.packageName, permission, userId);
2054                    }
2055                } else if (mPermissionReviewRequired) {
2056                    // In permission review mode we clear the review flag when we
2057                    // are asked to install the app with all permissions granted.
2058                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2059                        updatePermissionFlags(permission, pkg.packageName,
2060                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2061                    }
2062                }
2063            }
2064        }
2065    }
2066
2067    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2068        Bundle extras = null;
2069        switch (res.returnCode) {
2070            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2071                extras = new Bundle();
2072                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2073                        res.origPermission);
2074                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2075                        res.origPackage);
2076                break;
2077            }
2078            case PackageManager.INSTALL_SUCCEEDED: {
2079                extras = new Bundle();
2080                extras.putBoolean(Intent.EXTRA_REPLACING,
2081                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2082                break;
2083            }
2084        }
2085        return extras;
2086    }
2087
2088    void scheduleWriteSettingsLocked() {
2089        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2090            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2091        }
2092    }
2093
2094    void scheduleWritePackageListLocked(int userId) {
2095        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2096            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2097            msg.arg1 = userId;
2098            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2099        }
2100    }
2101
2102    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2103        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2104        scheduleWritePackageRestrictionsLocked(userId);
2105    }
2106
2107    void scheduleWritePackageRestrictionsLocked(int userId) {
2108        final int[] userIds = (userId == UserHandle.USER_ALL)
2109                ? sUserManager.getUserIds() : new int[]{userId};
2110        for (int nextUserId : userIds) {
2111            if (!sUserManager.exists(nextUserId)) return;
2112            mDirtyUsers.add(nextUserId);
2113            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2114                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2115            }
2116        }
2117    }
2118
2119    public static PackageManagerService main(Context context, Installer installer,
2120            boolean factoryTest, boolean onlyCore) {
2121        // Self-check for initial settings.
2122        PackageManagerServiceCompilerMapping.checkProperties();
2123
2124        PackageManagerService m = new PackageManagerService(context, installer,
2125                factoryTest, onlyCore);
2126        m.enableSystemUserPackages();
2127        ServiceManager.addService("package", m);
2128        return m;
2129    }
2130
2131    private void enableSystemUserPackages() {
2132        if (!UserManager.isSplitSystemUser()) {
2133            return;
2134        }
2135        // For system user, enable apps based on the following conditions:
2136        // - app is whitelisted or belong to one of these groups:
2137        //   -- system app which has no launcher icons
2138        //   -- system app which has INTERACT_ACROSS_USERS permission
2139        //   -- system IME app
2140        // - app is not in the blacklist
2141        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2142        Set<String> enableApps = new ArraySet<>();
2143        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2144                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2145                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2146        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2147        enableApps.addAll(wlApps);
2148        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2149                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2150        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2151        enableApps.removeAll(blApps);
2152        Log.i(TAG, "Applications installed for system user: " + enableApps);
2153        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2154                UserHandle.SYSTEM);
2155        final int allAppsSize = allAps.size();
2156        synchronized (mPackages) {
2157            for (int i = 0; i < allAppsSize; i++) {
2158                String pName = allAps.get(i);
2159                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2160                // Should not happen, but we shouldn't be failing if it does
2161                if (pkgSetting == null) {
2162                    continue;
2163                }
2164                boolean install = enableApps.contains(pName);
2165                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2166                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2167                            + " for system user");
2168                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2169                }
2170            }
2171            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2172        }
2173    }
2174
2175    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2176        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2177                Context.DISPLAY_SERVICE);
2178        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2179    }
2180
2181    /**
2182     * Requests that files preopted on a secondary system partition be copied to the data partition
2183     * if possible.  Note that the actual copying of the files is accomplished by init for security
2184     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2185     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2186     */
2187    private static void requestCopyPreoptedFiles() {
2188        final int WAIT_TIME_MS = 100;
2189        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2190        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2191            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2192            // We will wait for up to 100 seconds.
2193            final long timeStart = SystemClock.uptimeMillis();
2194            final long timeEnd = timeStart + 100 * 1000;
2195            long timeNow = timeStart;
2196            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2197                try {
2198                    Thread.sleep(WAIT_TIME_MS);
2199                } catch (InterruptedException e) {
2200                    // Do nothing
2201                }
2202                timeNow = SystemClock.uptimeMillis();
2203                if (timeNow > timeEnd) {
2204                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2205                    Slog.wtf(TAG, "cppreopt did not finish!");
2206                    break;
2207                }
2208            }
2209
2210            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2211        }
2212    }
2213
2214    public PackageManagerService(Context context, Installer installer,
2215            boolean factoryTest, boolean onlyCore) {
2216        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2217        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2218        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2219                SystemClock.uptimeMillis());
2220
2221        if (mSdkVersion <= 0) {
2222            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2223        }
2224
2225        mContext = context;
2226
2227        mPermissionReviewRequired = context.getResources().getBoolean(
2228                R.bool.config_permissionReviewRequired);
2229
2230        mFactoryTest = factoryTest;
2231        mOnlyCore = onlyCore;
2232        mMetrics = new DisplayMetrics();
2233        mSettings = new Settings(mPackages);
2234        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2235                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2236        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2243                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2244        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2245                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2246
2247        String separateProcesses = SystemProperties.get("debug.separate_processes");
2248        if (separateProcesses != null && separateProcesses.length() > 0) {
2249            if ("*".equals(separateProcesses)) {
2250                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2251                mSeparateProcesses = null;
2252                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2253            } else {
2254                mDefParseFlags = 0;
2255                mSeparateProcesses = separateProcesses.split(",");
2256                Slog.w(TAG, "Running with debug.separate_processes: "
2257                        + separateProcesses);
2258            }
2259        } else {
2260            mDefParseFlags = 0;
2261            mSeparateProcesses = null;
2262        }
2263
2264        mInstaller = installer;
2265        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2266                "*dexopt*");
2267        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2268        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2269
2270        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2271                FgThread.get().getLooper());
2272
2273        getDefaultDisplayMetrics(context, mMetrics);
2274
2275        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2276        SystemConfig systemConfig = SystemConfig.getInstance();
2277        mGlobalGids = systemConfig.getGlobalGids();
2278        mSystemPermissions = systemConfig.getSystemPermissions();
2279        mAvailableFeatures = systemConfig.getAvailableFeatures();
2280        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2281
2282        mProtectedPackages = new ProtectedPackages(mContext);
2283
2284        synchronized (mInstallLock) {
2285        // writer
2286        synchronized (mPackages) {
2287            mHandlerThread = new ServiceThread(TAG,
2288                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2289            mHandlerThread.start();
2290            mHandler = new PackageHandler(mHandlerThread.getLooper());
2291            mProcessLoggingHandler = new ProcessLoggingHandler();
2292            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2293
2294            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2295            mInstantAppRegistry = new InstantAppRegistry(this);
2296
2297            File dataDir = Environment.getDataDirectory();
2298            mAppInstallDir = new File(dataDir, "app");
2299            mAppLib32InstallDir = new File(dataDir, "app-lib");
2300            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2301            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2302            sUserManager = new UserManagerService(context, this,
2303                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2304
2305            // Propagate permission configuration in to package manager.
2306            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2307                    = systemConfig.getPermissions();
2308            for (int i=0; i<permConfig.size(); i++) {
2309                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2310                BasePermission bp = mSettings.mPermissions.get(perm.name);
2311                if (bp == null) {
2312                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2313                    mSettings.mPermissions.put(perm.name, bp);
2314                }
2315                if (perm.gids != null) {
2316                    bp.setGids(perm.gids, perm.perUser);
2317                }
2318            }
2319
2320            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2321            final int builtInLibCount = libConfig.size();
2322            for (int i = 0; i < builtInLibCount; i++) {
2323                String name = libConfig.keyAt(i);
2324                String path = libConfig.valueAt(i);
2325                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2326                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2327            }
2328
2329            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2330
2331            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2332            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2333            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2334
2335            // Clean up orphaned packages for which the code path doesn't exist
2336            // and they are an update to a system app - caused by bug/32321269
2337            final int packageSettingCount = mSettings.mPackages.size();
2338            for (int i = packageSettingCount - 1; i >= 0; i--) {
2339                PackageSetting ps = mSettings.mPackages.valueAt(i);
2340                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2341                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2342                    mSettings.mPackages.removeAt(i);
2343                    mSettings.enableSystemPackageLPw(ps.name);
2344                }
2345            }
2346
2347            if (mFirstBoot) {
2348                requestCopyPreoptedFiles();
2349            }
2350
2351            String customResolverActivity = Resources.getSystem().getString(
2352                    R.string.config_customResolverActivity);
2353            if (TextUtils.isEmpty(customResolverActivity)) {
2354                customResolverActivity = null;
2355            } else {
2356                mCustomResolverComponentName = ComponentName.unflattenFromString(
2357                        customResolverActivity);
2358            }
2359
2360            long startTime = SystemClock.uptimeMillis();
2361
2362            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2363                    startTime);
2364
2365            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2366            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2367
2368            if (bootClassPath == null) {
2369                Slog.w(TAG, "No BOOTCLASSPATH found!");
2370            }
2371
2372            if (systemServerClassPath == null) {
2373                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2374            }
2375
2376            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2377            final String[] dexCodeInstructionSets =
2378                    getDexCodeInstructionSets(
2379                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2380
2381            /**
2382             * Ensure all external libraries have had dexopt run on them.
2383             */
2384            if (mSharedLibraries.size() > 0) {
2385                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2386                // NOTE: For now, we're compiling these system "shared libraries"
2387                // (and framework jars) into all available architectures. It's possible
2388                // to compile them only when we come across an app that uses them (there's
2389                // already logic for that in scanPackageLI) but that adds some complexity.
2390                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2391                    final int libCount = mSharedLibraries.size();
2392                    for (int i = 0; i < libCount; i++) {
2393                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2394                        final int versionCount = versionedLib.size();
2395                        for (int j = 0; j < versionCount; j++) {
2396                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2397                            final String libPath = libEntry.path != null
2398                                    ? libEntry.path : libEntry.apk;
2399                            if (libPath == null) {
2400                                continue;
2401                            }
2402                            try {
2403                                // Shared libraries do not have profiles so we perform a full
2404                                // AOT compilation (if needed).
2405                                int dexoptNeeded = DexFile.getDexOptNeeded(
2406                                        libPath, dexCodeInstructionSet,
2407                                        getCompilerFilterForReason(REASON_SHARED_APK),
2408                                        false /* newProfile */);
2409                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2410                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2411                                            dexCodeInstructionSet, dexoptNeeded, null,
2412                                            DEXOPT_PUBLIC,
2413                                            getCompilerFilterForReason(REASON_SHARED_APK),
2414                                            StorageManager.UUID_PRIVATE_INTERNAL,
2415                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2416                                }
2417                            } catch (FileNotFoundException e) {
2418                                Slog.w(TAG, "Library not found: " + libPath);
2419                            } catch (IOException | InstallerException e) {
2420                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2421                                        + e.getMessage());
2422                            }
2423                        }
2424                    }
2425                }
2426                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2427            }
2428
2429            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2430
2431            final VersionInfo ver = mSettings.getInternalVersion();
2432            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2433
2434            // when upgrading from pre-M, promote system app permissions from install to runtime
2435            mPromoteSystemApps =
2436                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2437
2438            // When upgrading from pre-N, we need to handle package extraction like first boot,
2439            // as there is no profiling data available.
2440            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2441
2442            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2443
2444            // save off the names of pre-existing system packages prior to scanning; we don't
2445            // want to automatically grant runtime permissions for new system apps
2446            if (mPromoteSystemApps) {
2447                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2448                while (pkgSettingIter.hasNext()) {
2449                    PackageSetting ps = pkgSettingIter.next();
2450                    if (isSystemApp(ps)) {
2451                        mExistingSystemPackages.add(ps.name);
2452                    }
2453                }
2454            }
2455
2456            mCacheDir = preparePackageParserCache(mIsUpgrade);
2457
2458            // Set flag to monitor and not change apk file paths when
2459            // scanning install directories.
2460            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2461
2462            if (mIsUpgrade || mFirstBoot) {
2463                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2464            }
2465
2466            // Collect vendor overlay packages. (Do this before scanning any apps.)
2467            // For security and version matching reason, only consider
2468            // overlay packages if they reside in the right directory.
2469            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2470                    | PackageParser.PARSE_IS_SYSTEM
2471                    | PackageParser.PARSE_IS_SYSTEM_DIR
2472                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2473
2474            // Find base frameworks (resource packages without code).
2475            scanDirTracedLI(frameworkDir, mDefParseFlags
2476                    | PackageParser.PARSE_IS_SYSTEM
2477                    | PackageParser.PARSE_IS_SYSTEM_DIR
2478                    | PackageParser.PARSE_IS_PRIVILEGED,
2479                    scanFlags | SCAN_NO_DEX, 0);
2480
2481            // Collected privileged system packages.
2482            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2483            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2484                    | PackageParser.PARSE_IS_SYSTEM
2485                    | PackageParser.PARSE_IS_SYSTEM_DIR
2486                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2487
2488            // Collect ordinary system packages.
2489            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2490            scanDirTracedLI(systemAppDir, mDefParseFlags
2491                    | PackageParser.PARSE_IS_SYSTEM
2492                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2493
2494            // Collect all vendor packages.
2495            File vendorAppDir = new File("/vendor/app");
2496            try {
2497                vendorAppDir = vendorAppDir.getCanonicalFile();
2498            } catch (IOException e) {
2499                // failed to look up canonical path, continue with original one
2500            }
2501            scanDirTracedLI(vendorAppDir, mDefParseFlags
2502                    | PackageParser.PARSE_IS_SYSTEM
2503                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2504
2505            // Collect all OEM packages.
2506            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2507            scanDirTracedLI(oemAppDir, mDefParseFlags
2508                    | PackageParser.PARSE_IS_SYSTEM
2509                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2510
2511            // Prune any system packages that no longer exist.
2512            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2513            if (!mOnlyCore) {
2514                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2515                while (psit.hasNext()) {
2516                    PackageSetting ps = psit.next();
2517
2518                    /*
2519                     * If this is not a system app, it can't be a
2520                     * disable system app.
2521                     */
2522                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2523                        continue;
2524                    }
2525
2526                    /*
2527                     * If the package is scanned, it's not erased.
2528                     */
2529                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2530                    if (scannedPkg != null) {
2531                        /*
2532                         * If the system app is both scanned and in the
2533                         * disabled packages list, then it must have been
2534                         * added via OTA. Remove it from the currently
2535                         * scanned package so the previously user-installed
2536                         * application can be scanned.
2537                         */
2538                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2539                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2540                                    + ps.name + "; removing system app.  Last known codePath="
2541                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2542                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2543                                    + scannedPkg.mVersionCode);
2544                            removePackageLI(scannedPkg, true);
2545                            mExpectingBetter.put(ps.name, ps.codePath);
2546                        }
2547
2548                        continue;
2549                    }
2550
2551                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2552                        psit.remove();
2553                        logCriticalInfo(Log.WARN, "System package " + ps.name
2554                                + " no longer exists; it's data will be wiped");
2555                        // Actual deletion of code and data will be handled by later
2556                        // reconciliation step
2557                    } else {
2558                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2559                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2560                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2561                        }
2562                    }
2563                }
2564            }
2565
2566            //look for any incomplete package installations
2567            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2568            for (int i = 0; i < deletePkgsList.size(); i++) {
2569                // Actual deletion of code and data will be handled by later
2570                // reconciliation step
2571                final String packageName = deletePkgsList.get(i).name;
2572                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2573                synchronized (mPackages) {
2574                    mSettings.removePackageLPw(packageName);
2575                }
2576            }
2577
2578            //delete tmp files
2579            deleteTempPackageFiles();
2580
2581            // Remove any shared userIDs that have no associated packages
2582            mSettings.pruneSharedUsersLPw();
2583
2584            if (!mOnlyCore) {
2585                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2586                        SystemClock.uptimeMillis());
2587                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2588
2589                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2590                        | PackageParser.PARSE_FORWARD_LOCK,
2591                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2592
2593                /**
2594                 * Remove disable package settings for any updated system
2595                 * apps that were removed via an OTA. If they're not a
2596                 * previously-updated app, remove them completely.
2597                 * Otherwise, just revoke their system-level permissions.
2598                 */
2599                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2600                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2601                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2602
2603                    String msg;
2604                    if (deletedPkg == null) {
2605                        msg = "Updated system package " + deletedAppName
2606                                + " no longer exists; it's data will be wiped";
2607                        // Actual deletion of code and data will be handled by later
2608                        // reconciliation step
2609                    } else {
2610                        msg = "Updated system app + " + deletedAppName
2611                                + " no longer present; removing system privileges for "
2612                                + deletedAppName;
2613
2614                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2615
2616                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2617                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2618                    }
2619                    logCriticalInfo(Log.WARN, msg);
2620                }
2621
2622                /**
2623                 * Make sure all system apps that we expected to appear on
2624                 * the userdata partition actually showed up. If they never
2625                 * appeared, crawl back and revive the system version.
2626                 */
2627                for (int i = 0; i < mExpectingBetter.size(); i++) {
2628                    final String packageName = mExpectingBetter.keyAt(i);
2629                    if (!mPackages.containsKey(packageName)) {
2630                        final File scanFile = mExpectingBetter.valueAt(i);
2631
2632                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2633                                + " but never showed up; reverting to system");
2634
2635                        int reparseFlags = mDefParseFlags;
2636                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2637                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2638                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2639                                    | PackageParser.PARSE_IS_PRIVILEGED;
2640                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2641                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2642                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2643                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2644                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2645                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2646                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else {
2650                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2651                            continue;
2652                        }
2653
2654                        mSettings.enableSystemPackageLPw(packageName);
2655
2656                        try {
2657                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2658                        } catch (PackageManagerException e) {
2659                            Slog.e(TAG, "Failed to parse original system package: "
2660                                    + e.getMessage());
2661                        }
2662                    }
2663                }
2664            }
2665            mExpectingBetter.clear();
2666
2667            // Resolve the storage manager.
2668            mStorageManagerPackage = getStorageManagerPackageName();
2669
2670            // Resolve protected action filters. Only the setup wizard is allowed to
2671            // have a high priority filter for these actions.
2672            mSetupWizardPackage = getSetupWizardPackageName();
2673            if (mProtectedFilters.size() > 0) {
2674                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2675                    Slog.i(TAG, "No setup wizard;"
2676                        + " All protected intents capped to priority 0");
2677                }
2678                for (ActivityIntentInfo filter : mProtectedFilters) {
2679                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2680                        if (DEBUG_FILTERS) {
2681                            Slog.i(TAG, "Found setup wizard;"
2682                                + " allow priority " + filter.getPriority() + ";"
2683                                + " package: " + filter.activity.info.packageName
2684                                + " activity: " + filter.activity.className
2685                                + " priority: " + filter.getPriority());
2686                        }
2687                        // skip setup wizard; allow it to keep the high priority filter
2688                        continue;
2689                    }
2690                    Slog.w(TAG, "Protected action; cap priority to 0;"
2691                            + " package: " + filter.activity.info.packageName
2692                            + " activity: " + filter.activity.className
2693                            + " origPrio: " + filter.getPriority());
2694                    filter.setPriority(0);
2695                }
2696            }
2697            mDeferProtectedFilters = false;
2698            mProtectedFilters.clear();
2699
2700            // Now that we know all of the shared libraries, update all clients to have
2701            // the correct library paths.
2702            updateAllSharedLibrariesLPw(null);
2703
2704            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2705                // NOTE: We ignore potential failures here during a system scan (like
2706                // the rest of the commands above) because there's precious little we
2707                // can do about it. A settings error is reported, though.
2708                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2709            }
2710
2711            // Now that we know all the packages we are keeping,
2712            // read and update their last usage times.
2713            mPackageUsage.read(mPackages);
2714            mCompilerStats.read();
2715
2716            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2717                    SystemClock.uptimeMillis());
2718            Slog.i(TAG, "Time to scan packages: "
2719                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2720                    + " seconds");
2721
2722            // If the platform SDK has changed since the last time we booted,
2723            // we need to re-grant app permission to catch any new ones that
2724            // appear.  This is really a hack, and means that apps can in some
2725            // cases get permissions that the user didn't initially explicitly
2726            // allow...  it would be nice to have some better way to handle
2727            // this situation.
2728            int updateFlags = UPDATE_PERMISSIONS_ALL;
2729            if (ver.sdkVersion != mSdkVersion) {
2730                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2731                        + mSdkVersion + "; regranting permissions for internal storage");
2732                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2733            }
2734            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2735            ver.sdkVersion = mSdkVersion;
2736
2737            // If this is the first boot or an update from pre-M, and it is a normal
2738            // boot, then we need to initialize the default preferred apps across
2739            // all defined users.
2740            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2741                for (UserInfo user : sUserManager.getUsers(true)) {
2742                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2743                    applyFactoryDefaultBrowserLPw(user.id);
2744                    primeDomainVerificationsLPw(user.id);
2745                }
2746            }
2747
2748            // Prepare storage for system user really early during boot,
2749            // since core system apps like SettingsProvider and SystemUI
2750            // can't wait for user to start
2751            final int storageFlags;
2752            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2753                storageFlags = StorageManager.FLAG_STORAGE_DE;
2754            } else {
2755                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2756            }
2757            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2758                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2759                    true /* onlyCoreApps */);
2760            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2761                if (deferPackages == null || deferPackages.isEmpty()) {
2762                    return;
2763                }
2764                int count = 0;
2765                for (String pkgName : deferPackages) {
2766                    PackageParser.Package pkg = null;
2767                    synchronized (mPackages) {
2768                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2769                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2770                            pkg = ps.pkg;
2771                        }
2772                    }
2773                    if (pkg != null) {
2774                        synchronized (mInstallLock) {
2775                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2776                                    true /* maybeMigrateAppData */);
2777                        }
2778                        count++;
2779                    }
2780                }
2781                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2782            }, "prepareAppData");
2783
2784            // If this is first boot after an OTA, and a normal boot, then
2785            // we need to clear code cache directories.
2786            // Note that we do *not* clear the application profiles. These remain valid
2787            // across OTAs and are used to drive profile verification (post OTA) and
2788            // profile compilation (without waiting to collect a fresh set of profiles).
2789            if (mIsUpgrade && !onlyCore) {
2790                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2791                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2792                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2793                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2794                        // No apps are running this early, so no need to freeze
2795                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2796                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2797                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2798                    }
2799                }
2800                ver.fingerprint = Build.FINGERPRINT;
2801            }
2802
2803            checkDefaultBrowser();
2804
2805            // clear only after permissions and other defaults have been updated
2806            mExistingSystemPackages.clear();
2807            mPromoteSystemApps = false;
2808
2809            // All the changes are done during package scanning.
2810            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2811
2812            // can downgrade to reader
2813            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2814            mSettings.writeLPr();
2815            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2816
2817            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2818            // early on (before the package manager declares itself as early) because other
2819            // components in the system server might ask for package contexts for these apps.
2820            //
2821            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2822            // (i.e, that the data partition is unavailable).
2823            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2824                long start = System.nanoTime();
2825                List<PackageParser.Package> coreApps = new ArrayList<>();
2826                for (PackageParser.Package pkg : mPackages.values()) {
2827                    if (pkg.coreApp) {
2828                        coreApps.add(pkg);
2829                    }
2830                }
2831
2832                int[] stats = performDexOptUpgrade(coreApps, false,
2833                        getCompilerFilterForReason(REASON_CORE_APP));
2834
2835                final int elapsedTimeSeconds =
2836                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2837                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2838
2839                if (DEBUG_DEXOPT) {
2840                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2841                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2842                }
2843
2844
2845                // TODO: Should we log these stats to tron too ?
2846                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2847                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2848                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2849                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2850            }
2851
2852            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2853                    SystemClock.uptimeMillis());
2854
2855            if (!mOnlyCore) {
2856                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2857                mRequiredInstallerPackage = getRequiredInstallerLPr();
2858                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2859                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2860                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2861                        mIntentFilterVerifierComponent);
2862                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2863                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2864                        SharedLibraryInfo.VERSION_UNDEFINED);
2865                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2866                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2867                        SharedLibraryInfo.VERSION_UNDEFINED);
2868            } else {
2869                mRequiredVerifierPackage = null;
2870                mRequiredInstallerPackage = null;
2871                mRequiredUninstallerPackage = null;
2872                mIntentFilterVerifierComponent = null;
2873                mIntentFilterVerifier = null;
2874                mServicesSystemSharedLibraryPackageName = null;
2875                mSharedSystemSharedLibraryPackageName = null;
2876            }
2877
2878            mInstallerService = new PackageInstallerService(context, this);
2879
2880            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2881            if (ephemeralResolverComponent != null) {
2882                if (DEBUG_EPHEMERAL) {
2883                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2884                }
2885                mInstantAppResolverConnection =
2886                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2887            } else {
2888                mInstantAppResolverConnection = null;
2889            }
2890            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2891            if (mInstantAppInstallerComponent != null) {
2892                if (DEBUG_EPHEMERAL) {
2893                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2894                }
2895                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2896            }
2897
2898            // Read and update the usage of dex files.
2899            // Do this at the end of PM init so that all the packages have their
2900            // data directory reconciled.
2901            // At this point we know the code paths of the packages, so we can validate
2902            // the disk file and build the internal cache.
2903            // The usage file is expected to be small so loading and verifying it
2904            // should take a fairly small time compare to the other activities (e.g. package
2905            // scanning).
2906            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2907            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2908            for (int userId : currentUserIds) {
2909                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2910            }
2911            mDexManager.load(userPackages);
2912        } // synchronized (mPackages)
2913        } // synchronized (mInstallLock)
2914
2915        // Now after opening every single application zip, make sure they
2916        // are all flushed.  Not really needed, but keeps things nice and
2917        // tidy.
2918        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2919        Runtime.getRuntime().gc();
2920        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2921
2922        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2923        FallbackCategoryProvider.loadFallbacks();
2924        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2925
2926        // The initial scanning above does many calls into installd while
2927        // holding the mPackages lock, but we're mostly interested in yelling
2928        // once we have a booted system.
2929        mInstaller.setWarnIfHeld(mPackages);
2930
2931        // Expose private service for system components to use.
2932        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2933        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2934    }
2935
2936    private static File preparePackageParserCache(boolean isUpgrade) {
2937        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2938            return null;
2939        }
2940
2941        // Disable package parsing on eng builds to allow for faster incremental development.
2942        if ("eng".equals(Build.TYPE)) {
2943            return null;
2944        }
2945
2946        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2947            Slog.i(TAG, "Disabling package parser cache due to system property.");
2948            return null;
2949        }
2950
2951        // The base directory for the package parser cache lives under /data/system/.
2952        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2953                "package_cache");
2954        if (cacheBaseDir == null) {
2955            return null;
2956        }
2957
2958        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2959        // This also serves to "GC" unused entries when the package cache version changes (which
2960        // can only happen during upgrades).
2961        if (isUpgrade) {
2962            FileUtils.deleteContents(cacheBaseDir);
2963        }
2964
2965
2966        // Return the versioned package cache directory. This is something like
2967        // "/data/system/package_cache/1"
2968        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2969
2970        // The following is a workaround to aid development on non-numbered userdebug
2971        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2972        // the system partition is newer.
2973        //
2974        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2975        // that starts with "eng." to signify that this is an engineering build and not
2976        // destined for release.
2977        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2978            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2979
2980            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2981            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2982            // in general and should not be used for production changes. In this specific case,
2983            // we know that they will work.
2984            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2985            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2986                FileUtils.deleteContents(cacheBaseDir);
2987                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2988            }
2989        }
2990
2991        return cacheDir;
2992    }
2993
2994    @Override
2995    public boolean isFirstBoot() {
2996        return mFirstBoot;
2997    }
2998
2999    @Override
3000    public boolean isOnlyCoreApps() {
3001        return mOnlyCore;
3002    }
3003
3004    @Override
3005    public boolean isUpgrade() {
3006        return mIsUpgrade;
3007    }
3008
3009    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3010        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3011
3012        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3013                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3014                UserHandle.USER_SYSTEM);
3015        if (matches.size() == 1) {
3016            return matches.get(0).getComponentInfo().packageName;
3017        } else if (matches.size() == 0) {
3018            Log.e(TAG, "There should probably be a verifier, but, none were found");
3019            return null;
3020        }
3021        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3022    }
3023
3024    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3025        synchronized (mPackages) {
3026            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3027            if (libraryEntry == null) {
3028                throw new IllegalStateException("Missing required shared library:" + name);
3029            }
3030            return libraryEntry.apk;
3031        }
3032    }
3033
3034    private @NonNull String getRequiredInstallerLPr() {
3035        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3036        intent.addCategory(Intent.CATEGORY_DEFAULT);
3037        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3038
3039        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3040                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3041                UserHandle.USER_SYSTEM);
3042        if (matches.size() == 1) {
3043            ResolveInfo resolveInfo = matches.get(0);
3044            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3045                throw new RuntimeException("The installer must be a privileged app");
3046            }
3047            return matches.get(0).getComponentInfo().packageName;
3048        } else {
3049            throw new RuntimeException("There must be exactly one installer; found " + matches);
3050        }
3051    }
3052
3053    private @NonNull String getRequiredUninstallerLPr() {
3054        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3055        intent.addCategory(Intent.CATEGORY_DEFAULT);
3056        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3057
3058        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3059                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3060                UserHandle.USER_SYSTEM);
3061        if (resolveInfo == null ||
3062                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3063            throw new RuntimeException("There must be exactly one uninstaller; found "
3064                    + resolveInfo);
3065        }
3066        return resolveInfo.getComponentInfo().packageName;
3067    }
3068
3069    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3070        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3071
3072        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3073                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3074                UserHandle.USER_SYSTEM);
3075        ResolveInfo best = null;
3076        final int N = matches.size();
3077        for (int i = 0; i < N; i++) {
3078            final ResolveInfo cur = matches.get(i);
3079            final String packageName = cur.getComponentInfo().packageName;
3080            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3081                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3082                continue;
3083            }
3084
3085            if (best == null || cur.priority > best.priority) {
3086                best = cur;
3087            }
3088        }
3089
3090        if (best != null) {
3091            return best.getComponentInfo().getComponentName();
3092        } else {
3093            throw new RuntimeException("There must be at least one intent filter verifier");
3094        }
3095    }
3096
3097    private @Nullable ComponentName getEphemeralResolverLPr() {
3098        final String[] packageArray =
3099                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3100        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3101            if (DEBUG_EPHEMERAL) {
3102                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3103            }
3104            return null;
3105        }
3106
3107        final int resolveFlags =
3108                MATCH_DIRECT_BOOT_AWARE
3109                | MATCH_DIRECT_BOOT_UNAWARE
3110                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3111        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3112        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3113                resolveFlags, UserHandle.USER_SYSTEM);
3114
3115        final int N = resolvers.size();
3116        if (N == 0) {
3117            if (DEBUG_EPHEMERAL) {
3118                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3119            }
3120            return null;
3121        }
3122
3123        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3124        for (int i = 0; i < N; i++) {
3125            final ResolveInfo info = resolvers.get(i);
3126
3127            if (info.serviceInfo == null) {
3128                continue;
3129            }
3130
3131            final String packageName = info.serviceInfo.packageName;
3132            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3133                if (DEBUG_EPHEMERAL) {
3134                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3135                            + " pkg: " + packageName + ", info:" + info);
3136                }
3137                continue;
3138            }
3139
3140            if (DEBUG_EPHEMERAL) {
3141                Slog.v(TAG, "Ephemeral resolver found;"
3142                        + " pkg: " + packageName + ", info:" + info);
3143            }
3144            return new ComponentName(packageName, info.serviceInfo.name);
3145        }
3146        if (DEBUG_EPHEMERAL) {
3147            Slog.v(TAG, "Ephemeral resolver NOT found");
3148        }
3149        return null;
3150    }
3151
3152    private @Nullable ComponentName getEphemeralInstallerLPr() {
3153        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3154        intent.addCategory(Intent.CATEGORY_DEFAULT);
3155        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3156
3157        final int resolveFlags =
3158                MATCH_DIRECT_BOOT_AWARE
3159                | MATCH_DIRECT_BOOT_UNAWARE
3160                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3161        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3162                resolveFlags, UserHandle.USER_SYSTEM);
3163        Iterator<ResolveInfo> iter = matches.iterator();
3164        while (iter.hasNext()) {
3165            final ResolveInfo rInfo = iter.next();
3166            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3167            if (ps != null) {
3168                final PermissionsState permissionsState = ps.getPermissionsState();
3169                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3170                    continue;
3171                }
3172            }
3173            iter.remove();
3174        }
3175        if (matches.size() == 0) {
3176            return null;
3177        } else if (matches.size() == 1) {
3178            return matches.get(0).getComponentInfo().getComponentName();
3179        } else {
3180            throw new RuntimeException(
3181                    "There must be at most one ephemeral installer; found " + matches);
3182        }
3183    }
3184
3185    private void primeDomainVerificationsLPw(int userId) {
3186        if (DEBUG_DOMAIN_VERIFICATION) {
3187            Slog.d(TAG, "Priming domain verifications in user " + userId);
3188        }
3189
3190        SystemConfig systemConfig = SystemConfig.getInstance();
3191        ArraySet<String> packages = systemConfig.getLinkedApps();
3192
3193        for (String packageName : packages) {
3194            PackageParser.Package pkg = mPackages.get(packageName);
3195            if (pkg != null) {
3196                if (!pkg.isSystemApp()) {
3197                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3198                    continue;
3199                }
3200
3201                ArraySet<String> domains = null;
3202                for (PackageParser.Activity a : pkg.activities) {
3203                    for (ActivityIntentInfo filter : a.intents) {
3204                        if (hasValidDomains(filter)) {
3205                            if (domains == null) {
3206                                domains = new ArraySet<String>();
3207                            }
3208                            domains.addAll(filter.getHostsList());
3209                        }
3210                    }
3211                }
3212
3213                if (domains != null && domains.size() > 0) {
3214                    if (DEBUG_DOMAIN_VERIFICATION) {
3215                        Slog.v(TAG, "      + " + packageName);
3216                    }
3217                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3218                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3219                    // and then 'always' in the per-user state actually used for intent resolution.
3220                    final IntentFilterVerificationInfo ivi;
3221                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3222                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3223                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3224                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3225                } else {
3226                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3227                            + "' does not handle web links");
3228                }
3229            } else {
3230                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3231            }
3232        }
3233
3234        scheduleWritePackageRestrictionsLocked(userId);
3235        scheduleWriteSettingsLocked();
3236    }
3237
3238    private void applyFactoryDefaultBrowserLPw(int userId) {
3239        // The default browser app's package name is stored in a string resource,
3240        // with a product-specific overlay used for vendor customization.
3241        String browserPkg = mContext.getResources().getString(
3242                com.android.internal.R.string.default_browser);
3243        if (!TextUtils.isEmpty(browserPkg)) {
3244            // non-empty string => required to be a known package
3245            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3246            if (ps == null) {
3247                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3248                browserPkg = null;
3249            } else {
3250                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3251            }
3252        }
3253
3254        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3255        // default.  If there's more than one, just leave everything alone.
3256        if (browserPkg == null) {
3257            calculateDefaultBrowserLPw(userId);
3258        }
3259    }
3260
3261    private void calculateDefaultBrowserLPw(int userId) {
3262        List<String> allBrowsers = resolveAllBrowserApps(userId);
3263        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3264        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3265    }
3266
3267    private List<String> resolveAllBrowserApps(int userId) {
3268        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3269        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3270                PackageManager.MATCH_ALL, userId);
3271
3272        final int count = list.size();
3273        List<String> result = new ArrayList<String>(count);
3274        for (int i=0; i<count; i++) {
3275            ResolveInfo info = list.get(i);
3276            if (info.activityInfo == null
3277                    || !info.handleAllWebDataURI
3278                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3279                    || result.contains(info.activityInfo.packageName)) {
3280                continue;
3281            }
3282            result.add(info.activityInfo.packageName);
3283        }
3284
3285        return result;
3286    }
3287
3288    private boolean packageIsBrowser(String packageName, int userId) {
3289        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3290                PackageManager.MATCH_ALL, userId);
3291        final int N = list.size();
3292        for (int i = 0; i < N; i++) {
3293            ResolveInfo info = list.get(i);
3294            if (packageName.equals(info.activityInfo.packageName)) {
3295                return true;
3296            }
3297        }
3298        return false;
3299    }
3300
3301    private void checkDefaultBrowser() {
3302        final int myUserId = UserHandle.myUserId();
3303        final String packageName = getDefaultBrowserPackageName(myUserId);
3304        if (packageName != null) {
3305            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3306            if (info == null) {
3307                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3308                synchronized (mPackages) {
3309                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3310                }
3311            }
3312        }
3313    }
3314
3315    @Override
3316    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3317            throws RemoteException {
3318        try {
3319            return super.onTransact(code, data, reply, flags);
3320        } catch (RuntimeException e) {
3321            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3322                Slog.wtf(TAG, "Package Manager Crash", e);
3323            }
3324            throw e;
3325        }
3326    }
3327
3328    static int[] appendInts(int[] cur, int[] add) {
3329        if (add == null) return cur;
3330        if (cur == null) return add;
3331        final int N = add.length;
3332        for (int i=0; i<N; i++) {
3333            cur = appendInt(cur, add[i]);
3334        }
3335        return cur;
3336    }
3337
3338    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3339        if (!sUserManager.exists(userId)) return null;
3340        if (ps == null) {
3341            return null;
3342        }
3343        final PackageParser.Package p = ps.pkg;
3344        if (p == null) {
3345            return null;
3346        }
3347        // Filter out ephemeral app metadata:
3348        //   * The system/shell/root can see metadata for any app
3349        //   * An installed app can see metadata for 1) other installed apps
3350        //     and 2) ephemeral apps that have explicitly interacted with it
3351        //   * Ephemeral apps can only see their own metadata
3352        //   * Holding a signature permission allows seeing instant apps
3353        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3354        if (callingAppId != Process.SYSTEM_UID
3355                && callingAppId != Process.SHELL_UID
3356                && callingAppId != Process.ROOT_UID
3357                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3358                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3359            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3360            if (instantAppPackageName != null) {
3361                // ephemeral apps can only get information on themselves
3362                if (!instantAppPackageName.equals(p.packageName)) {
3363                    return null;
3364                }
3365            } else {
3366                if (ps.getInstantApp(userId)) {
3367                    // only get access to the ephemeral app if we've been granted access
3368                    if (!mInstantAppRegistry.isInstantAccessGranted(
3369                            userId, callingAppId, ps.appId)) {
3370                        return null;
3371                    }
3372                }
3373            }
3374        }
3375
3376        final PermissionsState permissionsState = ps.getPermissionsState();
3377
3378        // Compute GIDs only if requested
3379        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3380                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3381        // Compute granted permissions only if package has requested permissions
3382        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3383                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3384        final PackageUserState state = ps.readUserState(userId);
3385
3386        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3387                && ps.isSystem()) {
3388            flags |= MATCH_ANY_USER;
3389        }
3390
3391        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3392                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3393
3394        if (packageInfo == null) {
3395            return null;
3396        }
3397
3398        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3399
3400        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3401                resolveExternalPackageNameLPr(p);
3402
3403        return packageInfo;
3404    }
3405
3406    @Override
3407    public void checkPackageStartable(String packageName, int userId) {
3408        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3409
3410        synchronized (mPackages) {
3411            final PackageSetting ps = mSettings.mPackages.get(packageName);
3412            if (ps == null) {
3413                throw new SecurityException("Package " + packageName + " was not found!");
3414            }
3415
3416            if (!ps.getInstalled(userId)) {
3417                throw new SecurityException(
3418                        "Package " + packageName + " was not installed for user " + userId + "!");
3419            }
3420
3421            if (mSafeMode && !ps.isSystem()) {
3422                throw new SecurityException("Package " + packageName + " not a system app!");
3423            }
3424
3425            if (mFrozenPackages.contains(packageName)) {
3426                throw new SecurityException("Package " + packageName + " is currently frozen!");
3427            }
3428
3429            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3430                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3431                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3432            }
3433        }
3434    }
3435
3436    @Override
3437    public boolean isPackageAvailable(String packageName, int userId) {
3438        if (!sUserManager.exists(userId)) return false;
3439        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3440                false /* requireFullPermission */, false /* checkShell */, "is package available");
3441        synchronized (mPackages) {
3442            PackageParser.Package p = mPackages.get(packageName);
3443            if (p != null) {
3444                final PackageSetting ps = (PackageSetting) p.mExtras;
3445                if (ps != null) {
3446                    final PackageUserState state = ps.readUserState(userId);
3447                    if (state != null) {
3448                        return PackageParser.isAvailable(state);
3449                    }
3450                }
3451            }
3452        }
3453        return false;
3454    }
3455
3456    @Override
3457    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3458        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3459                flags, userId);
3460    }
3461
3462    @Override
3463    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3464            int flags, int userId) {
3465        return getPackageInfoInternal(versionedPackage.getPackageName(),
3466                // TODO: We will change version code to long, so in the new API it is long
3467                (int) versionedPackage.getVersionCode(), flags, userId);
3468    }
3469
3470    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3471            int flags, int userId) {
3472        if (!sUserManager.exists(userId)) return null;
3473        flags = updateFlagsForPackage(flags, userId, packageName);
3474        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3475                false /* requireFullPermission */, false /* checkShell */, "get package info");
3476
3477        // reader
3478        synchronized (mPackages) {
3479            // Normalize package name to handle renamed packages and static libs
3480            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3481
3482            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3483            if (matchFactoryOnly) {
3484                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3485                if (ps != null) {
3486                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3487                        return null;
3488                    }
3489                    return generatePackageInfo(ps, flags, userId);
3490                }
3491            }
3492
3493            PackageParser.Package p = mPackages.get(packageName);
3494            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3495                return null;
3496            }
3497            if (DEBUG_PACKAGE_INFO)
3498                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3499            if (p != null) {
3500                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3501                        Binder.getCallingUid(), userId)) {
3502                    return null;
3503                }
3504                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3505            }
3506            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3507                final PackageSetting ps = mSettings.mPackages.get(packageName);
3508                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3509                    return null;
3510                }
3511                return generatePackageInfo(ps, flags, userId);
3512            }
3513        }
3514        return null;
3515    }
3516
3517
3518    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3519        // System/shell/root get to see all static libs
3520        final int appId = UserHandle.getAppId(uid);
3521        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3522                || appId == Process.ROOT_UID) {
3523            return false;
3524        }
3525
3526        // No package means no static lib as it is always on internal storage
3527        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3528            return false;
3529        }
3530
3531        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3532                ps.pkg.staticSharedLibVersion);
3533        if (libEntry == null) {
3534            return false;
3535        }
3536
3537        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3538        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3539        if (uidPackageNames == null) {
3540            return true;
3541        }
3542
3543        for (String uidPackageName : uidPackageNames) {
3544            if (ps.name.equals(uidPackageName)) {
3545                return false;
3546            }
3547            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3548            if (uidPs != null) {
3549                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3550                        libEntry.info.getName());
3551                if (index < 0) {
3552                    continue;
3553                }
3554                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3555                    return false;
3556                }
3557            }
3558        }
3559        return true;
3560    }
3561
3562    @Override
3563    public String[] currentToCanonicalPackageNames(String[] names) {
3564        String[] out = new String[names.length];
3565        // reader
3566        synchronized (mPackages) {
3567            for (int i=names.length-1; i>=0; i--) {
3568                PackageSetting ps = mSettings.mPackages.get(names[i]);
3569                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3570            }
3571        }
3572        return out;
3573    }
3574
3575    @Override
3576    public String[] canonicalToCurrentPackageNames(String[] names) {
3577        String[] out = new String[names.length];
3578        // reader
3579        synchronized (mPackages) {
3580            for (int i=names.length-1; i>=0; i--) {
3581                String cur = mSettings.getRenamedPackageLPr(names[i]);
3582                out[i] = cur != null ? cur : names[i];
3583            }
3584        }
3585        return out;
3586    }
3587
3588    @Override
3589    public int getPackageUid(String packageName, int flags, int userId) {
3590        if (!sUserManager.exists(userId)) return -1;
3591        flags = updateFlagsForPackage(flags, userId, packageName);
3592        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3593                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3594
3595        // reader
3596        synchronized (mPackages) {
3597            final PackageParser.Package p = mPackages.get(packageName);
3598            if (p != null && p.isMatch(flags)) {
3599                return UserHandle.getUid(userId, p.applicationInfo.uid);
3600            }
3601            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3602                final PackageSetting ps = mSettings.mPackages.get(packageName);
3603                if (ps != null && ps.isMatch(flags)) {
3604                    return UserHandle.getUid(userId, ps.appId);
3605                }
3606            }
3607        }
3608
3609        return -1;
3610    }
3611
3612    @Override
3613    public int[] getPackageGids(String packageName, int flags, int userId) {
3614        if (!sUserManager.exists(userId)) return null;
3615        flags = updateFlagsForPackage(flags, userId, packageName);
3616        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3617                false /* requireFullPermission */, false /* checkShell */,
3618                "getPackageGids");
3619
3620        // reader
3621        synchronized (mPackages) {
3622            final PackageParser.Package p = mPackages.get(packageName);
3623            if (p != null && p.isMatch(flags)) {
3624                PackageSetting ps = (PackageSetting) p.mExtras;
3625                // TODO: Shouldn't this be checking for package installed state for userId and
3626                // return null?
3627                return ps.getPermissionsState().computeGids(userId);
3628            }
3629            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3630                final PackageSetting ps = mSettings.mPackages.get(packageName);
3631                if (ps != null && ps.isMatch(flags)) {
3632                    return ps.getPermissionsState().computeGids(userId);
3633                }
3634            }
3635        }
3636
3637        return null;
3638    }
3639
3640    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3641        if (bp.perm != null) {
3642            return PackageParser.generatePermissionInfo(bp.perm, flags);
3643        }
3644        PermissionInfo pi = new PermissionInfo();
3645        pi.name = bp.name;
3646        pi.packageName = bp.sourcePackage;
3647        pi.nonLocalizedLabel = bp.name;
3648        pi.protectionLevel = bp.protectionLevel;
3649        return pi;
3650    }
3651
3652    @Override
3653    public PermissionInfo getPermissionInfo(String name, int flags) {
3654        // reader
3655        synchronized (mPackages) {
3656            final BasePermission p = mSettings.mPermissions.get(name);
3657            if (p != null) {
3658                return generatePermissionInfo(p, flags);
3659            }
3660            return null;
3661        }
3662    }
3663
3664    @Override
3665    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3666            int flags) {
3667        // reader
3668        synchronized (mPackages) {
3669            if (group != null && !mPermissionGroups.containsKey(group)) {
3670                // This is thrown as NameNotFoundException
3671                return null;
3672            }
3673
3674            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3675            for (BasePermission p : mSettings.mPermissions.values()) {
3676                if (group == null) {
3677                    if (p.perm == null || p.perm.info.group == null) {
3678                        out.add(generatePermissionInfo(p, flags));
3679                    }
3680                } else {
3681                    if (p.perm != null && group.equals(p.perm.info.group)) {
3682                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3683                    }
3684                }
3685            }
3686            return new ParceledListSlice<>(out);
3687        }
3688    }
3689
3690    @Override
3691    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3692        // reader
3693        synchronized (mPackages) {
3694            return PackageParser.generatePermissionGroupInfo(
3695                    mPermissionGroups.get(name), flags);
3696        }
3697    }
3698
3699    @Override
3700    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3701        // reader
3702        synchronized (mPackages) {
3703            final int N = mPermissionGroups.size();
3704            ArrayList<PermissionGroupInfo> out
3705                    = new ArrayList<PermissionGroupInfo>(N);
3706            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3707                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3708            }
3709            return new ParceledListSlice<>(out);
3710        }
3711    }
3712
3713    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3714            int uid, int userId) {
3715        if (!sUserManager.exists(userId)) return null;
3716        PackageSetting ps = mSettings.mPackages.get(packageName);
3717        if (ps != null) {
3718            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3719                return null;
3720            }
3721            if (ps.pkg == null) {
3722                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3723                if (pInfo != null) {
3724                    return pInfo.applicationInfo;
3725                }
3726                return null;
3727            }
3728            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3729                    ps.readUserState(userId), userId);
3730            if (ai != null) {
3731                rebaseEnabledOverlays(ai, userId);
3732                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3733            }
3734            return ai;
3735        }
3736        return null;
3737    }
3738
3739    @Override
3740    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3741        if (!sUserManager.exists(userId)) return null;
3742        flags = updateFlagsForApplication(flags, userId, packageName);
3743        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3744                false /* requireFullPermission */, false /* checkShell */, "get application info");
3745
3746        // writer
3747        synchronized (mPackages) {
3748            // Normalize package name to handle renamed packages and static libs
3749            packageName = resolveInternalPackageNameLPr(packageName,
3750                    PackageManager.VERSION_CODE_HIGHEST);
3751
3752            PackageParser.Package p = mPackages.get(packageName);
3753            if (DEBUG_PACKAGE_INFO) Log.v(
3754                    TAG, "getApplicationInfo " + packageName
3755                    + ": " + p);
3756            if (p != null) {
3757                PackageSetting ps = mSettings.mPackages.get(packageName);
3758                if (ps == null) return null;
3759                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3760                    return null;
3761                }
3762                // Note: isEnabledLP() does not apply here - always return info
3763                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3764                        p, flags, ps.readUserState(userId), userId);
3765                if (ai != null) {
3766                    rebaseEnabledOverlays(ai, userId);
3767                    ai.packageName = resolveExternalPackageNameLPr(p);
3768                }
3769                return ai;
3770            }
3771            if ("android".equals(packageName)||"system".equals(packageName)) {
3772                return mAndroidApplication;
3773            }
3774            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3775                // Already generates the external package name
3776                return generateApplicationInfoFromSettingsLPw(packageName,
3777                        Binder.getCallingUid(), flags, userId);
3778            }
3779        }
3780        return null;
3781    }
3782
3783    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3784        List<String> paths = new ArrayList<>();
3785        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3786            mEnabledOverlayPaths.get(userId);
3787        if (userSpecificOverlays != null) {
3788            if (!"android".equals(ai.packageName)) {
3789                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3790                if (frameworkOverlays != null) {
3791                    paths.addAll(frameworkOverlays);
3792                }
3793            }
3794
3795            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3796            if (appOverlays != null) {
3797                paths.addAll(appOverlays);
3798            }
3799        }
3800        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3801    }
3802
3803    private String normalizePackageNameLPr(String packageName) {
3804        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3805        return normalizedPackageName != null ? normalizedPackageName : packageName;
3806    }
3807
3808    @Override
3809    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3810            final IPackageDataObserver observer) {
3811        mContext.enforceCallingOrSelfPermission(
3812                android.Manifest.permission.CLEAR_APP_CACHE, null);
3813        mHandler.post(() -> {
3814            boolean success = false;
3815            try {
3816                freeStorage(volumeUuid, freeStorageSize, 0);
3817                success = true;
3818            } catch (IOException e) {
3819                Slog.w(TAG, e);
3820            }
3821            if (observer != null) {
3822                try {
3823                    observer.onRemoveCompleted(null, success);
3824                } catch (RemoteException e) {
3825                    Slog.w(TAG, e);
3826                }
3827            }
3828        });
3829    }
3830
3831    @Override
3832    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3833            final IntentSender pi) {
3834        mContext.enforceCallingOrSelfPermission(
3835                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3836        mHandler.post(() -> {
3837            boolean success = false;
3838            try {
3839                freeStorage(volumeUuid, freeStorageSize, 0);
3840                success = true;
3841            } catch (IOException e) {
3842                Slog.w(TAG, e);
3843            }
3844            if (pi != null) {
3845                try {
3846                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3847                } catch (SendIntentException e) {
3848                    Slog.w(TAG, e);
3849                }
3850            }
3851        });
3852    }
3853
3854    /**
3855     * Blocking call to clear various types of cached data across the system
3856     * until the requested bytes are available.
3857     */
3858    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3859        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3860        final File file = storage.findPathForUuid(volumeUuid);
3861
3862        if (ENABLE_FREE_CACHE_V2) {
3863            final boolean aggressive = (storageFlags
3864                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3865
3866            // 1. Pre-flight to determine if we have any chance to succeed
3867            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3868
3869            // 3. Consider parsed APK data (aggressive only)
3870            if (aggressive) {
3871                FileUtils.deleteContents(mCacheDir);
3872            }
3873            if (file.getUsableSpace() >= bytes) return;
3874
3875            // 4. Consider cached app data (above quotas)
3876            try {
3877                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3878            } catch (InstallerException ignored) {
3879            }
3880            if (file.getUsableSpace() >= bytes) return;
3881
3882            // 5. Consider shared libraries with refcount=0 and age>2h
3883            // 6. Consider dexopt output (aggressive only)
3884            // 7. Consider ephemeral apps not used in last week
3885
3886            // 8. Consider cached app data (below quotas)
3887            try {
3888                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3889                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3890            } catch (InstallerException ignored) {
3891            }
3892            if (file.getUsableSpace() >= bytes) return;
3893
3894            // 9. Consider DropBox entries
3895            // 10. Consider ephemeral cookies
3896
3897        } else {
3898            try {
3899                mInstaller.freeCache(volumeUuid, bytes, 0);
3900            } catch (InstallerException ignored) {
3901            }
3902            if (file.getUsableSpace() >= bytes) return;
3903        }
3904
3905        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3906    }
3907
3908    /**
3909     * Update given flags based on encryption status of current user.
3910     */
3911    private int updateFlags(int flags, int userId) {
3912        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3913                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3914            // Caller expressed an explicit opinion about what encryption
3915            // aware/unaware components they want to see, so fall through and
3916            // give them what they want
3917        } else {
3918            // Caller expressed no opinion, so match based on user state
3919            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3920                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3921            } else {
3922                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3923            }
3924        }
3925        return flags;
3926    }
3927
3928    private UserManagerInternal getUserManagerInternal() {
3929        if (mUserManagerInternal == null) {
3930            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3931        }
3932        return mUserManagerInternal;
3933    }
3934
3935    private DeviceIdleController.LocalService getDeviceIdleController() {
3936        if (mDeviceIdleController == null) {
3937            mDeviceIdleController =
3938                    LocalServices.getService(DeviceIdleController.LocalService.class);
3939        }
3940        return mDeviceIdleController;
3941    }
3942
3943    /**
3944     * Update given flags when being used to request {@link PackageInfo}.
3945     */
3946    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3947        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3948        boolean triaged = true;
3949        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3950                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3951            // Caller is asking for component details, so they'd better be
3952            // asking for specific encryption matching behavior, or be triaged
3953            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3954                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3955                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3956                triaged = false;
3957            }
3958        }
3959        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3960                | PackageManager.MATCH_SYSTEM_ONLY
3961                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3962            triaged = false;
3963        }
3964        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3965            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3966                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3967                    + Debug.getCallers(5));
3968        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3969                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3970            // If the caller wants all packages and has a restricted profile associated with it,
3971            // then match all users. This is to make sure that launchers that need to access work
3972            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3973            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3974            flags |= PackageManager.MATCH_ANY_USER;
3975        }
3976        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3977            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3978                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3979        }
3980        return updateFlags(flags, userId);
3981    }
3982
3983    /**
3984     * Update given flags when being used to request {@link ApplicationInfo}.
3985     */
3986    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3987        return updateFlagsForPackage(flags, userId, cookie);
3988    }
3989
3990    /**
3991     * Update given flags when being used to request {@link ComponentInfo}.
3992     */
3993    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3994        if (cookie instanceof Intent) {
3995            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3996                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3997            }
3998        }
3999
4000        boolean triaged = true;
4001        // Caller is asking for component details, so they'd better be
4002        // asking for specific encryption matching behavior, or be triaged
4003        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4004                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4005                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4006            triaged = false;
4007        }
4008        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4009            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4010                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4011        }
4012
4013        return updateFlags(flags, userId);
4014    }
4015
4016    /**
4017     * Update given intent when being used to request {@link ResolveInfo}.
4018     */
4019    private Intent updateIntentForResolve(Intent intent) {
4020        if (intent.getSelector() != null) {
4021            intent = intent.getSelector();
4022        }
4023        if (DEBUG_PREFERRED) {
4024            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4025        }
4026        return intent;
4027    }
4028
4029    /**
4030     * Update given flags when being used to request {@link ResolveInfo}.
4031     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4032     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4033     * flag set. However, this flag is only honoured in three circumstances:
4034     * <ul>
4035     * <li>when called from a system process</li>
4036     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4037     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4038     * action and a {@code android.intent.category.BROWSABLE} category</li>
4039     * </ul>
4040     */
4041    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4042        // Safe mode means we shouldn't match any third-party components
4043        if (mSafeMode) {
4044            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4045        }
4046        final int callingUid = Binder.getCallingUid();
4047        if (getInstantAppPackageName(callingUid) != null) {
4048            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4049            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4050            flags |= PackageManager.MATCH_INSTANT;
4051        } else {
4052            // Otherwise, prevent leaking ephemeral components
4053            final boolean isSpecialProcess =
4054                    callingUid == Process.SYSTEM_UID
4055                    || callingUid == Process.SHELL_UID
4056                    || callingUid == 0;
4057            final boolean allowMatchInstant =
4058                    (includeInstantApp
4059                            && Intent.ACTION_VIEW.equals(intent.getAction())
4060                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4061                            && hasWebURI(intent))
4062                    || isSpecialProcess
4063                    || mContext.checkCallingOrSelfPermission(
4064                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4065            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4066            if (!allowMatchInstant) {
4067                flags &= ~PackageManager.MATCH_INSTANT;
4068            }
4069        }
4070        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4071    }
4072
4073    @Override
4074    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4075        if (!sUserManager.exists(userId)) return null;
4076        flags = updateFlagsForComponent(flags, userId, component);
4077        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4078                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4079        synchronized (mPackages) {
4080            PackageParser.Activity a = mActivities.mActivities.get(component);
4081
4082            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4083            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4084                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4085                if (ps == null) return null;
4086                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4087                        userId);
4088            }
4089            if (mResolveComponentName.equals(component)) {
4090                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4091                        new PackageUserState(), userId);
4092            }
4093        }
4094        return null;
4095    }
4096
4097    @Override
4098    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4099            String resolvedType) {
4100        synchronized (mPackages) {
4101            if (component.equals(mResolveComponentName)) {
4102                // The resolver supports EVERYTHING!
4103                return true;
4104            }
4105            PackageParser.Activity a = mActivities.mActivities.get(component);
4106            if (a == null) {
4107                return false;
4108            }
4109            for (int i=0; i<a.intents.size(); i++) {
4110                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4111                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4112                    return true;
4113                }
4114            }
4115            return false;
4116        }
4117    }
4118
4119    @Override
4120    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4121        if (!sUserManager.exists(userId)) return null;
4122        flags = updateFlagsForComponent(flags, userId, component);
4123        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4124                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4125        synchronized (mPackages) {
4126            PackageParser.Activity a = mReceivers.mActivities.get(component);
4127            if (DEBUG_PACKAGE_INFO) Log.v(
4128                TAG, "getReceiverInfo " + component + ": " + a);
4129            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4130                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4131                if (ps == null) return null;
4132                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4133                        ps.readUserState(userId), userId);
4134                if (ri != null) {
4135                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4136                }
4137                return ri;
4138            }
4139        }
4140        return null;
4141    }
4142
4143    @Override
4144    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4145        if (!sUserManager.exists(userId)) return null;
4146        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4147
4148        flags = updateFlagsForPackage(flags, userId, null);
4149
4150        final boolean canSeeStaticLibraries =
4151                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4152                        == PERMISSION_GRANTED
4153                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4154                        == PERMISSION_GRANTED
4155                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4156                        == PERMISSION_GRANTED
4157                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4158                        == PERMISSION_GRANTED;
4159
4160        synchronized (mPackages) {
4161            List<SharedLibraryInfo> result = null;
4162
4163            final int libCount = mSharedLibraries.size();
4164            for (int i = 0; i < libCount; i++) {
4165                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4166                if (versionedLib == null) {
4167                    continue;
4168                }
4169
4170                final int versionCount = versionedLib.size();
4171                for (int j = 0; j < versionCount; j++) {
4172                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4173                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4174                        break;
4175                    }
4176                    final long identity = Binder.clearCallingIdentity();
4177                    try {
4178                        // TODO: We will change version code to long, so in the new API it is long
4179                        PackageInfo packageInfo = getPackageInfoVersioned(
4180                                libInfo.getDeclaringPackage(), flags, userId);
4181                        if (packageInfo == null) {
4182                            continue;
4183                        }
4184                    } finally {
4185                        Binder.restoreCallingIdentity(identity);
4186                    }
4187
4188                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4189                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4190                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4191
4192                    if (result == null) {
4193                        result = new ArrayList<>();
4194                    }
4195                    result.add(resLibInfo);
4196                }
4197            }
4198
4199            return result != null ? new ParceledListSlice<>(result) : null;
4200        }
4201    }
4202
4203    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4204            SharedLibraryInfo libInfo, int flags, int userId) {
4205        List<VersionedPackage> versionedPackages = null;
4206        final int packageCount = mSettings.mPackages.size();
4207        for (int i = 0; i < packageCount; i++) {
4208            PackageSetting ps = mSettings.mPackages.valueAt(i);
4209
4210            if (ps == null) {
4211                continue;
4212            }
4213
4214            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4215                continue;
4216            }
4217
4218            final String libName = libInfo.getName();
4219            if (libInfo.isStatic()) {
4220                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4221                if (libIdx < 0) {
4222                    continue;
4223                }
4224                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4225                    continue;
4226                }
4227                if (versionedPackages == null) {
4228                    versionedPackages = new ArrayList<>();
4229                }
4230                // If the dependent is a static shared lib, use the public package name
4231                String dependentPackageName = ps.name;
4232                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4233                    dependentPackageName = ps.pkg.manifestPackageName;
4234                }
4235                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4236            } else if (ps.pkg != null) {
4237                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4238                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4239                    if (versionedPackages == null) {
4240                        versionedPackages = new ArrayList<>();
4241                    }
4242                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4243                }
4244            }
4245        }
4246
4247        return versionedPackages;
4248    }
4249
4250    @Override
4251    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4252        if (!sUserManager.exists(userId)) return null;
4253        flags = updateFlagsForComponent(flags, userId, component);
4254        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4255                false /* requireFullPermission */, false /* checkShell */, "get service info");
4256        synchronized (mPackages) {
4257            PackageParser.Service s = mServices.mServices.get(component);
4258            if (DEBUG_PACKAGE_INFO) Log.v(
4259                TAG, "getServiceInfo " + component + ": " + s);
4260            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4261                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4262                if (ps == null) return null;
4263                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4264                        ps.readUserState(userId), userId);
4265                if (si != null) {
4266                    rebaseEnabledOverlays(si.applicationInfo, userId);
4267                }
4268                return si;
4269            }
4270        }
4271        return null;
4272    }
4273
4274    @Override
4275    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4276        if (!sUserManager.exists(userId)) return null;
4277        flags = updateFlagsForComponent(flags, userId, component);
4278        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4279                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4280        synchronized (mPackages) {
4281            PackageParser.Provider p = mProviders.mProviders.get(component);
4282            if (DEBUG_PACKAGE_INFO) Log.v(
4283                TAG, "getProviderInfo " + component + ": " + p);
4284            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4285                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4286                if (ps == null) return null;
4287                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4288                        ps.readUserState(userId), userId);
4289                if (pi != null) {
4290                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4291                }
4292                return pi;
4293            }
4294        }
4295        return null;
4296    }
4297
4298    @Override
4299    public String[] getSystemSharedLibraryNames() {
4300        synchronized (mPackages) {
4301            Set<String> libs = null;
4302            final int libCount = mSharedLibraries.size();
4303            for (int i = 0; i < libCount; i++) {
4304                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4305                if (versionedLib == null) {
4306                    continue;
4307                }
4308                final int versionCount = versionedLib.size();
4309                for (int j = 0; j < versionCount; j++) {
4310                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4311                    if (!libEntry.info.isStatic()) {
4312                        if (libs == null) {
4313                            libs = new ArraySet<>();
4314                        }
4315                        libs.add(libEntry.info.getName());
4316                        break;
4317                    }
4318                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4319                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4320                            UserHandle.getUserId(Binder.getCallingUid()))) {
4321                        if (libs == null) {
4322                            libs = new ArraySet<>();
4323                        }
4324                        libs.add(libEntry.info.getName());
4325                        break;
4326                    }
4327                }
4328            }
4329
4330            if (libs != null) {
4331                String[] libsArray = new String[libs.size()];
4332                libs.toArray(libsArray);
4333                return libsArray;
4334            }
4335
4336            return null;
4337        }
4338    }
4339
4340    @Override
4341    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4342        synchronized (mPackages) {
4343            return mServicesSystemSharedLibraryPackageName;
4344        }
4345    }
4346
4347    @Override
4348    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4349        synchronized (mPackages) {
4350            return mSharedSystemSharedLibraryPackageName;
4351        }
4352    }
4353
4354    private void updateSequenceNumberLP(String packageName, int[] userList) {
4355        for (int i = userList.length - 1; i >= 0; --i) {
4356            final int userId = userList[i];
4357            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4358            if (changedPackages == null) {
4359                changedPackages = new SparseArray<>();
4360                mChangedPackages.put(userId, changedPackages);
4361            }
4362            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4363            if (sequenceNumbers == null) {
4364                sequenceNumbers = new HashMap<>();
4365                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4366            }
4367            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4368            if (sequenceNumber != null) {
4369                changedPackages.remove(sequenceNumber);
4370            }
4371            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4372            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4373        }
4374        mChangedPackagesSequenceNumber++;
4375    }
4376
4377    @Override
4378    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4379        synchronized (mPackages) {
4380            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4381                return null;
4382            }
4383            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4384            if (changedPackages == null) {
4385                return null;
4386            }
4387            final List<String> packageNames =
4388                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4389            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4390                final String packageName = changedPackages.get(i);
4391                if (packageName != null) {
4392                    packageNames.add(packageName);
4393                }
4394            }
4395            return packageNames.isEmpty()
4396                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4397        }
4398    }
4399
4400    @Override
4401    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4402        ArrayList<FeatureInfo> res;
4403        synchronized (mAvailableFeatures) {
4404            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4405            res.addAll(mAvailableFeatures.values());
4406        }
4407        final FeatureInfo fi = new FeatureInfo();
4408        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4409                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4410        res.add(fi);
4411
4412        return new ParceledListSlice<>(res);
4413    }
4414
4415    @Override
4416    public boolean hasSystemFeature(String name, int version) {
4417        synchronized (mAvailableFeatures) {
4418            final FeatureInfo feat = mAvailableFeatures.get(name);
4419            if (feat == null) {
4420                return false;
4421            } else {
4422                return feat.version >= version;
4423            }
4424        }
4425    }
4426
4427    @Override
4428    public int checkPermission(String permName, String pkgName, int userId) {
4429        if (!sUserManager.exists(userId)) {
4430            return PackageManager.PERMISSION_DENIED;
4431        }
4432
4433        synchronized (mPackages) {
4434            final PackageParser.Package p = mPackages.get(pkgName);
4435            if (p != null && p.mExtras != null) {
4436                final PackageSetting ps = (PackageSetting) p.mExtras;
4437                final PermissionsState permissionsState = ps.getPermissionsState();
4438                if (permissionsState.hasPermission(permName, userId)) {
4439                    return PackageManager.PERMISSION_GRANTED;
4440                }
4441                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4442                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4443                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4444                    return PackageManager.PERMISSION_GRANTED;
4445                }
4446            }
4447        }
4448
4449        return PackageManager.PERMISSION_DENIED;
4450    }
4451
4452    @Override
4453    public int checkUidPermission(String permName, int uid) {
4454        final int userId = UserHandle.getUserId(uid);
4455
4456        if (!sUserManager.exists(userId)) {
4457            return PackageManager.PERMISSION_DENIED;
4458        }
4459
4460        synchronized (mPackages) {
4461            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4462            if (obj != null) {
4463                final SettingBase ps = (SettingBase) obj;
4464                final PermissionsState permissionsState = ps.getPermissionsState();
4465                if (permissionsState.hasPermission(permName, userId)) {
4466                    return PackageManager.PERMISSION_GRANTED;
4467                }
4468                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4469                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4470                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4471                    return PackageManager.PERMISSION_GRANTED;
4472                }
4473            } else {
4474                ArraySet<String> perms = mSystemPermissions.get(uid);
4475                if (perms != null) {
4476                    if (perms.contains(permName)) {
4477                        return PackageManager.PERMISSION_GRANTED;
4478                    }
4479                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4480                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4481                        return PackageManager.PERMISSION_GRANTED;
4482                    }
4483                }
4484            }
4485        }
4486
4487        return PackageManager.PERMISSION_DENIED;
4488    }
4489
4490    @Override
4491    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4492        if (UserHandle.getCallingUserId() != userId) {
4493            mContext.enforceCallingPermission(
4494                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4495                    "isPermissionRevokedByPolicy for user " + userId);
4496        }
4497
4498        if (checkPermission(permission, packageName, userId)
4499                == PackageManager.PERMISSION_GRANTED) {
4500            return false;
4501        }
4502
4503        final long identity = Binder.clearCallingIdentity();
4504        try {
4505            final int flags = getPermissionFlags(permission, packageName, userId);
4506            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4507        } finally {
4508            Binder.restoreCallingIdentity(identity);
4509        }
4510    }
4511
4512    @Override
4513    public String getPermissionControllerPackageName() {
4514        synchronized (mPackages) {
4515            return mRequiredInstallerPackage;
4516        }
4517    }
4518
4519    /**
4520     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4521     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4522     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4523     * @param message the message to log on security exception
4524     */
4525    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4526            boolean checkShell, String message) {
4527        if (userId < 0) {
4528            throw new IllegalArgumentException("Invalid userId " + userId);
4529        }
4530        if (checkShell) {
4531            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4532        }
4533        if (userId == UserHandle.getUserId(callingUid)) return;
4534        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4535            if (requireFullPermission) {
4536                mContext.enforceCallingOrSelfPermission(
4537                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4538            } else {
4539                try {
4540                    mContext.enforceCallingOrSelfPermission(
4541                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4542                } catch (SecurityException se) {
4543                    mContext.enforceCallingOrSelfPermission(
4544                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4545                }
4546            }
4547        }
4548    }
4549
4550    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4551        if (callingUid == Process.SHELL_UID) {
4552            if (userHandle >= 0
4553                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4554                throw new SecurityException("Shell does not have permission to access user "
4555                        + userHandle);
4556            } else if (userHandle < 0) {
4557                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4558                        + Debug.getCallers(3));
4559            }
4560        }
4561    }
4562
4563    private BasePermission findPermissionTreeLP(String permName) {
4564        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4565            if (permName.startsWith(bp.name) &&
4566                    permName.length() > bp.name.length() &&
4567                    permName.charAt(bp.name.length()) == '.') {
4568                return bp;
4569            }
4570        }
4571        return null;
4572    }
4573
4574    private BasePermission checkPermissionTreeLP(String permName) {
4575        if (permName != null) {
4576            BasePermission bp = findPermissionTreeLP(permName);
4577            if (bp != null) {
4578                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4579                    return bp;
4580                }
4581                throw new SecurityException("Calling uid "
4582                        + Binder.getCallingUid()
4583                        + " is not allowed to add to permission tree "
4584                        + bp.name + " owned by uid " + bp.uid);
4585            }
4586        }
4587        throw new SecurityException("No permission tree found for " + permName);
4588    }
4589
4590    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4591        if (s1 == null) {
4592            return s2 == null;
4593        }
4594        if (s2 == null) {
4595            return false;
4596        }
4597        if (s1.getClass() != s2.getClass()) {
4598            return false;
4599        }
4600        return s1.equals(s2);
4601    }
4602
4603    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4604        if (pi1.icon != pi2.icon) return false;
4605        if (pi1.logo != pi2.logo) return false;
4606        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4607        if (!compareStrings(pi1.name, pi2.name)) return false;
4608        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4609        // We'll take care of setting this one.
4610        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4611        // These are not currently stored in settings.
4612        //if (!compareStrings(pi1.group, pi2.group)) return false;
4613        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4614        //if (pi1.labelRes != pi2.labelRes) return false;
4615        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4616        return true;
4617    }
4618
4619    int permissionInfoFootprint(PermissionInfo info) {
4620        int size = info.name.length();
4621        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4622        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4623        return size;
4624    }
4625
4626    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4627        int size = 0;
4628        for (BasePermission perm : mSettings.mPermissions.values()) {
4629            if (perm.uid == tree.uid) {
4630                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4631            }
4632        }
4633        return size;
4634    }
4635
4636    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4637        // We calculate the max size of permissions defined by this uid and throw
4638        // if that plus the size of 'info' would exceed our stated maximum.
4639        if (tree.uid != Process.SYSTEM_UID) {
4640            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4641            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4642                throw new SecurityException("Permission tree size cap exceeded");
4643            }
4644        }
4645    }
4646
4647    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4648        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4649            throw new SecurityException("Label must be specified in permission");
4650        }
4651        BasePermission tree = checkPermissionTreeLP(info.name);
4652        BasePermission bp = mSettings.mPermissions.get(info.name);
4653        boolean added = bp == null;
4654        boolean changed = true;
4655        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4656        if (added) {
4657            enforcePermissionCapLocked(info, tree);
4658            bp = new BasePermission(info.name, tree.sourcePackage,
4659                    BasePermission.TYPE_DYNAMIC);
4660        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4661            throw new SecurityException(
4662                    "Not allowed to modify non-dynamic permission "
4663                    + info.name);
4664        } else {
4665            if (bp.protectionLevel == fixedLevel
4666                    && bp.perm.owner.equals(tree.perm.owner)
4667                    && bp.uid == tree.uid
4668                    && comparePermissionInfos(bp.perm.info, info)) {
4669                changed = false;
4670            }
4671        }
4672        bp.protectionLevel = fixedLevel;
4673        info = new PermissionInfo(info);
4674        info.protectionLevel = fixedLevel;
4675        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4676        bp.perm.info.packageName = tree.perm.info.packageName;
4677        bp.uid = tree.uid;
4678        if (added) {
4679            mSettings.mPermissions.put(info.name, bp);
4680        }
4681        if (changed) {
4682            if (!async) {
4683                mSettings.writeLPr();
4684            } else {
4685                scheduleWriteSettingsLocked();
4686            }
4687        }
4688        return added;
4689    }
4690
4691    @Override
4692    public boolean addPermission(PermissionInfo info) {
4693        synchronized (mPackages) {
4694            return addPermissionLocked(info, false);
4695        }
4696    }
4697
4698    @Override
4699    public boolean addPermissionAsync(PermissionInfo info) {
4700        synchronized (mPackages) {
4701            return addPermissionLocked(info, true);
4702        }
4703    }
4704
4705    @Override
4706    public void removePermission(String name) {
4707        synchronized (mPackages) {
4708            checkPermissionTreeLP(name);
4709            BasePermission bp = mSettings.mPermissions.get(name);
4710            if (bp != null) {
4711                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4712                    throw new SecurityException(
4713                            "Not allowed to modify non-dynamic permission "
4714                            + name);
4715                }
4716                mSettings.mPermissions.remove(name);
4717                mSettings.writeLPr();
4718            }
4719        }
4720    }
4721
4722    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4723            BasePermission bp) {
4724        int index = pkg.requestedPermissions.indexOf(bp.name);
4725        if (index == -1) {
4726            throw new SecurityException("Package " + pkg.packageName
4727                    + " has not requested permission " + bp.name);
4728        }
4729        if (!bp.isRuntime() && !bp.isDevelopment()) {
4730            throw new SecurityException("Permission " + bp.name
4731                    + " is not a changeable permission type");
4732        }
4733    }
4734
4735    @Override
4736    public void grantRuntimePermission(String packageName, String name, final int userId) {
4737        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4738    }
4739
4740    private void grantRuntimePermission(String packageName, String name, final int userId,
4741            boolean overridePolicy) {
4742        if (!sUserManager.exists(userId)) {
4743            Log.e(TAG, "No such user:" + userId);
4744            return;
4745        }
4746
4747        mContext.enforceCallingOrSelfPermission(
4748                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4749                "grantRuntimePermission");
4750
4751        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4752                true /* requireFullPermission */, true /* checkShell */,
4753                "grantRuntimePermission");
4754
4755        final int uid;
4756        final SettingBase sb;
4757
4758        synchronized (mPackages) {
4759            final PackageParser.Package pkg = mPackages.get(packageName);
4760            if (pkg == null) {
4761                throw new IllegalArgumentException("Unknown package: " + packageName);
4762            }
4763
4764            final BasePermission bp = mSettings.mPermissions.get(name);
4765            if (bp == null) {
4766                throw new IllegalArgumentException("Unknown permission: " + name);
4767            }
4768
4769            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4770
4771            // If a permission review is required for legacy apps we represent
4772            // their permissions as always granted runtime ones since we need
4773            // to keep the review required permission flag per user while an
4774            // install permission's state is shared across all users.
4775            if (mPermissionReviewRequired
4776                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4777                    && bp.isRuntime()) {
4778                return;
4779            }
4780
4781            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4782            sb = (SettingBase) pkg.mExtras;
4783            if (sb == null) {
4784                throw new IllegalArgumentException("Unknown package: " + packageName);
4785            }
4786
4787            final PermissionsState permissionsState = sb.getPermissionsState();
4788
4789            final int flags = permissionsState.getPermissionFlags(name, userId);
4790            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4791                throw new SecurityException("Cannot grant system fixed permission "
4792                        + name + " for package " + packageName);
4793            }
4794            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4795                throw new SecurityException("Cannot grant policy fixed permission "
4796                        + name + " for package " + packageName);
4797            }
4798
4799            if (bp.isDevelopment()) {
4800                // Development permissions must be handled specially, since they are not
4801                // normal runtime permissions.  For now they apply to all users.
4802                if (permissionsState.grantInstallPermission(bp) !=
4803                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4804                    scheduleWriteSettingsLocked();
4805                }
4806                return;
4807            }
4808
4809            final PackageSetting ps = mSettings.mPackages.get(packageName);
4810            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4811                throw new SecurityException("Cannot grant non-ephemeral permission"
4812                        + name + " for package " + packageName);
4813            }
4814
4815            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4816                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4817                return;
4818            }
4819
4820            final int result = permissionsState.grantRuntimePermission(bp, userId);
4821            switch (result) {
4822                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4823                    return;
4824                }
4825
4826                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4827                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4828                    mHandler.post(new Runnable() {
4829                        @Override
4830                        public void run() {
4831                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4832                        }
4833                    });
4834                }
4835                break;
4836            }
4837
4838            if (bp.isRuntime()) {
4839                logPermissionGranted(mContext, name, packageName);
4840            }
4841
4842            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4843
4844            // Not critical if that is lost - app has to request again.
4845            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4846        }
4847
4848        // Only need to do this if user is initialized. Otherwise it's a new user
4849        // and there are no processes running as the user yet and there's no need
4850        // to make an expensive call to remount processes for the changed permissions.
4851        if (READ_EXTERNAL_STORAGE.equals(name)
4852                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4853            final long token = Binder.clearCallingIdentity();
4854            try {
4855                if (sUserManager.isInitialized(userId)) {
4856                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4857                            StorageManagerInternal.class);
4858                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4859                }
4860            } finally {
4861                Binder.restoreCallingIdentity(token);
4862            }
4863        }
4864    }
4865
4866    @Override
4867    public void revokeRuntimePermission(String packageName, String name, int userId) {
4868        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4869    }
4870
4871    private void revokeRuntimePermission(String packageName, String name, int userId,
4872            boolean overridePolicy) {
4873        if (!sUserManager.exists(userId)) {
4874            Log.e(TAG, "No such user:" + userId);
4875            return;
4876        }
4877
4878        mContext.enforceCallingOrSelfPermission(
4879                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4880                "revokeRuntimePermission");
4881
4882        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4883                true /* requireFullPermission */, true /* checkShell */,
4884                "revokeRuntimePermission");
4885
4886        final int appId;
4887
4888        synchronized (mPackages) {
4889            final PackageParser.Package pkg = mPackages.get(packageName);
4890            if (pkg == null) {
4891                throw new IllegalArgumentException("Unknown package: " + packageName);
4892            }
4893
4894            final BasePermission bp = mSettings.mPermissions.get(name);
4895            if (bp == null) {
4896                throw new IllegalArgumentException("Unknown permission: " + name);
4897            }
4898
4899            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4900
4901            // If a permission review is required for legacy apps we represent
4902            // their permissions as always granted runtime ones since we need
4903            // to keep the review required permission flag per user while an
4904            // install permission's state is shared across all users.
4905            if (mPermissionReviewRequired
4906                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4907                    && bp.isRuntime()) {
4908                return;
4909            }
4910
4911            SettingBase sb = (SettingBase) pkg.mExtras;
4912            if (sb == null) {
4913                throw new IllegalArgumentException("Unknown package: " + packageName);
4914            }
4915
4916            final PermissionsState permissionsState = sb.getPermissionsState();
4917
4918            final int flags = permissionsState.getPermissionFlags(name, userId);
4919            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4920                throw new SecurityException("Cannot revoke system fixed permission "
4921                        + name + " for package " + packageName);
4922            }
4923            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4924                throw new SecurityException("Cannot revoke policy fixed permission "
4925                        + name + " for package " + packageName);
4926            }
4927
4928            if (bp.isDevelopment()) {
4929                // Development permissions must be handled specially, since they are not
4930                // normal runtime permissions.  For now they apply to all users.
4931                if (permissionsState.revokeInstallPermission(bp) !=
4932                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4933                    scheduleWriteSettingsLocked();
4934                }
4935                return;
4936            }
4937
4938            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4939                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4940                return;
4941            }
4942
4943            if (bp.isRuntime()) {
4944                logPermissionRevoked(mContext, name, packageName);
4945            }
4946
4947            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4948
4949            // Critical, after this call app should never have the permission.
4950            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4951
4952            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4953        }
4954
4955        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4956    }
4957
4958    /**
4959     * Get the first event id for the permission.
4960     *
4961     * <p>There are four events for each permission: <ul>
4962     *     <li>Request permission: first id + 0</li>
4963     *     <li>Grant permission: first id + 1</li>
4964     *     <li>Request for permission denied: first id + 2</li>
4965     *     <li>Revoke permission: first id + 3</li>
4966     * </ul></p>
4967     *
4968     * @param name name of the permission
4969     *
4970     * @return The first event id for the permission
4971     */
4972    private static int getBaseEventId(@NonNull String name) {
4973        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4974
4975        if (eventIdIndex == -1) {
4976            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4977                    || "user".equals(Build.TYPE)) {
4978                Log.i(TAG, "Unknown permission " + name);
4979
4980                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4981            } else {
4982                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4983                //
4984                // Also update
4985                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4986                // - metrics_constants.proto
4987                throw new IllegalStateException("Unknown permission " + name);
4988            }
4989        }
4990
4991        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4992    }
4993
4994    /**
4995     * Log that a permission was revoked.
4996     *
4997     * @param context Context of the caller
4998     * @param name name of the permission
4999     * @param packageName package permission if for
5000     */
5001    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5002            @NonNull String packageName) {
5003        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5004    }
5005
5006    /**
5007     * Log that a permission request was granted.
5008     *
5009     * @param context Context of the caller
5010     * @param name name of the permission
5011     * @param packageName package permission if for
5012     */
5013    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5014            @NonNull String packageName) {
5015        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5016    }
5017
5018    @Override
5019    public void resetRuntimePermissions() {
5020        mContext.enforceCallingOrSelfPermission(
5021                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5022                "revokeRuntimePermission");
5023
5024        int callingUid = Binder.getCallingUid();
5025        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5026            mContext.enforceCallingOrSelfPermission(
5027                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5028                    "resetRuntimePermissions");
5029        }
5030
5031        synchronized (mPackages) {
5032            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5033            for (int userId : UserManagerService.getInstance().getUserIds()) {
5034                final int packageCount = mPackages.size();
5035                for (int i = 0; i < packageCount; i++) {
5036                    PackageParser.Package pkg = mPackages.valueAt(i);
5037                    if (!(pkg.mExtras instanceof PackageSetting)) {
5038                        continue;
5039                    }
5040                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5041                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5042                }
5043            }
5044        }
5045    }
5046
5047    @Override
5048    public int getPermissionFlags(String name, String packageName, int userId) {
5049        if (!sUserManager.exists(userId)) {
5050            return 0;
5051        }
5052
5053        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5054
5055        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5056                true /* requireFullPermission */, false /* checkShell */,
5057                "getPermissionFlags");
5058
5059        synchronized (mPackages) {
5060            final PackageParser.Package pkg = mPackages.get(packageName);
5061            if (pkg == null) {
5062                return 0;
5063            }
5064
5065            final BasePermission bp = mSettings.mPermissions.get(name);
5066            if (bp == null) {
5067                return 0;
5068            }
5069
5070            SettingBase sb = (SettingBase) pkg.mExtras;
5071            if (sb == null) {
5072                return 0;
5073            }
5074
5075            PermissionsState permissionsState = sb.getPermissionsState();
5076            return permissionsState.getPermissionFlags(name, userId);
5077        }
5078    }
5079
5080    @Override
5081    public void updatePermissionFlags(String name, String packageName, int flagMask,
5082            int flagValues, int userId) {
5083        if (!sUserManager.exists(userId)) {
5084            return;
5085        }
5086
5087        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5088
5089        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5090                true /* requireFullPermission */, true /* checkShell */,
5091                "updatePermissionFlags");
5092
5093        // Only the system can change these flags and nothing else.
5094        if (getCallingUid() != Process.SYSTEM_UID) {
5095            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5096            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5097            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5098            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5099            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5100        }
5101
5102        synchronized (mPackages) {
5103            final PackageParser.Package pkg = mPackages.get(packageName);
5104            if (pkg == null) {
5105                throw new IllegalArgumentException("Unknown package: " + packageName);
5106            }
5107
5108            final BasePermission bp = mSettings.mPermissions.get(name);
5109            if (bp == null) {
5110                throw new IllegalArgumentException("Unknown permission: " + name);
5111            }
5112
5113            SettingBase sb = (SettingBase) pkg.mExtras;
5114            if (sb == null) {
5115                throw new IllegalArgumentException("Unknown package: " + packageName);
5116            }
5117
5118            PermissionsState permissionsState = sb.getPermissionsState();
5119
5120            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5121
5122            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5123                // Install and runtime permissions are stored in different places,
5124                // so figure out what permission changed and persist the change.
5125                if (permissionsState.getInstallPermissionState(name) != null) {
5126                    scheduleWriteSettingsLocked();
5127                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5128                        || hadState) {
5129                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5130                }
5131            }
5132        }
5133    }
5134
5135    /**
5136     * Update the permission flags for all packages and runtime permissions of a user in order
5137     * to allow device or profile owner to remove POLICY_FIXED.
5138     */
5139    @Override
5140    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5141        if (!sUserManager.exists(userId)) {
5142            return;
5143        }
5144
5145        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5146
5147        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5148                true /* requireFullPermission */, true /* checkShell */,
5149                "updatePermissionFlagsForAllApps");
5150
5151        // Only the system can change system fixed flags.
5152        if (getCallingUid() != Process.SYSTEM_UID) {
5153            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5154            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5155        }
5156
5157        synchronized (mPackages) {
5158            boolean changed = false;
5159            final int packageCount = mPackages.size();
5160            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5161                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5162                SettingBase sb = (SettingBase) pkg.mExtras;
5163                if (sb == null) {
5164                    continue;
5165                }
5166                PermissionsState permissionsState = sb.getPermissionsState();
5167                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5168                        userId, flagMask, flagValues);
5169            }
5170            if (changed) {
5171                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5172            }
5173        }
5174    }
5175
5176    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5177        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5178                != PackageManager.PERMISSION_GRANTED
5179            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5180                != PackageManager.PERMISSION_GRANTED) {
5181            throw new SecurityException(message + " requires "
5182                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5183                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5184        }
5185    }
5186
5187    @Override
5188    public boolean shouldShowRequestPermissionRationale(String permissionName,
5189            String packageName, int userId) {
5190        if (UserHandle.getCallingUserId() != userId) {
5191            mContext.enforceCallingPermission(
5192                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5193                    "canShowRequestPermissionRationale for user " + userId);
5194        }
5195
5196        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5197        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5198            return false;
5199        }
5200
5201        if (checkPermission(permissionName, packageName, userId)
5202                == PackageManager.PERMISSION_GRANTED) {
5203            return false;
5204        }
5205
5206        final int flags;
5207
5208        final long identity = Binder.clearCallingIdentity();
5209        try {
5210            flags = getPermissionFlags(permissionName,
5211                    packageName, userId);
5212        } finally {
5213            Binder.restoreCallingIdentity(identity);
5214        }
5215
5216        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5217                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5218                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5219
5220        if ((flags & fixedFlags) != 0) {
5221            return false;
5222        }
5223
5224        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5225    }
5226
5227    @Override
5228    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5229        mContext.enforceCallingOrSelfPermission(
5230                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5231                "addOnPermissionsChangeListener");
5232
5233        synchronized (mPackages) {
5234            mOnPermissionChangeListeners.addListenerLocked(listener);
5235        }
5236    }
5237
5238    @Override
5239    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5240        synchronized (mPackages) {
5241            mOnPermissionChangeListeners.removeListenerLocked(listener);
5242        }
5243    }
5244
5245    @Override
5246    public boolean isProtectedBroadcast(String actionName) {
5247        synchronized (mPackages) {
5248            if (mProtectedBroadcasts.contains(actionName)) {
5249                return true;
5250            } else if (actionName != null) {
5251                // TODO: remove these terrible hacks
5252                if (actionName.startsWith("android.net.netmon.lingerExpired")
5253                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5254                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5255                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5256                    return true;
5257                }
5258            }
5259        }
5260        return false;
5261    }
5262
5263    @Override
5264    public int checkSignatures(String pkg1, String pkg2) {
5265        synchronized (mPackages) {
5266            final PackageParser.Package p1 = mPackages.get(pkg1);
5267            final PackageParser.Package p2 = mPackages.get(pkg2);
5268            if (p1 == null || p1.mExtras == null
5269                    || p2 == null || p2.mExtras == null) {
5270                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5271            }
5272            return compareSignatures(p1.mSignatures, p2.mSignatures);
5273        }
5274    }
5275
5276    @Override
5277    public int checkUidSignatures(int uid1, int uid2) {
5278        // Map to base uids.
5279        uid1 = UserHandle.getAppId(uid1);
5280        uid2 = UserHandle.getAppId(uid2);
5281        // reader
5282        synchronized (mPackages) {
5283            Signature[] s1;
5284            Signature[] s2;
5285            Object obj = mSettings.getUserIdLPr(uid1);
5286            if (obj != null) {
5287                if (obj instanceof SharedUserSetting) {
5288                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5289                } else if (obj instanceof PackageSetting) {
5290                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5291                } else {
5292                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5293                }
5294            } else {
5295                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5296            }
5297            obj = mSettings.getUserIdLPr(uid2);
5298            if (obj != null) {
5299                if (obj instanceof SharedUserSetting) {
5300                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5301                } else if (obj instanceof PackageSetting) {
5302                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5303                } else {
5304                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5305                }
5306            } else {
5307                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5308            }
5309            return compareSignatures(s1, s2);
5310        }
5311    }
5312
5313    /**
5314     * This method should typically only be used when granting or revoking
5315     * permissions, since the app may immediately restart after this call.
5316     * <p>
5317     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5318     * guard your work against the app being relaunched.
5319     */
5320    private void killUid(int appId, int userId, String reason) {
5321        final long identity = Binder.clearCallingIdentity();
5322        try {
5323            IActivityManager am = ActivityManager.getService();
5324            if (am != null) {
5325                try {
5326                    am.killUid(appId, userId, reason);
5327                } catch (RemoteException e) {
5328                    /* ignore - same process */
5329                }
5330            }
5331        } finally {
5332            Binder.restoreCallingIdentity(identity);
5333        }
5334    }
5335
5336    /**
5337     * Compares two sets of signatures. Returns:
5338     * <br />
5339     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5340     * <br />
5341     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5342     * <br />
5343     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5344     * <br />
5345     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5346     * <br />
5347     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5348     */
5349    static int compareSignatures(Signature[] s1, Signature[] s2) {
5350        if (s1 == null) {
5351            return s2 == null
5352                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5353                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5354        }
5355
5356        if (s2 == null) {
5357            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5358        }
5359
5360        if (s1.length != s2.length) {
5361            return PackageManager.SIGNATURE_NO_MATCH;
5362        }
5363
5364        // Since both signature sets are of size 1, we can compare without HashSets.
5365        if (s1.length == 1) {
5366            return s1[0].equals(s2[0]) ?
5367                    PackageManager.SIGNATURE_MATCH :
5368                    PackageManager.SIGNATURE_NO_MATCH;
5369        }
5370
5371        ArraySet<Signature> set1 = new ArraySet<Signature>();
5372        for (Signature sig : s1) {
5373            set1.add(sig);
5374        }
5375        ArraySet<Signature> set2 = new ArraySet<Signature>();
5376        for (Signature sig : s2) {
5377            set2.add(sig);
5378        }
5379        // Make sure s2 contains all signatures in s1.
5380        if (set1.equals(set2)) {
5381            return PackageManager.SIGNATURE_MATCH;
5382        }
5383        return PackageManager.SIGNATURE_NO_MATCH;
5384    }
5385
5386    /**
5387     * If the database version for this type of package (internal storage or
5388     * external storage) is less than the version where package signatures
5389     * were updated, return true.
5390     */
5391    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5392        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5393        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5394    }
5395
5396    /**
5397     * Used for backward compatibility to make sure any packages with
5398     * certificate chains get upgraded to the new style. {@code existingSigs}
5399     * will be in the old format (since they were stored on disk from before the
5400     * system upgrade) and {@code scannedSigs} will be in the newer format.
5401     */
5402    private int compareSignaturesCompat(PackageSignatures existingSigs,
5403            PackageParser.Package scannedPkg) {
5404        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5405            return PackageManager.SIGNATURE_NO_MATCH;
5406        }
5407
5408        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5409        for (Signature sig : existingSigs.mSignatures) {
5410            existingSet.add(sig);
5411        }
5412        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5413        for (Signature sig : scannedPkg.mSignatures) {
5414            try {
5415                Signature[] chainSignatures = sig.getChainSignatures();
5416                for (Signature chainSig : chainSignatures) {
5417                    scannedCompatSet.add(chainSig);
5418                }
5419            } catch (CertificateEncodingException e) {
5420                scannedCompatSet.add(sig);
5421            }
5422        }
5423        /*
5424         * Make sure the expanded scanned set contains all signatures in the
5425         * existing one.
5426         */
5427        if (scannedCompatSet.equals(existingSet)) {
5428            // Migrate the old signatures to the new scheme.
5429            existingSigs.assignSignatures(scannedPkg.mSignatures);
5430            // The new KeySets will be re-added later in the scanning process.
5431            synchronized (mPackages) {
5432                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5433            }
5434            return PackageManager.SIGNATURE_MATCH;
5435        }
5436        return PackageManager.SIGNATURE_NO_MATCH;
5437    }
5438
5439    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5440        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5441        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5442    }
5443
5444    private int compareSignaturesRecover(PackageSignatures existingSigs,
5445            PackageParser.Package scannedPkg) {
5446        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5447            return PackageManager.SIGNATURE_NO_MATCH;
5448        }
5449
5450        String msg = null;
5451        try {
5452            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5453                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5454                        + scannedPkg.packageName);
5455                return PackageManager.SIGNATURE_MATCH;
5456            }
5457        } catch (CertificateException e) {
5458            msg = e.getMessage();
5459        }
5460
5461        logCriticalInfo(Log.INFO,
5462                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5463        return PackageManager.SIGNATURE_NO_MATCH;
5464    }
5465
5466    @Override
5467    public List<String> getAllPackages() {
5468        synchronized (mPackages) {
5469            return new ArrayList<String>(mPackages.keySet());
5470        }
5471    }
5472
5473    @Override
5474    public String[] getPackagesForUid(int uid) {
5475        final int userId = UserHandle.getUserId(uid);
5476        uid = UserHandle.getAppId(uid);
5477        // reader
5478        synchronized (mPackages) {
5479            Object obj = mSettings.getUserIdLPr(uid);
5480            if (obj instanceof SharedUserSetting) {
5481                final SharedUserSetting sus = (SharedUserSetting) obj;
5482                final int N = sus.packages.size();
5483                String[] res = new String[N];
5484                final Iterator<PackageSetting> it = sus.packages.iterator();
5485                int i = 0;
5486                while (it.hasNext()) {
5487                    PackageSetting ps = it.next();
5488                    if (ps.getInstalled(userId)) {
5489                        res[i++] = ps.name;
5490                    } else {
5491                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5492                    }
5493                }
5494                return res;
5495            } else if (obj instanceof PackageSetting) {
5496                final PackageSetting ps = (PackageSetting) obj;
5497                if (ps.getInstalled(userId)) {
5498                    return new String[]{ps.name};
5499                }
5500            }
5501        }
5502        return null;
5503    }
5504
5505    @Override
5506    public String getNameForUid(int uid) {
5507        // reader
5508        synchronized (mPackages) {
5509            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5510            if (obj instanceof SharedUserSetting) {
5511                final SharedUserSetting sus = (SharedUserSetting) obj;
5512                return sus.name + ":" + sus.userId;
5513            } else if (obj instanceof PackageSetting) {
5514                final PackageSetting ps = (PackageSetting) obj;
5515                return ps.name;
5516            }
5517        }
5518        return null;
5519    }
5520
5521    @Override
5522    public int getUidForSharedUser(String sharedUserName) {
5523        if(sharedUserName == null) {
5524            return -1;
5525        }
5526        // reader
5527        synchronized (mPackages) {
5528            SharedUserSetting suid;
5529            try {
5530                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5531                if (suid != null) {
5532                    return suid.userId;
5533                }
5534            } catch (PackageManagerException ignore) {
5535                // can't happen, but, still need to catch it
5536            }
5537            return -1;
5538        }
5539    }
5540
5541    @Override
5542    public int getFlagsForUid(int uid) {
5543        synchronized (mPackages) {
5544            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5545            if (obj instanceof SharedUserSetting) {
5546                final SharedUserSetting sus = (SharedUserSetting) obj;
5547                return sus.pkgFlags;
5548            } else if (obj instanceof PackageSetting) {
5549                final PackageSetting ps = (PackageSetting) obj;
5550                return ps.pkgFlags;
5551            }
5552        }
5553        return 0;
5554    }
5555
5556    @Override
5557    public int getPrivateFlagsForUid(int uid) {
5558        synchronized (mPackages) {
5559            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5560            if (obj instanceof SharedUserSetting) {
5561                final SharedUserSetting sus = (SharedUserSetting) obj;
5562                return sus.pkgPrivateFlags;
5563            } else if (obj instanceof PackageSetting) {
5564                final PackageSetting ps = (PackageSetting) obj;
5565                return ps.pkgPrivateFlags;
5566            }
5567        }
5568        return 0;
5569    }
5570
5571    @Override
5572    public boolean isUidPrivileged(int uid) {
5573        uid = UserHandle.getAppId(uid);
5574        // reader
5575        synchronized (mPackages) {
5576            Object obj = mSettings.getUserIdLPr(uid);
5577            if (obj instanceof SharedUserSetting) {
5578                final SharedUserSetting sus = (SharedUserSetting) obj;
5579                final Iterator<PackageSetting> it = sus.packages.iterator();
5580                while (it.hasNext()) {
5581                    if (it.next().isPrivileged()) {
5582                        return true;
5583                    }
5584                }
5585            } else if (obj instanceof PackageSetting) {
5586                final PackageSetting ps = (PackageSetting) obj;
5587                return ps.isPrivileged();
5588            }
5589        }
5590        return false;
5591    }
5592
5593    @Override
5594    public String[] getAppOpPermissionPackages(String permissionName) {
5595        synchronized (mPackages) {
5596            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5597            if (pkgs == null) {
5598                return null;
5599            }
5600            return pkgs.toArray(new String[pkgs.size()]);
5601        }
5602    }
5603
5604    @Override
5605    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5606            int flags, int userId) {
5607        return resolveIntentInternal(
5608                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5609    }
5610
5611    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5612            int flags, int userId, boolean includeInstantApp) {
5613        try {
5614            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5615
5616            if (!sUserManager.exists(userId)) return null;
5617            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5618            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5619                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5620
5621            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5622            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5623                    flags, userId, includeInstantApp);
5624            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5625
5626            final ResolveInfo bestChoice =
5627                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5628            return bestChoice;
5629        } finally {
5630            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5631        }
5632    }
5633
5634    @Override
5635    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5636        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5637            throw new SecurityException(
5638                    "findPersistentPreferredActivity can only be run by the system");
5639        }
5640        if (!sUserManager.exists(userId)) {
5641            return null;
5642        }
5643        intent = updateIntentForResolve(intent);
5644        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5645        final int flags = updateFlagsForResolve(0, userId, intent, false);
5646        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5647                userId);
5648        synchronized (mPackages) {
5649            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5650                    userId);
5651        }
5652    }
5653
5654    @Override
5655    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5656            IntentFilter filter, int match, ComponentName activity) {
5657        final int userId = UserHandle.getCallingUserId();
5658        if (DEBUG_PREFERRED) {
5659            Log.v(TAG, "setLastChosenActivity intent=" + intent
5660                + " resolvedType=" + resolvedType
5661                + " flags=" + flags
5662                + " filter=" + filter
5663                + " match=" + match
5664                + " activity=" + activity);
5665            filter.dump(new PrintStreamPrinter(System.out), "    ");
5666        }
5667        intent.setComponent(null);
5668        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5669                userId);
5670        // Find any earlier preferred or last chosen entries and nuke them
5671        findPreferredActivity(intent, resolvedType,
5672                flags, query, 0, false, true, false, userId);
5673        // Add the new activity as the last chosen for this filter
5674        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5675                "Setting last chosen");
5676    }
5677
5678    @Override
5679    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5680        final int userId = UserHandle.getCallingUserId();
5681        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5682        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5683                userId);
5684        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5685                false, false, false, userId);
5686    }
5687
5688    /**
5689     * Returns whether or not instant apps have been disabled remotely.
5690     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5691     * held. Otherwise we run the risk of deadlock.
5692     */
5693    private boolean isEphemeralDisabled() {
5694        // ephemeral apps have been disabled across the board
5695        if (DISABLE_EPHEMERAL_APPS) {
5696            return true;
5697        }
5698        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5699        if (!mSystemReady) {
5700            return true;
5701        }
5702        // we can't get a content resolver until the system is ready; these checks must happen last
5703        final ContentResolver resolver = mContext.getContentResolver();
5704        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5705            return true;
5706        }
5707        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5708    }
5709
5710    private boolean isEphemeralAllowed(
5711            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5712            boolean skipPackageCheck) {
5713        final int callingUser = UserHandle.getCallingUserId();
5714        if (callingUser != UserHandle.USER_SYSTEM) {
5715            return false;
5716        }
5717        if (mInstantAppResolverConnection == null) {
5718            return false;
5719        }
5720        if (mInstantAppInstallerComponent == null) {
5721            return false;
5722        }
5723        if (intent.getComponent() != null) {
5724            return false;
5725        }
5726        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5727            return false;
5728        }
5729        if (!skipPackageCheck && intent.getPackage() != null) {
5730            return false;
5731        }
5732        final boolean isWebUri = hasWebURI(intent);
5733        if (!isWebUri || intent.getData().getHost() == null) {
5734            return false;
5735        }
5736        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5737        // Or if there's already an ephemeral app installed that handles the action
5738        synchronized (mPackages) {
5739            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5740            for (int n = 0; n < count; n++) {
5741                ResolveInfo info = resolvedActivities.get(n);
5742                String packageName = info.activityInfo.packageName;
5743                PackageSetting ps = mSettings.mPackages.get(packageName);
5744                if (ps != null) {
5745                    // Try to get the status from User settings first
5746                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5747                    int status = (int) (packedStatus >> 32);
5748                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5749                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5750                        if (DEBUG_EPHEMERAL) {
5751                            Slog.v(TAG, "DENY ephemeral apps;"
5752                                + " pkg: " + packageName + ", status: " + status);
5753                        }
5754                        return false;
5755                    }
5756                    if (ps.getInstantApp(userId)) {
5757                        return false;
5758                    }
5759                }
5760            }
5761        }
5762        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5763        return true;
5764    }
5765
5766    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5767            Intent origIntent, String resolvedType, String callingPackage,
5768            int userId) {
5769        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5770                new InstantAppRequest(responseObj, origIntent, resolvedType,
5771                        callingPackage, userId));
5772        mHandler.sendMessage(msg);
5773    }
5774
5775    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5776            int flags, List<ResolveInfo> query, int userId) {
5777        if (query != null) {
5778            final int N = query.size();
5779            if (N == 1) {
5780                return query.get(0);
5781            } else if (N > 1) {
5782                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5783                // If there is more than one activity with the same priority,
5784                // then let the user decide between them.
5785                ResolveInfo r0 = query.get(0);
5786                ResolveInfo r1 = query.get(1);
5787                if (DEBUG_INTENT_MATCHING || debug) {
5788                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5789                            + r1.activityInfo.name + "=" + r1.priority);
5790                }
5791                // If the first activity has a higher priority, or a different
5792                // default, then it is always desirable to pick it.
5793                if (r0.priority != r1.priority
5794                        || r0.preferredOrder != r1.preferredOrder
5795                        || r0.isDefault != r1.isDefault) {
5796                    return query.get(0);
5797                }
5798                // If we have saved a preference for a preferred activity for
5799                // this Intent, use that.
5800                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5801                        flags, query, r0.priority, true, false, debug, userId);
5802                if (ri != null) {
5803                    return ri;
5804                }
5805                // If we have an ephemeral app, use it
5806                for (int i = 0; i < N; i++) {
5807                    ri = query.get(i);
5808                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5809                        return ri;
5810                    }
5811                }
5812                ri = new ResolveInfo(mResolveInfo);
5813                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5814                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5815                // If all of the options come from the same package, show the application's
5816                // label and icon instead of the generic resolver's.
5817                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5818                // and then throw away the ResolveInfo itself, meaning that the caller loses
5819                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5820                // a fallback for this case; we only set the target package's resources on
5821                // the ResolveInfo, not the ActivityInfo.
5822                final String intentPackage = intent.getPackage();
5823                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5824                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5825                    ri.resolvePackageName = intentPackage;
5826                    if (userNeedsBadging(userId)) {
5827                        ri.noResourceId = true;
5828                    } else {
5829                        ri.icon = appi.icon;
5830                    }
5831                    ri.iconResourceId = appi.icon;
5832                    ri.labelRes = appi.labelRes;
5833                }
5834                ri.activityInfo.applicationInfo = new ApplicationInfo(
5835                        ri.activityInfo.applicationInfo);
5836                if (userId != 0) {
5837                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5838                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5839                }
5840                // Make sure that the resolver is displayable in car mode
5841                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5842                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5843                return ri;
5844            }
5845        }
5846        return null;
5847    }
5848
5849    /**
5850     * Return true if the given list is not empty and all of its contents have
5851     * an activityInfo with the given package name.
5852     */
5853    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5854        if (ArrayUtils.isEmpty(list)) {
5855            return false;
5856        }
5857        for (int i = 0, N = list.size(); i < N; i++) {
5858            final ResolveInfo ri = list.get(i);
5859            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5860            if (ai == null || !packageName.equals(ai.packageName)) {
5861                return false;
5862            }
5863        }
5864        return true;
5865    }
5866
5867    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5868            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5869        final int N = query.size();
5870        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5871                .get(userId);
5872        // Get the list of persistent preferred activities that handle the intent
5873        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5874        List<PersistentPreferredActivity> pprefs = ppir != null
5875                ? ppir.queryIntent(intent, resolvedType,
5876                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5877                        userId)
5878                : null;
5879        if (pprefs != null && pprefs.size() > 0) {
5880            final int M = pprefs.size();
5881            for (int i=0; i<M; i++) {
5882                final PersistentPreferredActivity ppa = pprefs.get(i);
5883                if (DEBUG_PREFERRED || debug) {
5884                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5885                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5886                            + "\n  component=" + ppa.mComponent);
5887                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5888                }
5889                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5890                        flags | MATCH_DISABLED_COMPONENTS, userId);
5891                if (DEBUG_PREFERRED || debug) {
5892                    Slog.v(TAG, "Found persistent preferred activity:");
5893                    if (ai != null) {
5894                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5895                    } else {
5896                        Slog.v(TAG, "  null");
5897                    }
5898                }
5899                if (ai == null) {
5900                    // This previously registered persistent preferred activity
5901                    // component is no longer known. Ignore it and do NOT remove it.
5902                    continue;
5903                }
5904                for (int j=0; j<N; j++) {
5905                    final ResolveInfo ri = query.get(j);
5906                    if (!ri.activityInfo.applicationInfo.packageName
5907                            .equals(ai.applicationInfo.packageName)) {
5908                        continue;
5909                    }
5910                    if (!ri.activityInfo.name.equals(ai.name)) {
5911                        continue;
5912                    }
5913                    //  Found a persistent preference that can handle the intent.
5914                    if (DEBUG_PREFERRED || debug) {
5915                        Slog.v(TAG, "Returning persistent preferred activity: " +
5916                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5917                    }
5918                    return ri;
5919                }
5920            }
5921        }
5922        return null;
5923    }
5924
5925    // TODO: handle preferred activities missing while user has amnesia
5926    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5927            List<ResolveInfo> query, int priority, boolean always,
5928            boolean removeMatches, boolean debug, int userId) {
5929        if (!sUserManager.exists(userId)) return null;
5930        flags = updateFlagsForResolve(flags, userId, intent, false);
5931        intent = updateIntentForResolve(intent);
5932        // writer
5933        synchronized (mPackages) {
5934            // Try to find a matching persistent preferred activity.
5935            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5936                    debug, userId);
5937
5938            // If a persistent preferred activity matched, use it.
5939            if (pri != null) {
5940                return pri;
5941            }
5942
5943            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5944            // Get the list of preferred activities that handle the intent
5945            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5946            List<PreferredActivity> prefs = pir != null
5947                    ? pir.queryIntent(intent, resolvedType,
5948                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5949                            userId)
5950                    : null;
5951            if (prefs != null && prefs.size() > 0) {
5952                boolean changed = false;
5953                try {
5954                    // First figure out how good the original match set is.
5955                    // We will only allow preferred activities that came
5956                    // from the same match quality.
5957                    int match = 0;
5958
5959                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5960
5961                    final int N = query.size();
5962                    for (int j=0; j<N; j++) {
5963                        final ResolveInfo ri = query.get(j);
5964                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5965                                + ": 0x" + Integer.toHexString(match));
5966                        if (ri.match > match) {
5967                            match = ri.match;
5968                        }
5969                    }
5970
5971                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5972                            + Integer.toHexString(match));
5973
5974                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5975                    final int M = prefs.size();
5976                    for (int i=0; i<M; i++) {
5977                        final PreferredActivity pa = prefs.get(i);
5978                        if (DEBUG_PREFERRED || debug) {
5979                            Slog.v(TAG, "Checking PreferredActivity ds="
5980                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5981                                    + "\n  component=" + pa.mPref.mComponent);
5982                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5983                        }
5984                        if (pa.mPref.mMatch != match) {
5985                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5986                                    + Integer.toHexString(pa.mPref.mMatch));
5987                            continue;
5988                        }
5989                        // If it's not an "always" type preferred activity and that's what we're
5990                        // looking for, skip it.
5991                        if (always && !pa.mPref.mAlways) {
5992                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5993                            continue;
5994                        }
5995                        final ActivityInfo ai = getActivityInfo(
5996                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5997                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5998                                userId);
5999                        if (DEBUG_PREFERRED || debug) {
6000                            Slog.v(TAG, "Found preferred activity:");
6001                            if (ai != null) {
6002                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6003                            } else {
6004                                Slog.v(TAG, "  null");
6005                            }
6006                        }
6007                        if (ai == null) {
6008                            // This previously registered preferred activity
6009                            // component is no longer known.  Most likely an update
6010                            // to the app was installed and in the new version this
6011                            // component no longer exists.  Clean it up by removing
6012                            // it from the preferred activities list, and skip it.
6013                            Slog.w(TAG, "Removing dangling preferred activity: "
6014                                    + pa.mPref.mComponent);
6015                            pir.removeFilter(pa);
6016                            changed = true;
6017                            continue;
6018                        }
6019                        for (int j=0; j<N; j++) {
6020                            final ResolveInfo ri = query.get(j);
6021                            if (!ri.activityInfo.applicationInfo.packageName
6022                                    .equals(ai.applicationInfo.packageName)) {
6023                                continue;
6024                            }
6025                            if (!ri.activityInfo.name.equals(ai.name)) {
6026                                continue;
6027                            }
6028
6029                            if (removeMatches) {
6030                                pir.removeFilter(pa);
6031                                changed = true;
6032                                if (DEBUG_PREFERRED) {
6033                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6034                                }
6035                                break;
6036                            }
6037
6038                            // Okay we found a previously set preferred or last chosen app.
6039                            // If the result set is different from when this
6040                            // was created, we need to clear it and re-ask the
6041                            // user their preference, if we're looking for an "always" type entry.
6042                            if (always && !pa.mPref.sameSet(query)) {
6043                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6044                                        + intent + " type " + resolvedType);
6045                                if (DEBUG_PREFERRED) {
6046                                    Slog.v(TAG, "Removing preferred activity since set changed "
6047                                            + pa.mPref.mComponent);
6048                                }
6049                                pir.removeFilter(pa);
6050                                // Re-add the filter as a "last chosen" entry (!always)
6051                                PreferredActivity lastChosen = new PreferredActivity(
6052                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6053                                pir.addFilter(lastChosen);
6054                                changed = true;
6055                                return null;
6056                            }
6057
6058                            // Yay! Either the set matched or we're looking for the last chosen
6059                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6060                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6061                            return ri;
6062                        }
6063                    }
6064                } finally {
6065                    if (changed) {
6066                        if (DEBUG_PREFERRED) {
6067                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6068                        }
6069                        scheduleWritePackageRestrictionsLocked(userId);
6070                    }
6071                }
6072            }
6073        }
6074        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6075        return null;
6076    }
6077
6078    /*
6079     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6080     */
6081    @Override
6082    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6083            int targetUserId) {
6084        mContext.enforceCallingOrSelfPermission(
6085                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6086        List<CrossProfileIntentFilter> matches =
6087                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6088        if (matches != null) {
6089            int size = matches.size();
6090            for (int i = 0; i < size; i++) {
6091                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6092            }
6093        }
6094        if (hasWebURI(intent)) {
6095            // cross-profile app linking works only towards the parent.
6096            final UserInfo parent = getProfileParent(sourceUserId);
6097            synchronized(mPackages) {
6098                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6099                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6100                        intent, resolvedType, flags, sourceUserId, parent.id);
6101                return xpDomainInfo != null;
6102            }
6103        }
6104        return false;
6105    }
6106
6107    private UserInfo getProfileParent(int userId) {
6108        final long identity = Binder.clearCallingIdentity();
6109        try {
6110            return sUserManager.getProfileParent(userId);
6111        } finally {
6112            Binder.restoreCallingIdentity(identity);
6113        }
6114    }
6115
6116    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6117            String resolvedType, int userId) {
6118        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6119        if (resolver != null) {
6120            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6121        }
6122        return null;
6123    }
6124
6125    @Override
6126    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6127            String resolvedType, int flags, int userId) {
6128        try {
6129            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6130
6131            return new ParceledListSlice<>(
6132                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6133        } finally {
6134            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6135        }
6136    }
6137
6138    /**
6139     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6140     * instant, returns {@code null}.
6141     */
6142    private String getInstantAppPackageName(int callingUid) {
6143        final int appId = UserHandle.getAppId(callingUid);
6144        synchronized (mPackages) {
6145            final Object obj = mSettings.getUserIdLPr(appId);
6146            if (obj instanceof PackageSetting) {
6147                final PackageSetting ps = (PackageSetting) obj;
6148                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6149                return isInstantApp ? ps.pkg.packageName : null;
6150            }
6151        }
6152        return null;
6153    }
6154
6155    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6156            String resolvedType, int flags, int userId) {
6157        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6158    }
6159
6160    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6161            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6162        if (!sUserManager.exists(userId)) return Collections.emptyList();
6163        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6164        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6165        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6166                false /* requireFullPermission */, false /* checkShell */,
6167                "query intent activities");
6168        ComponentName comp = intent.getComponent();
6169        if (comp == null) {
6170            if (intent.getSelector() != null) {
6171                intent = intent.getSelector();
6172                comp = intent.getComponent();
6173            }
6174        }
6175
6176        if (comp != null) {
6177            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6178            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6179            if (ai != null) {
6180                // When specifying an explicit component, we prevent the activity from being
6181                // used when either 1) the calling package is normal and the activity is within
6182                // an ephemeral application or 2) the calling package is ephemeral and the
6183                // activity is not visible to ephemeral applications.
6184                final boolean matchInstantApp =
6185                        (flags & PackageManager.MATCH_INSTANT) != 0;
6186                final boolean matchVisibleToInstantAppOnly =
6187                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6188                final boolean isCallerInstantApp =
6189                        instantAppPkgName != null;
6190                final boolean isTargetSameInstantApp =
6191                        comp.getPackageName().equals(instantAppPkgName);
6192                final boolean isTargetInstantApp =
6193                        (ai.applicationInfo.privateFlags
6194                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6195                final boolean isTargetHiddenFromInstantApp =
6196                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6197                final boolean blockResolution =
6198                        !isTargetSameInstantApp
6199                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6200                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6201                                        && isTargetHiddenFromInstantApp));
6202                if (!blockResolution) {
6203                    final ResolveInfo ri = new ResolveInfo();
6204                    ri.activityInfo = ai;
6205                    list.add(ri);
6206                }
6207            }
6208            return applyPostResolutionFilter(list, instantAppPkgName);
6209        }
6210
6211        // reader
6212        boolean sortResult = false;
6213        boolean addEphemeral = false;
6214        List<ResolveInfo> result;
6215        final String pkgName = intent.getPackage();
6216        final boolean ephemeralDisabled = isEphemeralDisabled();
6217        synchronized (mPackages) {
6218            if (pkgName == null) {
6219                List<CrossProfileIntentFilter> matchingFilters =
6220                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6221                // Check for results that need to skip the current profile.
6222                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6223                        resolvedType, flags, userId);
6224                if (xpResolveInfo != null) {
6225                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6226                    xpResult.add(xpResolveInfo);
6227                    return applyPostResolutionFilter(
6228                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6229                }
6230
6231                // Check for results in the current profile.
6232                result = filterIfNotSystemUser(mActivities.queryIntent(
6233                        intent, resolvedType, flags, userId), userId);
6234                addEphemeral = !ephemeralDisabled
6235                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6236
6237                // Check for cross profile results.
6238                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6239                xpResolveInfo = queryCrossProfileIntents(
6240                        matchingFilters, intent, resolvedType, flags, userId,
6241                        hasNonNegativePriorityResult);
6242                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6243                    boolean isVisibleToUser = filterIfNotSystemUser(
6244                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6245                    if (isVisibleToUser) {
6246                        result.add(xpResolveInfo);
6247                        sortResult = true;
6248                    }
6249                }
6250                if (hasWebURI(intent)) {
6251                    CrossProfileDomainInfo xpDomainInfo = null;
6252                    final UserInfo parent = getProfileParent(userId);
6253                    if (parent != null) {
6254                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6255                                flags, userId, parent.id);
6256                    }
6257                    if (xpDomainInfo != null) {
6258                        if (xpResolveInfo != null) {
6259                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6260                            // in the result.
6261                            result.remove(xpResolveInfo);
6262                        }
6263                        if (result.size() == 0 && !addEphemeral) {
6264                            // No result in current profile, but found candidate in parent user.
6265                            // And we are not going to add emphemeral app, so we can return the
6266                            // result straight away.
6267                            result.add(xpDomainInfo.resolveInfo);
6268                            return applyPostResolutionFilter(result, instantAppPkgName);
6269                        }
6270                    } else if (result.size() <= 1 && !addEphemeral) {
6271                        // No result in parent user and <= 1 result in current profile, and we
6272                        // are not going to add emphemeral app, so we can return the result without
6273                        // further processing.
6274                        return applyPostResolutionFilter(result, instantAppPkgName);
6275                    }
6276                    // We have more than one candidate (combining results from current and parent
6277                    // profile), so we need filtering and sorting.
6278                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6279                            intent, flags, result, xpDomainInfo, userId);
6280                    sortResult = true;
6281                }
6282            } else {
6283                final PackageParser.Package pkg = mPackages.get(pkgName);
6284                if (pkg != null) {
6285                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6286                            mActivities.queryIntentForPackage(
6287                                    intent, resolvedType, flags, pkg.activities, userId),
6288                            userId), instantAppPkgName);
6289                } else {
6290                    // the caller wants to resolve for a particular package; however, there
6291                    // were no installed results, so, try to find an ephemeral result
6292                    addEphemeral =  !ephemeralDisabled
6293                            && isEphemeralAllowed(
6294                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6295                    result = new ArrayList<ResolveInfo>();
6296                }
6297            }
6298        }
6299        if (addEphemeral) {
6300            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6301            final InstantAppRequest requestObject = new InstantAppRequest(
6302                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6303                    null /*callingPackage*/, userId);
6304            final AuxiliaryResolveInfo auxiliaryResponse =
6305                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6306                            mContext, mInstantAppResolverConnection, requestObject);
6307            if (auxiliaryResponse != null) {
6308                if (DEBUG_EPHEMERAL) {
6309                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6310                }
6311                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6312                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6313                // make sure this resolver is the default
6314                ephemeralInstaller.isDefault = true;
6315                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6316                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6317                // add a non-generic filter
6318                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6319                ephemeralInstaller.filter.addDataPath(
6320                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6321                ephemeralInstaller.instantAppAvailable = true;
6322                result.add(ephemeralInstaller);
6323            }
6324            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6325        }
6326        if (sortResult) {
6327            Collections.sort(result, mResolvePrioritySorter);
6328        }
6329        return applyPostResolutionFilter(result, instantAppPkgName);
6330    }
6331
6332    private static class CrossProfileDomainInfo {
6333        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6334        ResolveInfo resolveInfo;
6335        /* Best domain verification status of the activities found in the other profile */
6336        int bestDomainVerificationStatus;
6337    }
6338
6339    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6340            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6341        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6342                sourceUserId)) {
6343            return null;
6344        }
6345        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6346                resolvedType, flags, parentUserId);
6347
6348        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6349            return null;
6350        }
6351        CrossProfileDomainInfo result = null;
6352        int size = resultTargetUser.size();
6353        for (int i = 0; i < size; i++) {
6354            ResolveInfo riTargetUser = resultTargetUser.get(i);
6355            // Intent filter verification is only for filters that specify a host. So don't return
6356            // those that handle all web uris.
6357            if (riTargetUser.handleAllWebDataURI) {
6358                continue;
6359            }
6360            String packageName = riTargetUser.activityInfo.packageName;
6361            PackageSetting ps = mSettings.mPackages.get(packageName);
6362            if (ps == null) {
6363                continue;
6364            }
6365            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6366            int status = (int)(verificationState >> 32);
6367            if (result == null) {
6368                result = new CrossProfileDomainInfo();
6369                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6370                        sourceUserId, parentUserId);
6371                result.bestDomainVerificationStatus = status;
6372            } else {
6373                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6374                        result.bestDomainVerificationStatus);
6375            }
6376        }
6377        // Don't consider matches with status NEVER across profiles.
6378        if (result != null && result.bestDomainVerificationStatus
6379                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6380            return null;
6381        }
6382        return result;
6383    }
6384
6385    /**
6386     * Verification statuses are ordered from the worse to the best, except for
6387     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6388     */
6389    private int bestDomainVerificationStatus(int status1, int status2) {
6390        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6391            return status2;
6392        }
6393        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6394            return status1;
6395        }
6396        return (int) MathUtils.max(status1, status2);
6397    }
6398
6399    private boolean isUserEnabled(int userId) {
6400        long callingId = Binder.clearCallingIdentity();
6401        try {
6402            UserInfo userInfo = sUserManager.getUserInfo(userId);
6403            return userInfo != null && userInfo.isEnabled();
6404        } finally {
6405            Binder.restoreCallingIdentity(callingId);
6406        }
6407    }
6408
6409    /**
6410     * Filter out activities with systemUserOnly flag set, when current user is not System.
6411     *
6412     * @return filtered list
6413     */
6414    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6415        if (userId == UserHandle.USER_SYSTEM) {
6416            return resolveInfos;
6417        }
6418        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6419            ResolveInfo info = resolveInfos.get(i);
6420            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6421                resolveInfos.remove(i);
6422            }
6423        }
6424        return resolveInfos;
6425    }
6426
6427    /**
6428     * Filters out ephemeral activities.
6429     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6430     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6431     *
6432     * @param resolveInfos The pre-filtered list of resolved activities
6433     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6434     *          is performed.
6435     * @return A filtered list of resolved activities.
6436     */
6437    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6438            String ephemeralPkgName) {
6439        // TODO: When adding on-demand split support for non-instant apps, remove this check
6440        // and always apply post filtering
6441        if (ephemeralPkgName == null) {
6442            return resolveInfos;
6443        }
6444        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6445            final ResolveInfo info = resolveInfos.get(i);
6446            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6447            // allow activities that are defined in the provided package
6448            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6449                if (info.activityInfo.splitName != null
6450                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6451                                info.activityInfo.splitName)) {
6452                    // requested activity is defined in a split that hasn't been installed yet.
6453                    // add the installer to the resolve list
6454                    if (DEBUG_EPHEMERAL) {
6455                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6456                    }
6457                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6458                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6459                            info.activityInfo.packageName, info.activityInfo.splitName,
6460                            info.activityInfo.applicationInfo.versionCode);
6461                    // make sure this resolver is the default
6462                    installerInfo.isDefault = true;
6463                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6464                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6465                    // add a non-generic filter
6466                    installerInfo.filter = new IntentFilter();
6467                    // load resources from the correct package
6468                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6469                    resolveInfos.set(i, installerInfo);
6470                }
6471                continue;
6472            }
6473            // allow activities that have been explicitly exposed to ephemeral apps
6474            if (!isEphemeralApp
6475                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6476                continue;
6477            }
6478            resolveInfos.remove(i);
6479        }
6480        return resolveInfos;
6481    }
6482
6483    /**
6484     * @param resolveInfos list of resolve infos in descending priority order
6485     * @return if the list contains a resolve info with non-negative priority
6486     */
6487    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6488        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6489    }
6490
6491    private static boolean hasWebURI(Intent intent) {
6492        if (intent.getData() == null) {
6493            return false;
6494        }
6495        final String scheme = intent.getScheme();
6496        if (TextUtils.isEmpty(scheme)) {
6497            return false;
6498        }
6499        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6500    }
6501
6502    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6503            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6504            int userId) {
6505        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6506
6507        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6508            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6509                    candidates.size());
6510        }
6511
6512        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6513        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6514        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6515        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6516        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6517        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6518
6519        synchronized (mPackages) {
6520            final int count = candidates.size();
6521            // First, try to use linked apps. Partition the candidates into four lists:
6522            // one for the final results, one for the "do not use ever", one for "undefined status"
6523            // and finally one for "browser app type".
6524            for (int n=0; n<count; n++) {
6525                ResolveInfo info = candidates.get(n);
6526                String packageName = info.activityInfo.packageName;
6527                PackageSetting ps = mSettings.mPackages.get(packageName);
6528                if (ps != null) {
6529                    // Add to the special match all list (Browser use case)
6530                    if (info.handleAllWebDataURI) {
6531                        matchAllList.add(info);
6532                        continue;
6533                    }
6534                    // Try to get the status from User settings first
6535                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6536                    int status = (int)(packedStatus >> 32);
6537                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6538                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6539                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6540                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6541                                    + " : linkgen=" + linkGeneration);
6542                        }
6543                        // Use link-enabled generation as preferredOrder, i.e.
6544                        // prefer newly-enabled over earlier-enabled.
6545                        info.preferredOrder = linkGeneration;
6546                        alwaysList.add(info);
6547                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6548                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6549                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6550                        }
6551                        neverList.add(info);
6552                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6553                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6554                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6555                        }
6556                        alwaysAskList.add(info);
6557                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6558                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6559                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6560                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6561                        }
6562                        undefinedList.add(info);
6563                    }
6564                }
6565            }
6566
6567            // We'll want to include browser possibilities in a few cases
6568            boolean includeBrowser = false;
6569
6570            // First try to add the "always" resolution(s) for the current user, if any
6571            if (alwaysList.size() > 0) {
6572                result.addAll(alwaysList);
6573            } else {
6574                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6575                result.addAll(undefinedList);
6576                // Maybe add one for the other profile.
6577                if (xpDomainInfo != null && (
6578                        xpDomainInfo.bestDomainVerificationStatus
6579                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6580                    result.add(xpDomainInfo.resolveInfo);
6581                }
6582                includeBrowser = true;
6583            }
6584
6585            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6586            // If there were 'always' entries their preferred order has been set, so we also
6587            // back that off to make the alternatives equivalent
6588            if (alwaysAskList.size() > 0) {
6589                for (ResolveInfo i : result) {
6590                    i.preferredOrder = 0;
6591                }
6592                result.addAll(alwaysAskList);
6593                includeBrowser = true;
6594            }
6595
6596            if (includeBrowser) {
6597                // Also add browsers (all of them or only the default one)
6598                if (DEBUG_DOMAIN_VERIFICATION) {
6599                    Slog.v(TAG, "   ...including browsers in candidate set");
6600                }
6601                if ((matchFlags & MATCH_ALL) != 0) {
6602                    result.addAll(matchAllList);
6603                } else {
6604                    // Browser/generic handling case.  If there's a default browser, go straight
6605                    // to that (but only if there is no other higher-priority match).
6606                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6607                    int maxMatchPrio = 0;
6608                    ResolveInfo defaultBrowserMatch = null;
6609                    final int numCandidates = matchAllList.size();
6610                    for (int n = 0; n < numCandidates; n++) {
6611                        ResolveInfo info = matchAllList.get(n);
6612                        // track the highest overall match priority...
6613                        if (info.priority > maxMatchPrio) {
6614                            maxMatchPrio = info.priority;
6615                        }
6616                        // ...and the highest-priority default browser match
6617                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6618                            if (defaultBrowserMatch == null
6619                                    || (defaultBrowserMatch.priority < info.priority)) {
6620                                if (debug) {
6621                                    Slog.v(TAG, "Considering default browser match " + info);
6622                                }
6623                                defaultBrowserMatch = info;
6624                            }
6625                        }
6626                    }
6627                    if (defaultBrowserMatch != null
6628                            && defaultBrowserMatch.priority >= maxMatchPrio
6629                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6630                    {
6631                        if (debug) {
6632                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6633                        }
6634                        result.add(defaultBrowserMatch);
6635                    } else {
6636                        result.addAll(matchAllList);
6637                    }
6638                }
6639
6640                // If there is nothing selected, add all candidates and remove the ones that the user
6641                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6642                if (result.size() == 0) {
6643                    result.addAll(candidates);
6644                    result.removeAll(neverList);
6645                }
6646            }
6647        }
6648        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6649            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6650                    result.size());
6651            for (ResolveInfo info : result) {
6652                Slog.v(TAG, "  + " + info.activityInfo);
6653            }
6654        }
6655        return result;
6656    }
6657
6658    // Returns a packed value as a long:
6659    //
6660    // high 'int'-sized word: link status: undefined/ask/never/always.
6661    // low 'int'-sized word: relative priority among 'always' results.
6662    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6663        long result = ps.getDomainVerificationStatusForUser(userId);
6664        // if none available, get the master status
6665        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6666            if (ps.getIntentFilterVerificationInfo() != null) {
6667                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6668            }
6669        }
6670        return result;
6671    }
6672
6673    private ResolveInfo querySkipCurrentProfileIntents(
6674            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6675            int flags, int sourceUserId) {
6676        if (matchingFilters != null) {
6677            int size = matchingFilters.size();
6678            for (int i = 0; i < size; i ++) {
6679                CrossProfileIntentFilter filter = matchingFilters.get(i);
6680                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6681                    // Checking if there are activities in the target user that can handle the
6682                    // intent.
6683                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6684                            resolvedType, flags, sourceUserId);
6685                    if (resolveInfo != null) {
6686                        return resolveInfo;
6687                    }
6688                }
6689            }
6690        }
6691        return null;
6692    }
6693
6694    // Return matching ResolveInfo in target user if any.
6695    private ResolveInfo queryCrossProfileIntents(
6696            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6697            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6698        if (matchingFilters != null) {
6699            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6700            // match the same intent. For performance reasons, it is better not to
6701            // run queryIntent twice for the same userId
6702            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6703            int size = matchingFilters.size();
6704            for (int i = 0; i < size; i++) {
6705                CrossProfileIntentFilter filter = matchingFilters.get(i);
6706                int targetUserId = filter.getTargetUserId();
6707                boolean skipCurrentProfile =
6708                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6709                boolean skipCurrentProfileIfNoMatchFound =
6710                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6711                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6712                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6713                    // Checking if there are activities in the target user that can handle the
6714                    // intent.
6715                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6716                            resolvedType, flags, sourceUserId);
6717                    if (resolveInfo != null) return resolveInfo;
6718                    alreadyTriedUserIds.put(targetUserId, true);
6719                }
6720            }
6721        }
6722        return null;
6723    }
6724
6725    /**
6726     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6727     * will forward the intent to the filter's target user.
6728     * Otherwise, returns null.
6729     */
6730    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6731            String resolvedType, int flags, int sourceUserId) {
6732        int targetUserId = filter.getTargetUserId();
6733        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6734                resolvedType, flags, targetUserId);
6735        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6736            // If all the matches in the target profile are suspended, return null.
6737            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6738                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6739                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6740                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6741                            targetUserId);
6742                }
6743            }
6744        }
6745        return null;
6746    }
6747
6748    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6749            int sourceUserId, int targetUserId) {
6750        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6751        long ident = Binder.clearCallingIdentity();
6752        boolean targetIsProfile;
6753        try {
6754            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6755        } finally {
6756            Binder.restoreCallingIdentity(ident);
6757        }
6758        String className;
6759        if (targetIsProfile) {
6760            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6761        } else {
6762            className = FORWARD_INTENT_TO_PARENT;
6763        }
6764        ComponentName forwardingActivityComponentName = new ComponentName(
6765                mAndroidApplication.packageName, className);
6766        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6767                sourceUserId);
6768        if (!targetIsProfile) {
6769            forwardingActivityInfo.showUserIcon = targetUserId;
6770            forwardingResolveInfo.noResourceId = true;
6771        }
6772        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6773        forwardingResolveInfo.priority = 0;
6774        forwardingResolveInfo.preferredOrder = 0;
6775        forwardingResolveInfo.match = 0;
6776        forwardingResolveInfo.isDefault = true;
6777        forwardingResolveInfo.filter = filter;
6778        forwardingResolveInfo.targetUserId = targetUserId;
6779        return forwardingResolveInfo;
6780    }
6781
6782    @Override
6783    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6784            Intent[] specifics, String[] specificTypes, Intent intent,
6785            String resolvedType, int flags, int userId) {
6786        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6787                specificTypes, intent, resolvedType, flags, userId));
6788    }
6789
6790    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6791            Intent[] specifics, String[] specificTypes, Intent intent,
6792            String resolvedType, int flags, int userId) {
6793        if (!sUserManager.exists(userId)) return Collections.emptyList();
6794        flags = updateFlagsForResolve(flags, userId, intent, false);
6795        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6796                false /* requireFullPermission */, false /* checkShell */,
6797                "query intent activity options");
6798        final String resultsAction = intent.getAction();
6799
6800        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6801                | PackageManager.GET_RESOLVED_FILTER, userId);
6802
6803        if (DEBUG_INTENT_MATCHING) {
6804            Log.v(TAG, "Query " + intent + ": " + results);
6805        }
6806
6807        int specificsPos = 0;
6808        int N;
6809
6810        // todo: note that the algorithm used here is O(N^2).  This
6811        // isn't a problem in our current environment, but if we start running
6812        // into situations where we have more than 5 or 10 matches then this
6813        // should probably be changed to something smarter...
6814
6815        // First we go through and resolve each of the specific items
6816        // that were supplied, taking care of removing any corresponding
6817        // duplicate items in the generic resolve list.
6818        if (specifics != null) {
6819            for (int i=0; i<specifics.length; i++) {
6820                final Intent sintent = specifics[i];
6821                if (sintent == null) {
6822                    continue;
6823                }
6824
6825                if (DEBUG_INTENT_MATCHING) {
6826                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6827                }
6828
6829                String action = sintent.getAction();
6830                if (resultsAction != null && resultsAction.equals(action)) {
6831                    // If this action was explicitly requested, then don't
6832                    // remove things that have it.
6833                    action = null;
6834                }
6835
6836                ResolveInfo ri = null;
6837                ActivityInfo ai = null;
6838
6839                ComponentName comp = sintent.getComponent();
6840                if (comp == null) {
6841                    ri = resolveIntent(
6842                        sintent,
6843                        specificTypes != null ? specificTypes[i] : null,
6844                            flags, userId);
6845                    if (ri == null) {
6846                        continue;
6847                    }
6848                    if (ri == mResolveInfo) {
6849                        // ACK!  Must do something better with this.
6850                    }
6851                    ai = ri.activityInfo;
6852                    comp = new ComponentName(ai.applicationInfo.packageName,
6853                            ai.name);
6854                } else {
6855                    ai = getActivityInfo(comp, flags, userId);
6856                    if (ai == null) {
6857                        continue;
6858                    }
6859                }
6860
6861                // Look for any generic query activities that are duplicates
6862                // of this specific one, and remove them from the results.
6863                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6864                N = results.size();
6865                int j;
6866                for (j=specificsPos; j<N; j++) {
6867                    ResolveInfo sri = results.get(j);
6868                    if ((sri.activityInfo.name.equals(comp.getClassName())
6869                            && sri.activityInfo.applicationInfo.packageName.equals(
6870                                    comp.getPackageName()))
6871                        || (action != null && sri.filter.matchAction(action))) {
6872                        results.remove(j);
6873                        if (DEBUG_INTENT_MATCHING) Log.v(
6874                            TAG, "Removing duplicate item from " + j
6875                            + " due to specific " + specificsPos);
6876                        if (ri == null) {
6877                            ri = sri;
6878                        }
6879                        j--;
6880                        N--;
6881                    }
6882                }
6883
6884                // Add this specific item to its proper place.
6885                if (ri == null) {
6886                    ri = new ResolveInfo();
6887                    ri.activityInfo = ai;
6888                }
6889                results.add(specificsPos, ri);
6890                ri.specificIndex = i;
6891                specificsPos++;
6892            }
6893        }
6894
6895        // Now we go through the remaining generic results and remove any
6896        // duplicate actions that are found here.
6897        N = results.size();
6898        for (int i=specificsPos; i<N-1; i++) {
6899            final ResolveInfo rii = results.get(i);
6900            if (rii.filter == null) {
6901                continue;
6902            }
6903
6904            // Iterate over all of the actions of this result's intent
6905            // filter...  typically this should be just one.
6906            final Iterator<String> it = rii.filter.actionsIterator();
6907            if (it == null) {
6908                continue;
6909            }
6910            while (it.hasNext()) {
6911                final String action = it.next();
6912                if (resultsAction != null && resultsAction.equals(action)) {
6913                    // If this action was explicitly requested, then don't
6914                    // remove things that have it.
6915                    continue;
6916                }
6917                for (int j=i+1; j<N; j++) {
6918                    final ResolveInfo rij = results.get(j);
6919                    if (rij.filter != null && rij.filter.hasAction(action)) {
6920                        results.remove(j);
6921                        if (DEBUG_INTENT_MATCHING) Log.v(
6922                            TAG, "Removing duplicate item from " + j
6923                            + " due to action " + action + " at " + i);
6924                        j--;
6925                        N--;
6926                    }
6927                }
6928            }
6929
6930            // If the caller didn't request filter information, drop it now
6931            // so we don't have to marshall/unmarshall it.
6932            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6933                rii.filter = null;
6934            }
6935        }
6936
6937        // Filter out the caller activity if so requested.
6938        if (caller != null) {
6939            N = results.size();
6940            for (int i=0; i<N; i++) {
6941                ActivityInfo ainfo = results.get(i).activityInfo;
6942                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6943                        && caller.getClassName().equals(ainfo.name)) {
6944                    results.remove(i);
6945                    break;
6946                }
6947            }
6948        }
6949
6950        // If the caller didn't request filter information,
6951        // drop them now so we don't have to
6952        // marshall/unmarshall it.
6953        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6954            N = results.size();
6955            for (int i=0; i<N; i++) {
6956                results.get(i).filter = null;
6957            }
6958        }
6959
6960        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6961        return results;
6962    }
6963
6964    @Override
6965    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6966            String resolvedType, int flags, int userId) {
6967        return new ParceledListSlice<>(
6968                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6969    }
6970
6971    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6972            String resolvedType, int flags, int userId) {
6973        if (!sUserManager.exists(userId)) return Collections.emptyList();
6974        flags = updateFlagsForResolve(flags, userId, intent, false);
6975        ComponentName comp = intent.getComponent();
6976        if (comp == null) {
6977            if (intent.getSelector() != null) {
6978                intent = intent.getSelector();
6979                comp = intent.getComponent();
6980            }
6981        }
6982        if (comp != null) {
6983            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6984            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6985            if (ai != null) {
6986                ResolveInfo ri = new ResolveInfo();
6987                ri.activityInfo = ai;
6988                list.add(ri);
6989            }
6990            return list;
6991        }
6992
6993        // reader
6994        synchronized (mPackages) {
6995            String pkgName = intent.getPackage();
6996            if (pkgName == null) {
6997                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6998            }
6999            final PackageParser.Package pkg = mPackages.get(pkgName);
7000            if (pkg != null) {
7001                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7002                        userId);
7003            }
7004            return Collections.emptyList();
7005        }
7006    }
7007
7008    @Override
7009    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7010        if (!sUserManager.exists(userId)) return null;
7011        flags = updateFlagsForResolve(flags, userId, intent, false);
7012        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7013        if (query != null) {
7014            if (query.size() >= 1) {
7015                // If there is more than one service with the same priority,
7016                // just arbitrarily pick the first one.
7017                return query.get(0);
7018            }
7019        }
7020        return null;
7021    }
7022
7023    @Override
7024    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7025            String resolvedType, int flags, int userId) {
7026        return new ParceledListSlice<>(
7027                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7028    }
7029
7030    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7031            String resolvedType, int flags, int userId) {
7032        if (!sUserManager.exists(userId)) return Collections.emptyList();
7033        flags = updateFlagsForResolve(flags, userId, intent, false);
7034        ComponentName comp = intent.getComponent();
7035        if (comp == null) {
7036            if (intent.getSelector() != null) {
7037                intent = intent.getSelector();
7038                comp = intent.getComponent();
7039            }
7040        }
7041        if (comp != null) {
7042            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7043            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7044            if (si != null) {
7045                final ResolveInfo ri = new ResolveInfo();
7046                ri.serviceInfo = si;
7047                list.add(ri);
7048            }
7049            return list;
7050        }
7051
7052        // reader
7053        synchronized (mPackages) {
7054            String pkgName = intent.getPackage();
7055            if (pkgName == null) {
7056                return mServices.queryIntent(intent, resolvedType, flags, userId);
7057            }
7058            final PackageParser.Package pkg = mPackages.get(pkgName);
7059            if (pkg != null) {
7060                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7061                        userId);
7062            }
7063            return Collections.emptyList();
7064        }
7065    }
7066
7067    @Override
7068    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7069            String resolvedType, int flags, int userId) {
7070        return new ParceledListSlice<>(
7071                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7072    }
7073
7074    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7075            Intent intent, String resolvedType, int flags, int userId) {
7076        if (!sUserManager.exists(userId)) return Collections.emptyList();
7077        flags = updateFlagsForResolve(flags, userId, intent, false);
7078        ComponentName comp = intent.getComponent();
7079        if (comp == null) {
7080            if (intent.getSelector() != null) {
7081                intent = intent.getSelector();
7082                comp = intent.getComponent();
7083            }
7084        }
7085        if (comp != null) {
7086            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7087            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7088            if (pi != null) {
7089                final ResolveInfo ri = new ResolveInfo();
7090                ri.providerInfo = pi;
7091                list.add(ri);
7092            }
7093            return list;
7094        }
7095
7096        // reader
7097        synchronized (mPackages) {
7098            String pkgName = intent.getPackage();
7099            if (pkgName == null) {
7100                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7101            }
7102            final PackageParser.Package pkg = mPackages.get(pkgName);
7103            if (pkg != null) {
7104                return mProviders.queryIntentForPackage(
7105                        intent, resolvedType, flags, pkg.providers, userId);
7106            }
7107            return Collections.emptyList();
7108        }
7109    }
7110
7111    @Override
7112    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7113        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7114        flags = updateFlagsForPackage(flags, userId, null);
7115        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7116        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7117                true /* requireFullPermission */, false /* checkShell */,
7118                "get installed packages");
7119
7120        // writer
7121        synchronized (mPackages) {
7122            ArrayList<PackageInfo> list;
7123            if (listUninstalled) {
7124                list = new ArrayList<>(mSettings.mPackages.size());
7125                for (PackageSetting ps : mSettings.mPackages.values()) {
7126                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7127                        continue;
7128                    }
7129                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7130                    if (pi != null) {
7131                        list.add(pi);
7132                    }
7133                }
7134            } else {
7135                list = new ArrayList<>(mPackages.size());
7136                for (PackageParser.Package p : mPackages.values()) {
7137                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7138                            Binder.getCallingUid(), userId)) {
7139                        continue;
7140                    }
7141                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7142                            p.mExtras, flags, userId);
7143                    if (pi != null) {
7144                        list.add(pi);
7145                    }
7146                }
7147            }
7148
7149            return new ParceledListSlice<>(list);
7150        }
7151    }
7152
7153    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7154            String[] permissions, boolean[] tmp, int flags, int userId) {
7155        int numMatch = 0;
7156        final PermissionsState permissionsState = ps.getPermissionsState();
7157        for (int i=0; i<permissions.length; i++) {
7158            final String permission = permissions[i];
7159            if (permissionsState.hasPermission(permission, userId)) {
7160                tmp[i] = true;
7161                numMatch++;
7162            } else {
7163                tmp[i] = false;
7164            }
7165        }
7166        if (numMatch == 0) {
7167            return;
7168        }
7169        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7170
7171        // The above might return null in cases of uninstalled apps or install-state
7172        // skew across users/profiles.
7173        if (pi != null) {
7174            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7175                if (numMatch == permissions.length) {
7176                    pi.requestedPermissions = permissions;
7177                } else {
7178                    pi.requestedPermissions = new String[numMatch];
7179                    numMatch = 0;
7180                    for (int i=0; i<permissions.length; i++) {
7181                        if (tmp[i]) {
7182                            pi.requestedPermissions[numMatch] = permissions[i];
7183                            numMatch++;
7184                        }
7185                    }
7186                }
7187            }
7188            list.add(pi);
7189        }
7190    }
7191
7192    @Override
7193    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7194            String[] permissions, int flags, int userId) {
7195        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7196        flags = updateFlagsForPackage(flags, userId, permissions);
7197        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7198                true /* requireFullPermission */, false /* checkShell */,
7199                "get packages holding permissions");
7200        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7201
7202        // writer
7203        synchronized (mPackages) {
7204            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7205            boolean[] tmpBools = new boolean[permissions.length];
7206            if (listUninstalled) {
7207                for (PackageSetting ps : mSettings.mPackages.values()) {
7208                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7209                            userId);
7210                }
7211            } else {
7212                for (PackageParser.Package pkg : mPackages.values()) {
7213                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7214                    if (ps != null) {
7215                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7216                                userId);
7217                    }
7218                }
7219            }
7220
7221            return new ParceledListSlice<PackageInfo>(list);
7222        }
7223    }
7224
7225    @Override
7226    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7227        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7228        flags = updateFlagsForApplication(flags, userId, null);
7229        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7230
7231        // writer
7232        synchronized (mPackages) {
7233            ArrayList<ApplicationInfo> list;
7234            if (listUninstalled) {
7235                list = new ArrayList<>(mSettings.mPackages.size());
7236                for (PackageSetting ps : mSettings.mPackages.values()) {
7237                    ApplicationInfo ai;
7238                    int effectiveFlags = flags;
7239                    if (ps.isSystem()) {
7240                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7241                    }
7242                    if (ps.pkg != null) {
7243                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7244                            continue;
7245                        }
7246                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7247                                ps.readUserState(userId), userId);
7248                        if (ai != null) {
7249                            rebaseEnabledOverlays(ai, userId);
7250                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7251                        }
7252                    } else {
7253                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7254                        // and already converts to externally visible package name
7255                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7256                                Binder.getCallingUid(), effectiveFlags, userId);
7257                    }
7258                    if (ai != null) {
7259                        list.add(ai);
7260                    }
7261                }
7262            } else {
7263                list = new ArrayList<>(mPackages.size());
7264                for (PackageParser.Package p : mPackages.values()) {
7265                    if (p.mExtras != null) {
7266                        PackageSetting ps = (PackageSetting) p.mExtras;
7267                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7268                            continue;
7269                        }
7270                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7271                                ps.readUserState(userId), userId);
7272                        if (ai != null) {
7273                            rebaseEnabledOverlays(ai, userId);
7274                            ai.packageName = resolveExternalPackageNameLPr(p);
7275                            list.add(ai);
7276                        }
7277                    }
7278                }
7279            }
7280
7281            return new ParceledListSlice<>(list);
7282        }
7283    }
7284
7285    @Override
7286    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7287        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7288            return null;
7289        }
7290
7291        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7292                "getEphemeralApplications");
7293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7294                true /* requireFullPermission */, false /* checkShell */,
7295                "getEphemeralApplications");
7296        synchronized (mPackages) {
7297            List<InstantAppInfo> instantApps = mInstantAppRegistry
7298                    .getInstantAppsLPr(userId);
7299            if (instantApps != null) {
7300                return new ParceledListSlice<>(instantApps);
7301            }
7302        }
7303        return null;
7304    }
7305
7306    @Override
7307    public boolean isInstantApp(String packageName, int userId) {
7308        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7309                true /* requireFullPermission */, false /* checkShell */,
7310                "isInstantApp");
7311        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7312            return false;
7313        }
7314
7315        synchronized (mPackages) {
7316            final PackageSetting ps = mSettings.mPackages.get(packageName);
7317            final boolean returnAllowed =
7318                    ps != null
7319                    && (isCallerSameApp(packageName)
7320                            || mContext.checkCallingOrSelfPermission(
7321                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7322                                            == PERMISSION_GRANTED
7323                            || mInstantAppRegistry.isInstantAccessGranted(
7324                                    userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId));
7325            if (returnAllowed) {
7326                return ps.getInstantApp(userId);
7327            }
7328        }
7329        return false;
7330    }
7331
7332    @Override
7333    public byte[] getInstantAppCookie(String packageName, int userId) {
7334        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7335            return null;
7336        }
7337
7338        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7339                true /* requireFullPermission */, false /* checkShell */,
7340                "getInstantAppCookie");
7341        if (!isCallerSameApp(packageName)) {
7342            return null;
7343        }
7344        synchronized (mPackages) {
7345            return mInstantAppRegistry.getInstantAppCookieLPw(
7346                    packageName, userId);
7347        }
7348    }
7349
7350    @Override
7351    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7352        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7353            return true;
7354        }
7355
7356        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7357                true /* requireFullPermission */, true /* checkShell */,
7358                "setInstantAppCookie");
7359        if (!isCallerSameApp(packageName)) {
7360            return false;
7361        }
7362        synchronized (mPackages) {
7363            return mInstantAppRegistry.setInstantAppCookieLPw(
7364                    packageName, cookie, userId);
7365        }
7366    }
7367
7368    @Override
7369    public Bitmap getInstantAppIcon(String packageName, int userId) {
7370        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7371            return null;
7372        }
7373
7374        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7375                "getInstantAppIcon");
7376
7377        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7378                true /* requireFullPermission */, false /* checkShell */,
7379                "getInstantAppIcon");
7380
7381        synchronized (mPackages) {
7382            return mInstantAppRegistry.getInstantAppIconLPw(
7383                    packageName, userId);
7384        }
7385    }
7386
7387    private boolean isCallerSameApp(String packageName) {
7388        PackageParser.Package pkg = mPackages.get(packageName);
7389        return pkg != null
7390                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7391    }
7392
7393    @Override
7394    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7395        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7396    }
7397
7398    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7399        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7400
7401        // reader
7402        synchronized (mPackages) {
7403            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7404            final int userId = UserHandle.getCallingUserId();
7405            while (i.hasNext()) {
7406                final PackageParser.Package p = i.next();
7407                if (p.applicationInfo == null) continue;
7408
7409                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7410                        && !p.applicationInfo.isDirectBootAware();
7411                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7412                        && p.applicationInfo.isDirectBootAware();
7413
7414                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7415                        && (!mSafeMode || isSystemApp(p))
7416                        && (matchesUnaware || matchesAware)) {
7417                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7418                    if (ps != null) {
7419                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7420                                ps.readUserState(userId), userId);
7421                        if (ai != null) {
7422                            rebaseEnabledOverlays(ai, userId);
7423                            finalList.add(ai);
7424                        }
7425                    }
7426                }
7427            }
7428        }
7429
7430        return finalList;
7431    }
7432
7433    @Override
7434    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7435        if (!sUserManager.exists(userId)) return null;
7436        flags = updateFlagsForComponent(flags, userId, name);
7437        // reader
7438        synchronized (mPackages) {
7439            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7440            PackageSetting ps = provider != null
7441                    ? mSettings.mPackages.get(provider.owner.packageName)
7442                    : null;
7443            return ps != null
7444                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7445                    ? PackageParser.generateProviderInfo(provider, flags,
7446                            ps.readUserState(userId), userId)
7447                    : null;
7448        }
7449    }
7450
7451    /**
7452     * @deprecated
7453     */
7454    @Deprecated
7455    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7456        // reader
7457        synchronized (mPackages) {
7458            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7459                    .entrySet().iterator();
7460            final int userId = UserHandle.getCallingUserId();
7461            while (i.hasNext()) {
7462                Map.Entry<String, PackageParser.Provider> entry = i.next();
7463                PackageParser.Provider p = entry.getValue();
7464                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7465
7466                if (ps != null && p.syncable
7467                        && (!mSafeMode || (p.info.applicationInfo.flags
7468                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7469                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7470                            ps.readUserState(userId), userId);
7471                    if (info != null) {
7472                        outNames.add(entry.getKey());
7473                        outInfo.add(info);
7474                    }
7475                }
7476            }
7477        }
7478    }
7479
7480    @Override
7481    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7482            int uid, int flags, String metaDataKey) {
7483        final int userId = processName != null ? UserHandle.getUserId(uid)
7484                : UserHandle.getCallingUserId();
7485        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7486        flags = updateFlagsForComponent(flags, userId, processName);
7487
7488        ArrayList<ProviderInfo> finalList = null;
7489        // reader
7490        synchronized (mPackages) {
7491            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7492            while (i.hasNext()) {
7493                final PackageParser.Provider p = i.next();
7494                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7495                if (ps != null && p.info.authority != null
7496                        && (processName == null
7497                                || (p.info.processName.equals(processName)
7498                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7499                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7500
7501                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7502                    // parameter.
7503                    if (metaDataKey != null
7504                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7505                        continue;
7506                    }
7507
7508                    if (finalList == null) {
7509                        finalList = new ArrayList<ProviderInfo>(3);
7510                    }
7511                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7512                            ps.readUserState(userId), userId);
7513                    if (info != null) {
7514                        finalList.add(info);
7515                    }
7516                }
7517            }
7518        }
7519
7520        if (finalList != null) {
7521            Collections.sort(finalList, mProviderInitOrderSorter);
7522            return new ParceledListSlice<ProviderInfo>(finalList);
7523        }
7524
7525        return ParceledListSlice.emptyList();
7526    }
7527
7528    @Override
7529    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7530        // reader
7531        synchronized (mPackages) {
7532            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7533            return PackageParser.generateInstrumentationInfo(i, flags);
7534        }
7535    }
7536
7537    @Override
7538    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7539            String targetPackage, int flags) {
7540        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7541    }
7542
7543    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7544            int flags) {
7545        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7546
7547        // reader
7548        synchronized (mPackages) {
7549            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7550            while (i.hasNext()) {
7551                final PackageParser.Instrumentation p = i.next();
7552                if (targetPackage == null
7553                        || targetPackage.equals(p.info.targetPackage)) {
7554                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7555                            flags);
7556                    if (ii != null) {
7557                        finalList.add(ii);
7558                    }
7559                }
7560            }
7561        }
7562
7563        return finalList;
7564    }
7565
7566    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7567        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7568        try {
7569            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7570        } finally {
7571            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7572        }
7573    }
7574
7575    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7576        final File[] files = dir.listFiles();
7577        if (ArrayUtils.isEmpty(files)) {
7578            Log.d(TAG, "No files in app dir " + dir);
7579            return;
7580        }
7581
7582        if (DEBUG_PACKAGE_SCANNING) {
7583            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7584                    + " flags=0x" + Integer.toHexString(parseFlags));
7585        }
7586        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7587                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7588
7589        // Submit files for parsing in parallel
7590        int fileCount = 0;
7591        for (File file : files) {
7592            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7593                    && !PackageInstallerService.isStageName(file.getName());
7594            if (!isPackage) {
7595                // Ignore entries which are not packages
7596                continue;
7597            }
7598            parallelPackageParser.submit(file, parseFlags);
7599            fileCount++;
7600        }
7601
7602        // Process results one by one
7603        for (; fileCount > 0; fileCount--) {
7604            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7605            Throwable throwable = parseResult.throwable;
7606            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7607
7608            if (throwable == null) {
7609                // Static shared libraries have synthetic package names
7610                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7611                    renameStaticSharedLibraryPackage(parseResult.pkg);
7612                }
7613                try {
7614                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7615                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7616                                currentTime, null);
7617                    }
7618                } catch (PackageManagerException e) {
7619                    errorCode = e.error;
7620                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7621                }
7622            } else if (throwable instanceof PackageParser.PackageParserException) {
7623                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7624                        throwable;
7625                errorCode = e.error;
7626                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7627            } else {
7628                throw new IllegalStateException("Unexpected exception occurred while parsing "
7629                        + parseResult.scanFile, throwable);
7630            }
7631
7632            // Delete invalid userdata apps
7633            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7634                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7635                logCriticalInfo(Log.WARN,
7636                        "Deleting invalid package at " + parseResult.scanFile);
7637                removeCodePathLI(parseResult.scanFile);
7638            }
7639        }
7640        parallelPackageParser.close();
7641    }
7642
7643    private static File getSettingsProblemFile() {
7644        File dataDir = Environment.getDataDirectory();
7645        File systemDir = new File(dataDir, "system");
7646        File fname = new File(systemDir, "uiderrors.txt");
7647        return fname;
7648    }
7649
7650    static void reportSettingsProblem(int priority, String msg) {
7651        logCriticalInfo(priority, msg);
7652    }
7653
7654    public static void logCriticalInfo(int priority, String msg) {
7655        Slog.println(priority, TAG, msg);
7656        EventLogTags.writePmCriticalInfo(msg);
7657        try {
7658            File fname = getSettingsProblemFile();
7659            FileOutputStream out = new FileOutputStream(fname, true);
7660            PrintWriter pw = new FastPrintWriter(out);
7661            SimpleDateFormat formatter = new SimpleDateFormat();
7662            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7663            pw.println(dateString + ": " + msg);
7664            pw.close();
7665            FileUtils.setPermissions(
7666                    fname.toString(),
7667                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7668                    -1, -1);
7669        } catch (java.io.IOException e) {
7670        }
7671    }
7672
7673    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7674        if (srcFile.isDirectory()) {
7675            final File baseFile = new File(pkg.baseCodePath);
7676            long maxModifiedTime = baseFile.lastModified();
7677            if (pkg.splitCodePaths != null) {
7678                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7679                    final File splitFile = new File(pkg.splitCodePaths[i]);
7680                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7681                }
7682            }
7683            return maxModifiedTime;
7684        }
7685        return srcFile.lastModified();
7686    }
7687
7688    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7689            final int policyFlags) throws PackageManagerException {
7690        // When upgrading from pre-N MR1, verify the package time stamp using the package
7691        // directory and not the APK file.
7692        final long lastModifiedTime = mIsPreNMR1Upgrade
7693                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7694        if (ps != null
7695                && ps.codePath.equals(srcFile)
7696                && ps.timeStamp == lastModifiedTime
7697                && !isCompatSignatureUpdateNeeded(pkg)
7698                && !isRecoverSignatureUpdateNeeded(pkg)) {
7699            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7700            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7701            ArraySet<PublicKey> signingKs;
7702            synchronized (mPackages) {
7703                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7704            }
7705            if (ps.signatures.mSignatures != null
7706                    && ps.signatures.mSignatures.length != 0
7707                    && signingKs != null) {
7708                // Optimization: reuse the existing cached certificates
7709                // if the package appears to be unchanged.
7710                pkg.mSignatures = ps.signatures.mSignatures;
7711                pkg.mSigningKeys = signingKs;
7712                return;
7713            }
7714
7715            Slog.w(TAG, "PackageSetting for " + ps.name
7716                    + " is missing signatures.  Collecting certs again to recover them.");
7717        } else {
7718            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7719        }
7720
7721        try {
7722            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7723            PackageParser.collectCertificates(pkg, policyFlags);
7724        } catch (PackageParserException e) {
7725            throw PackageManagerException.from(e);
7726        } finally {
7727            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7728        }
7729    }
7730
7731    /**
7732     *  Traces a package scan.
7733     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7734     */
7735    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7736            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7737        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7738        try {
7739            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7740        } finally {
7741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7742        }
7743    }
7744
7745    /**
7746     *  Scans a package and returns the newly parsed package.
7747     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7748     */
7749    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7750            long currentTime, UserHandle user) throws PackageManagerException {
7751        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7752        PackageParser pp = new PackageParser();
7753        pp.setSeparateProcesses(mSeparateProcesses);
7754        pp.setOnlyCoreApps(mOnlyCore);
7755        pp.setDisplayMetrics(mMetrics);
7756        pp.setCallback(mPackageParserCallback);
7757
7758        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7759            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7760        }
7761
7762        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7763        final PackageParser.Package pkg;
7764        try {
7765            pkg = pp.parsePackage(scanFile, parseFlags);
7766        } catch (PackageParserException e) {
7767            throw PackageManagerException.from(e);
7768        } finally {
7769            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7770        }
7771
7772        // Static shared libraries have synthetic package names
7773        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7774            renameStaticSharedLibraryPackage(pkg);
7775        }
7776
7777        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7778    }
7779
7780    /**
7781     *  Scans a package and returns the newly parsed package.
7782     *  @throws PackageManagerException on a parse error.
7783     */
7784    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7785            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7786            throws PackageManagerException {
7787        // If the package has children and this is the first dive in the function
7788        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7789        // packages (parent and children) would be successfully scanned before the
7790        // actual scan since scanning mutates internal state and we want to atomically
7791        // install the package and its children.
7792        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7793            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7794                scanFlags |= SCAN_CHECK_ONLY;
7795            }
7796        } else {
7797            scanFlags &= ~SCAN_CHECK_ONLY;
7798        }
7799
7800        // Scan the parent
7801        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7802                scanFlags, currentTime, user);
7803
7804        // Scan the children
7805        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7806        for (int i = 0; i < childCount; i++) {
7807            PackageParser.Package childPackage = pkg.childPackages.get(i);
7808            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7809                    currentTime, user);
7810        }
7811
7812
7813        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7814            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7815        }
7816
7817        return scannedPkg;
7818    }
7819
7820    /**
7821     *  Scans a package and returns the newly parsed package.
7822     *  @throws PackageManagerException on a parse error.
7823     */
7824    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7825            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7826            throws PackageManagerException {
7827        PackageSetting ps = null;
7828        PackageSetting updatedPkg;
7829        // reader
7830        synchronized (mPackages) {
7831            // Look to see if we already know about this package.
7832            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7833            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7834                // This package has been renamed to its original name.  Let's
7835                // use that.
7836                ps = mSettings.getPackageLPr(oldName);
7837            }
7838            // If there was no original package, see one for the real package name.
7839            if (ps == null) {
7840                ps = mSettings.getPackageLPr(pkg.packageName);
7841            }
7842            // Check to see if this package could be hiding/updating a system
7843            // package.  Must look for it either under the original or real
7844            // package name depending on our state.
7845            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7846            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7847
7848            // If this is a package we don't know about on the system partition, we
7849            // may need to remove disabled child packages on the system partition
7850            // or may need to not add child packages if the parent apk is updated
7851            // on the data partition and no longer defines this child package.
7852            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7853                // If this is a parent package for an updated system app and this system
7854                // app got an OTA update which no longer defines some of the child packages
7855                // we have to prune them from the disabled system packages.
7856                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7857                if (disabledPs != null) {
7858                    final int scannedChildCount = (pkg.childPackages != null)
7859                            ? pkg.childPackages.size() : 0;
7860                    final int disabledChildCount = disabledPs.childPackageNames != null
7861                            ? disabledPs.childPackageNames.size() : 0;
7862                    for (int i = 0; i < disabledChildCount; i++) {
7863                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7864                        boolean disabledPackageAvailable = false;
7865                        for (int j = 0; j < scannedChildCount; j++) {
7866                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7867                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7868                                disabledPackageAvailable = true;
7869                                break;
7870                            }
7871                         }
7872                         if (!disabledPackageAvailable) {
7873                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7874                         }
7875                    }
7876                }
7877            }
7878        }
7879
7880        boolean updatedPkgBetter = false;
7881        // First check if this is a system package that may involve an update
7882        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7883            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7884            // it needs to drop FLAG_PRIVILEGED.
7885            if (locationIsPrivileged(scanFile)) {
7886                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7887            } else {
7888                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7889            }
7890
7891            if (ps != null && !ps.codePath.equals(scanFile)) {
7892                // The path has changed from what was last scanned...  check the
7893                // version of the new path against what we have stored to determine
7894                // what to do.
7895                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7896                if (pkg.mVersionCode <= ps.versionCode) {
7897                    // The system package has been updated and the code path does not match
7898                    // Ignore entry. Skip it.
7899                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7900                            + " ignored: updated version " + ps.versionCode
7901                            + " better than this " + pkg.mVersionCode);
7902                    if (!updatedPkg.codePath.equals(scanFile)) {
7903                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7904                                + ps.name + " changing from " + updatedPkg.codePathString
7905                                + " to " + scanFile);
7906                        updatedPkg.codePath = scanFile;
7907                        updatedPkg.codePathString = scanFile.toString();
7908                        updatedPkg.resourcePath = scanFile;
7909                        updatedPkg.resourcePathString = scanFile.toString();
7910                    }
7911                    updatedPkg.pkg = pkg;
7912                    updatedPkg.versionCode = pkg.mVersionCode;
7913
7914                    // Update the disabled system child packages to point to the package too.
7915                    final int childCount = updatedPkg.childPackageNames != null
7916                            ? updatedPkg.childPackageNames.size() : 0;
7917                    for (int i = 0; i < childCount; i++) {
7918                        String childPackageName = updatedPkg.childPackageNames.get(i);
7919                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7920                                childPackageName);
7921                        if (updatedChildPkg != null) {
7922                            updatedChildPkg.pkg = pkg;
7923                            updatedChildPkg.versionCode = pkg.mVersionCode;
7924                        }
7925                    }
7926
7927                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7928                            + scanFile + " ignored: updated version " + ps.versionCode
7929                            + " better than this " + pkg.mVersionCode);
7930                } else {
7931                    // The current app on the system partition is better than
7932                    // what we have updated to on the data partition; switch
7933                    // back to the system partition version.
7934                    // At this point, its safely assumed that package installation for
7935                    // apps in system partition will go through. If not there won't be a working
7936                    // version of the app
7937                    // writer
7938                    synchronized (mPackages) {
7939                        // Just remove the loaded entries from package lists.
7940                        mPackages.remove(ps.name);
7941                    }
7942
7943                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7944                            + " reverting from " + ps.codePathString
7945                            + ": new version " + pkg.mVersionCode
7946                            + " better than installed " + ps.versionCode);
7947
7948                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7949                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7950                    synchronized (mInstallLock) {
7951                        args.cleanUpResourcesLI();
7952                    }
7953                    synchronized (mPackages) {
7954                        mSettings.enableSystemPackageLPw(ps.name);
7955                    }
7956                    updatedPkgBetter = true;
7957                }
7958            }
7959        }
7960
7961        if (updatedPkg != null) {
7962            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7963            // initially
7964            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7965
7966            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7967            // flag set initially
7968            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7969                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7970            }
7971        }
7972
7973        // Verify certificates against what was last scanned
7974        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7975
7976        /*
7977         * A new system app appeared, but we already had a non-system one of the
7978         * same name installed earlier.
7979         */
7980        boolean shouldHideSystemApp = false;
7981        if (updatedPkg == null && ps != null
7982                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7983            /*
7984             * Check to make sure the signatures match first. If they don't,
7985             * wipe the installed application and its data.
7986             */
7987            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7988                    != PackageManager.SIGNATURE_MATCH) {
7989                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7990                        + " signatures don't match existing userdata copy; removing");
7991                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7992                        "scanPackageInternalLI")) {
7993                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7994                }
7995                ps = null;
7996            } else {
7997                /*
7998                 * If the newly-added system app is an older version than the
7999                 * already installed version, hide it. It will be scanned later
8000                 * and re-added like an update.
8001                 */
8002                if (pkg.mVersionCode <= ps.versionCode) {
8003                    shouldHideSystemApp = true;
8004                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8005                            + " but new version " + pkg.mVersionCode + " better than installed "
8006                            + ps.versionCode + "; hiding system");
8007                } else {
8008                    /*
8009                     * The newly found system app is a newer version that the
8010                     * one previously installed. Simply remove the
8011                     * already-installed application and replace it with our own
8012                     * while keeping the application data.
8013                     */
8014                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8015                            + " reverting from " + ps.codePathString + ": new version "
8016                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8017                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8018                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8019                    synchronized (mInstallLock) {
8020                        args.cleanUpResourcesLI();
8021                    }
8022                }
8023            }
8024        }
8025
8026        // The apk is forward locked (not public) if its code and resources
8027        // are kept in different files. (except for app in either system or
8028        // vendor path).
8029        // TODO grab this value from PackageSettings
8030        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8031            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8032                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8033            }
8034        }
8035
8036        // TODO: extend to support forward-locked splits
8037        String resourcePath = null;
8038        String baseResourcePath = null;
8039        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8040            if (ps != null && ps.resourcePathString != null) {
8041                resourcePath = ps.resourcePathString;
8042                baseResourcePath = ps.resourcePathString;
8043            } else {
8044                // Should not happen at all. Just log an error.
8045                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8046            }
8047        } else {
8048            resourcePath = pkg.codePath;
8049            baseResourcePath = pkg.baseCodePath;
8050        }
8051
8052        // Set application objects path explicitly.
8053        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8054        pkg.setApplicationInfoCodePath(pkg.codePath);
8055        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8056        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8057        pkg.setApplicationInfoResourcePath(resourcePath);
8058        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8059        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8060
8061        final int userId = ((user == null) ? 0 : user.getIdentifier());
8062        if (ps != null && ps.getInstantApp(userId)) {
8063            scanFlags |= SCAN_AS_INSTANT_APP;
8064        }
8065
8066        // Note that we invoke the following method only if we are about to unpack an application
8067        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8068                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8069
8070        /*
8071         * If the system app should be overridden by a previously installed
8072         * data, hide the system app now and let the /data/app scan pick it up
8073         * again.
8074         */
8075        if (shouldHideSystemApp) {
8076            synchronized (mPackages) {
8077                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8078            }
8079        }
8080
8081        return scannedPkg;
8082    }
8083
8084    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8085        // Derive the new package synthetic package name
8086        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8087                + pkg.staticSharedLibVersion);
8088    }
8089
8090    private static String fixProcessName(String defProcessName,
8091            String processName) {
8092        if (processName == null) {
8093            return defProcessName;
8094        }
8095        return processName;
8096    }
8097
8098    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8099            throws PackageManagerException {
8100        if (pkgSetting.signatures.mSignatures != null) {
8101            // Already existing package. Make sure signatures match
8102            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8103                    == PackageManager.SIGNATURE_MATCH;
8104            if (!match) {
8105                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8106                        == PackageManager.SIGNATURE_MATCH;
8107            }
8108            if (!match) {
8109                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8110                        == PackageManager.SIGNATURE_MATCH;
8111            }
8112            if (!match) {
8113                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8114                        + pkg.packageName + " signatures do not match the "
8115                        + "previously installed version; ignoring!");
8116            }
8117        }
8118
8119        // Check for shared user signatures
8120        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8121            // Already existing package. Make sure signatures match
8122            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8123                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8124            if (!match) {
8125                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8126                        == PackageManager.SIGNATURE_MATCH;
8127            }
8128            if (!match) {
8129                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8130                        == PackageManager.SIGNATURE_MATCH;
8131            }
8132            if (!match) {
8133                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8134                        "Package " + pkg.packageName
8135                        + " has no signatures that match those in shared user "
8136                        + pkgSetting.sharedUser.name + "; ignoring!");
8137            }
8138        }
8139    }
8140
8141    /**
8142     * Enforces that only the system UID or root's UID can call a method exposed
8143     * via Binder.
8144     *
8145     * @param message used as message if SecurityException is thrown
8146     * @throws SecurityException if the caller is not system or root
8147     */
8148    private static final void enforceSystemOrRoot(String message) {
8149        final int uid = Binder.getCallingUid();
8150        if (uid != Process.SYSTEM_UID && uid != 0) {
8151            throw new SecurityException(message);
8152        }
8153    }
8154
8155    @Override
8156    public void performFstrimIfNeeded() {
8157        enforceSystemOrRoot("Only the system can request fstrim");
8158
8159        // Before everything else, see whether we need to fstrim.
8160        try {
8161            IStorageManager sm = PackageHelper.getStorageManager();
8162            if (sm != null) {
8163                boolean doTrim = false;
8164                final long interval = android.provider.Settings.Global.getLong(
8165                        mContext.getContentResolver(),
8166                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8167                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8168                if (interval > 0) {
8169                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8170                    if (timeSinceLast > interval) {
8171                        doTrim = true;
8172                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8173                                + "; running immediately");
8174                    }
8175                }
8176                if (doTrim) {
8177                    final boolean dexOptDialogShown;
8178                    synchronized (mPackages) {
8179                        dexOptDialogShown = mDexOptDialogShown;
8180                    }
8181                    if (!isFirstBoot() && dexOptDialogShown) {
8182                        try {
8183                            ActivityManager.getService().showBootMessage(
8184                                    mContext.getResources().getString(
8185                                            R.string.android_upgrading_fstrim), true);
8186                        } catch (RemoteException e) {
8187                        }
8188                    }
8189                    sm.runMaintenance();
8190                }
8191            } else {
8192                Slog.e(TAG, "storageManager service unavailable!");
8193            }
8194        } catch (RemoteException e) {
8195            // Can't happen; StorageManagerService is local
8196        }
8197    }
8198
8199    @Override
8200    public void updatePackagesIfNeeded() {
8201        enforceSystemOrRoot("Only the system can request package update");
8202
8203        // We need to re-extract after an OTA.
8204        boolean causeUpgrade = isUpgrade();
8205
8206        // First boot or factory reset.
8207        // Note: we also handle devices that are upgrading to N right now as if it is their
8208        //       first boot, as they do not have profile data.
8209        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8210
8211        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8212        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8213
8214        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8215            return;
8216        }
8217
8218        List<PackageParser.Package> pkgs;
8219        synchronized (mPackages) {
8220            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8221        }
8222
8223        final long startTime = System.nanoTime();
8224        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8225                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8226
8227        final int elapsedTimeSeconds =
8228                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8229
8230        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8231        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8232        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8233        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8234        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8235    }
8236
8237    /**
8238     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8239     * containing statistics about the invocation. The array consists of three elements,
8240     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8241     * and {@code numberOfPackagesFailed}.
8242     */
8243    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8244            String compilerFilter) {
8245
8246        int numberOfPackagesVisited = 0;
8247        int numberOfPackagesOptimized = 0;
8248        int numberOfPackagesSkipped = 0;
8249        int numberOfPackagesFailed = 0;
8250        final int numberOfPackagesToDexopt = pkgs.size();
8251
8252        for (PackageParser.Package pkg : pkgs) {
8253            numberOfPackagesVisited++;
8254
8255            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8256                if (DEBUG_DEXOPT) {
8257                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8258                }
8259                numberOfPackagesSkipped++;
8260                continue;
8261            }
8262
8263            if (DEBUG_DEXOPT) {
8264                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8265                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8266            }
8267
8268            if (showDialog) {
8269                try {
8270                    ActivityManager.getService().showBootMessage(
8271                            mContext.getResources().getString(R.string.android_upgrading_apk,
8272                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8273                } catch (RemoteException e) {
8274                }
8275                synchronized (mPackages) {
8276                    mDexOptDialogShown = true;
8277                }
8278            }
8279
8280            // If the OTA updates a system app which was previously preopted to a non-preopted state
8281            // the app might end up being verified at runtime. That's because by default the apps
8282            // are verify-profile but for preopted apps there's no profile.
8283            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8284            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8285            // filter (by default interpret-only).
8286            // Note that at this stage unused apps are already filtered.
8287            if (isSystemApp(pkg) &&
8288                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8289                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8290                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8291            }
8292
8293            // checkProfiles is false to avoid merging profiles during boot which
8294            // might interfere with background compilation (b/28612421).
8295            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8296            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8297            // trade-off worth doing to save boot time work.
8298            int dexOptStatus = performDexOptTraced(pkg.packageName,
8299                    false /* checkProfiles */,
8300                    compilerFilter,
8301                    false /* force */);
8302            switch (dexOptStatus) {
8303                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8304                    numberOfPackagesOptimized++;
8305                    break;
8306                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8307                    numberOfPackagesSkipped++;
8308                    break;
8309                case PackageDexOptimizer.DEX_OPT_FAILED:
8310                    numberOfPackagesFailed++;
8311                    break;
8312                default:
8313                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8314                    break;
8315            }
8316        }
8317
8318        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8319                numberOfPackagesFailed };
8320    }
8321
8322    @Override
8323    public void notifyPackageUse(String packageName, int reason) {
8324        synchronized (mPackages) {
8325            PackageParser.Package p = mPackages.get(packageName);
8326            if (p == null) {
8327                return;
8328            }
8329            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8330        }
8331    }
8332
8333    @Override
8334    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8335        int userId = UserHandle.getCallingUserId();
8336        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8337        if (ai == null) {
8338            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8339                + loadingPackageName + ", user=" + userId);
8340            return;
8341        }
8342        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8343    }
8344
8345    // TODO: this is not used nor needed. Delete it.
8346    @Override
8347    public boolean performDexOptIfNeeded(String packageName) {
8348        int dexOptStatus = performDexOptTraced(packageName,
8349                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8350        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8351    }
8352
8353    @Override
8354    public boolean performDexOpt(String packageName,
8355            boolean checkProfiles, int compileReason, boolean force) {
8356        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8357                getCompilerFilterForReason(compileReason), force);
8358        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8359    }
8360
8361    @Override
8362    public boolean performDexOptMode(String packageName,
8363            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8364        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8365                targetCompilerFilter, force);
8366        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8367    }
8368
8369    private int performDexOptTraced(String packageName,
8370                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8371        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8372        try {
8373            return performDexOptInternal(packageName, checkProfiles,
8374                    targetCompilerFilter, force);
8375        } finally {
8376            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8377        }
8378    }
8379
8380    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8381    // if the package can now be considered up to date for the given filter.
8382    private int performDexOptInternal(String packageName,
8383                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8384        PackageParser.Package p;
8385        synchronized (mPackages) {
8386            p = mPackages.get(packageName);
8387            if (p == null) {
8388                // Package could not be found. Report failure.
8389                return PackageDexOptimizer.DEX_OPT_FAILED;
8390            }
8391            mPackageUsage.maybeWriteAsync(mPackages);
8392            mCompilerStats.maybeWriteAsync();
8393        }
8394        long callingId = Binder.clearCallingIdentity();
8395        try {
8396            synchronized (mInstallLock) {
8397                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8398                        targetCompilerFilter, force);
8399            }
8400        } finally {
8401            Binder.restoreCallingIdentity(callingId);
8402        }
8403    }
8404
8405    public ArraySet<String> getOptimizablePackages() {
8406        ArraySet<String> pkgs = new ArraySet<String>();
8407        synchronized (mPackages) {
8408            for (PackageParser.Package p : mPackages.values()) {
8409                if (PackageDexOptimizer.canOptimizePackage(p)) {
8410                    pkgs.add(p.packageName);
8411                }
8412            }
8413        }
8414        return pkgs;
8415    }
8416
8417    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8418            boolean checkProfiles, String targetCompilerFilter,
8419            boolean force) {
8420        // Select the dex optimizer based on the force parameter.
8421        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8422        //       allocate an object here.
8423        PackageDexOptimizer pdo = force
8424                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8425                : mPackageDexOptimizer;
8426
8427        // Optimize all dependencies first. Note: we ignore the return value and march on
8428        // on errors.
8429        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8430        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8431        if (!deps.isEmpty()) {
8432            for (PackageParser.Package depPackage : deps) {
8433                // TODO: Analyze and investigate if we (should) profile libraries.
8434                // Currently this will do a full compilation of the library by default.
8435                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8436                        false /* checkProfiles */,
8437                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8438                        getOrCreateCompilerPackageStats(depPackage),
8439                        mDexManager.isUsedByOtherApps(p.packageName));
8440            }
8441        }
8442        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8443                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8444                mDexManager.isUsedByOtherApps(p.packageName));
8445    }
8446
8447    // Performs dexopt on the used secondary dex files belonging to the given package.
8448    // Returns true if all dex files were process successfully (which could mean either dexopt or
8449    // skip). Returns false if any of the files caused errors.
8450    @Override
8451    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8452            boolean force) {
8453        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8454    }
8455
8456    /**
8457     * Reconcile the information we have about the secondary dex files belonging to
8458     * {@code packagName} and the actual dex files. For all dex files that were
8459     * deleted, update the internal records and delete the generated oat files.
8460     */
8461    @Override
8462    public void reconcileSecondaryDexFiles(String packageName) {
8463        mDexManager.reconcileSecondaryDexFiles(packageName);
8464    }
8465
8466    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8467    // a reference there.
8468    /*package*/ DexManager getDexManager() {
8469        return mDexManager;
8470    }
8471
8472    /**
8473     * Execute the background dexopt job immediately.
8474     */
8475    @Override
8476    public boolean runBackgroundDexoptJob() {
8477        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8478    }
8479
8480    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8481        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8482                || p.usesStaticLibraries != null) {
8483            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8484            Set<String> collectedNames = new HashSet<>();
8485            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8486
8487            retValue.remove(p);
8488
8489            return retValue;
8490        } else {
8491            return Collections.emptyList();
8492        }
8493    }
8494
8495    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8496            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8497        if (!collectedNames.contains(p.packageName)) {
8498            collectedNames.add(p.packageName);
8499            collected.add(p);
8500
8501            if (p.usesLibraries != null) {
8502                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8503                        null, collected, collectedNames);
8504            }
8505            if (p.usesOptionalLibraries != null) {
8506                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8507                        null, collected, collectedNames);
8508            }
8509            if (p.usesStaticLibraries != null) {
8510                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8511                        p.usesStaticLibrariesVersions, collected, collectedNames);
8512            }
8513        }
8514    }
8515
8516    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8517            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8518        final int libNameCount = libs.size();
8519        for (int i = 0; i < libNameCount; i++) {
8520            String libName = libs.get(i);
8521            int version = (versions != null && versions.length == libNameCount)
8522                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8523            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8524            if (libPkg != null) {
8525                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8526            }
8527        }
8528    }
8529
8530    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8531        synchronized (mPackages) {
8532            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8533            if (libEntry != null) {
8534                return mPackages.get(libEntry.apk);
8535            }
8536            return null;
8537        }
8538    }
8539
8540    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8541        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8542        if (versionedLib == null) {
8543            return null;
8544        }
8545        return versionedLib.get(version);
8546    }
8547
8548    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8549        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8550                pkg.staticSharedLibName);
8551        if (versionedLib == null) {
8552            return null;
8553        }
8554        int previousLibVersion = -1;
8555        final int versionCount = versionedLib.size();
8556        for (int i = 0; i < versionCount; i++) {
8557            final int libVersion = versionedLib.keyAt(i);
8558            if (libVersion < pkg.staticSharedLibVersion) {
8559                previousLibVersion = Math.max(previousLibVersion, libVersion);
8560            }
8561        }
8562        if (previousLibVersion >= 0) {
8563            return versionedLib.get(previousLibVersion);
8564        }
8565        return null;
8566    }
8567
8568    public void shutdown() {
8569        mPackageUsage.writeNow(mPackages);
8570        mCompilerStats.writeNow();
8571    }
8572
8573    @Override
8574    public void dumpProfiles(String packageName) {
8575        PackageParser.Package pkg;
8576        synchronized (mPackages) {
8577            pkg = mPackages.get(packageName);
8578            if (pkg == null) {
8579                throw new IllegalArgumentException("Unknown package: " + packageName);
8580            }
8581        }
8582        /* Only the shell, root, or the app user should be able to dump profiles. */
8583        int callingUid = Binder.getCallingUid();
8584        if (callingUid != Process.SHELL_UID &&
8585            callingUid != Process.ROOT_UID &&
8586            callingUid != pkg.applicationInfo.uid) {
8587            throw new SecurityException("dumpProfiles");
8588        }
8589
8590        synchronized (mInstallLock) {
8591            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8592            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8593            try {
8594                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8595                String codePaths = TextUtils.join(";", allCodePaths);
8596                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8597            } catch (InstallerException e) {
8598                Slog.w(TAG, "Failed to dump profiles", e);
8599            }
8600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8601        }
8602    }
8603
8604    @Override
8605    public void forceDexOpt(String packageName) {
8606        enforceSystemOrRoot("forceDexOpt");
8607
8608        PackageParser.Package pkg;
8609        synchronized (mPackages) {
8610            pkg = mPackages.get(packageName);
8611            if (pkg == null) {
8612                throw new IllegalArgumentException("Unknown package: " + packageName);
8613            }
8614        }
8615
8616        synchronized (mInstallLock) {
8617            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8618
8619            // Whoever is calling forceDexOpt wants a fully compiled package.
8620            // Don't use profiles since that may cause compilation to be skipped.
8621            final int res = performDexOptInternalWithDependenciesLI(pkg,
8622                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8623                    true /* force */);
8624
8625            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8626            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8627                throw new IllegalStateException("Failed to dexopt: " + res);
8628            }
8629        }
8630    }
8631
8632    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8633        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8634            Slog.w(TAG, "Unable to update from " + oldPkg.name
8635                    + " to " + newPkg.packageName
8636                    + ": old package not in system partition");
8637            return false;
8638        } else if (mPackages.get(oldPkg.name) != null) {
8639            Slog.w(TAG, "Unable to update from " + oldPkg.name
8640                    + " to " + newPkg.packageName
8641                    + ": old package still exists");
8642            return false;
8643        }
8644        return true;
8645    }
8646
8647    void removeCodePathLI(File codePath) {
8648        if (codePath.isDirectory()) {
8649            try {
8650                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8651            } catch (InstallerException e) {
8652                Slog.w(TAG, "Failed to remove code path", e);
8653            }
8654        } else {
8655            codePath.delete();
8656        }
8657    }
8658
8659    private int[] resolveUserIds(int userId) {
8660        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8661    }
8662
8663    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8664        if (pkg == null) {
8665            Slog.wtf(TAG, "Package was null!", new Throwable());
8666            return;
8667        }
8668        clearAppDataLeafLIF(pkg, userId, flags);
8669        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8670        for (int i = 0; i < childCount; i++) {
8671            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8672        }
8673    }
8674
8675    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8676        final PackageSetting ps;
8677        synchronized (mPackages) {
8678            ps = mSettings.mPackages.get(pkg.packageName);
8679        }
8680        for (int realUserId : resolveUserIds(userId)) {
8681            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8682            try {
8683                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8684                        ceDataInode);
8685            } catch (InstallerException e) {
8686                Slog.w(TAG, String.valueOf(e));
8687            }
8688        }
8689    }
8690
8691    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8692        if (pkg == null) {
8693            Slog.wtf(TAG, "Package was null!", new Throwable());
8694            return;
8695        }
8696        destroyAppDataLeafLIF(pkg, userId, flags);
8697        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8698        for (int i = 0; i < childCount; i++) {
8699            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8700        }
8701    }
8702
8703    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8704        final PackageSetting ps;
8705        synchronized (mPackages) {
8706            ps = mSettings.mPackages.get(pkg.packageName);
8707        }
8708        for (int realUserId : resolveUserIds(userId)) {
8709            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8710            try {
8711                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8712                        ceDataInode);
8713            } catch (InstallerException e) {
8714                Slog.w(TAG, String.valueOf(e));
8715            }
8716            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8717        }
8718    }
8719
8720    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8721        if (pkg == null) {
8722            Slog.wtf(TAG, "Package was null!", new Throwable());
8723            return;
8724        }
8725        destroyAppProfilesLeafLIF(pkg);
8726        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8727        for (int i = 0; i < childCount; i++) {
8728            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8729        }
8730    }
8731
8732    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8733        try {
8734            mInstaller.destroyAppProfiles(pkg.packageName);
8735        } catch (InstallerException e) {
8736            Slog.w(TAG, String.valueOf(e));
8737        }
8738    }
8739
8740    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8741        if (pkg == null) {
8742            Slog.wtf(TAG, "Package was null!", new Throwable());
8743            return;
8744        }
8745        clearAppProfilesLeafLIF(pkg);
8746        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8747        for (int i = 0; i < childCount; i++) {
8748            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8749        }
8750    }
8751
8752    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8753        try {
8754            mInstaller.clearAppProfiles(pkg.packageName);
8755        } catch (InstallerException e) {
8756            Slog.w(TAG, String.valueOf(e));
8757        }
8758    }
8759
8760    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8761            long lastUpdateTime) {
8762        // Set parent install/update time
8763        PackageSetting ps = (PackageSetting) pkg.mExtras;
8764        if (ps != null) {
8765            ps.firstInstallTime = firstInstallTime;
8766            ps.lastUpdateTime = lastUpdateTime;
8767        }
8768        // Set children install/update time
8769        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8770        for (int i = 0; i < childCount; i++) {
8771            PackageParser.Package childPkg = pkg.childPackages.get(i);
8772            ps = (PackageSetting) childPkg.mExtras;
8773            if (ps != null) {
8774                ps.firstInstallTime = firstInstallTime;
8775                ps.lastUpdateTime = lastUpdateTime;
8776            }
8777        }
8778    }
8779
8780    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8781            PackageParser.Package changingLib) {
8782        if (file.path != null) {
8783            usesLibraryFiles.add(file.path);
8784            return;
8785        }
8786        PackageParser.Package p = mPackages.get(file.apk);
8787        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8788            // If we are doing this while in the middle of updating a library apk,
8789            // then we need to make sure to use that new apk for determining the
8790            // dependencies here.  (We haven't yet finished committing the new apk
8791            // to the package manager state.)
8792            if (p == null || p.packageName.equals(changingLib.packageName)) {
8793                p = changingLib;
8794            }
8795        }
8796        if (p != null) {
8797            usesLibraryFiles.addAll(p.getAllCodePaths());
8798        }
8799    }
8800
8801    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8802            PackageParser.Package changingLib) throws PackageManagerException {
8803        if (pkg == null) {
8804            return;
8805        }
8806        ArraySet<String> usesLibraryFiles = null;
8807        if (pkg.usesLibraries != null) {
8808            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8809                    null, null, pkg.packageName, changingLib, true, null);
8810        }
8811        if (pkg.usesStaticLibraries != null) {
8812            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8813                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8814                    pkg.packageName, changingLib, true, usesLibraryFiles);
8815        }
8816        if (pkg.usesOptionalLibraries != null) {
8817            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8818                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8819        }
8820        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8821            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8822        } else {
8823            pkg.usesLibraryFiles = null;
8824        }
8825    }
8826
8827    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8828            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8829            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8830            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8831            throws PackageManagerException {
8832        final int libCount = requestedLibraries.size();
8833        for (int i = 0; i < libCount; i++) {
8834            final String libName = requestedLibraries.get(i);
8835            final int libVersion = requiredVersions != null ? requiredVersions[i]
8836                    : SharedLibraryInfo.VERSION_UNDEFINED;
8837            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8838            if (libEntry == null) {
8839                if (required) {
8840                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8841                            "Package " + packageName + " requires unavailable shared library "
8842                                    + libName + "; failing!");
8843                } else {
8844                    Slog.w(TAG, "Package " + packageName
8845                            + " desires unavailable shared library "
8846                            + libName + "; ignoring!");
8847                }
8848            } else {
8849                if (requiredVersions != null && requiredCertDigests != null) {
8850                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8851                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8852                            "Package " + packageName + " requires unavailable static shared"
8853                                    + " library " + libName + " version "
8854                                    + libEntry.info.getVersion() + "; failing!");
8855                    }
8856
8857                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8858                    if (libPkg == null) {
8859                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8860                                "Package " + packageName + " requires unavailable static shared"
8861                                        + " library; failing!");
8862                    }
8863
8864                    String expectedCertDigest = requiredCertDigests[i];
8865                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8866                                libPkg.mSignatures[0]);
8867                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8868                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8869                                "Package " + packageName + " requires differently signed" +
8870                                        " static shared library; failing!");
8871                    }
8872                }
8873
8874                if (outUsedLibraries == null) {
8875                    outUsedLibraries = new ArraySet<>();
8876                }
8877                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8878            }
8879        }
8880        return outUsedLibraries;
8881    }
8882
8883    private static boolean hasString(List<String> list, List<String> which) {
8884        if (list == null) {
8885            return false;
8886        }
8887        for (int i=list.size()-1; i>=0; i--) {
8888            for (int j=which.size()-1; j>=0; j--) {
8889                if (which.get(j).equals(list.get(i))) {
8890                    return true;
8891                }
8892            }
8893        }
8894        return false;
8895    }
8896
8897    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8898            PackageParser.Package changingPkg) {
8899        ArrayList<PackageParser.Package> res = null;
8900        for (PackageParser.Package pkg : mPackages.values()) {
8901            if (changingPkg != null
8902                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8903                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8904                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8905                            changingPkg.staticSharedLibName)) {
8906                return null;
8907            }
8908            if (res == null) {
8909                res = new ArrayList<>();
8910            }
8911            res.add(pkg);
8912            try {
8913                updateSharedLibrariesLPr(pkg, changingPkg);
8914            } catch (PackageManagerException e) {
8915                // If a system app update or an app and a required lib missing we
8916                // delete the package and for updated system apps keep the data as
8917                // it is better for the user to reinstall than to be in an limbo
8918                // state. Also libs disappearing under an app should never happen
8919                // - just in case.
8920                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8921                    final int flags = pkg.isUpdatedSystemApp()
8922                            ? PackageManager.DELETE_KEEP_DATA : 0;
8923                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8924                            flags , null, true, null);
8925                }
8926                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8927            }
8928        }
8929        return res;
8930    }
8931
8932    /**
8933     * Derive the value of the {@code cpuAbiOverride} based on the provided
8934     * value and an optional stored value from the package settings.
8935     */
8936    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8937        String cpuAbiOverride = null;
8938
8939        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8940            cpuAbiOverride = null;
8941        } else if (abiOverride != null) {
8942            cpuAbiOverride = abiOverride;
8943        } else if (settings != null) {
8944            cpuAbiOverride = settings.cpuAbiOverrideString;
8945        }
8946
8947        return cpuAbiOverride;
8948    }
8949
8950    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8951            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8952                    throws PackageManagerException {
8953        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8954        // If the package has children and this is the first dive in the function
8955        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8956        // whether all packages (parent and children) would be successfully scanned
8957        // before the actual scan since scanning mutates internal state and we want
8958        // to atomically install the package and its children.
8959        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8960            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8961                scanFlags |= SCAN_CHECK_ONLY;
8962            }
8963        } else {
8964            scanFlags &= ~SCAN_CHECK_ONLY;
8965        }
8966
8967        final PackageParser.Package scannedPkg;
8968        try {
8969            // Scan the parent
8970            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8971            // Scan the children
8972            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8973            for (int i = 0; i < childCount; i++) {
8974                PackageParser.Package childPkg = pkg.childPackages.get(i);
8975                scanPackageLI(childPkg, policyFlags,
8976                        scanFlags, currentTime, user);
8977            }
8978        } finally {
8979            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8980        }
8981
8982        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8983            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8984        }
8985
8986        return scannedPkg;
8987    }
8988
8989    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8990            int scanFlags, long currentTime, @Nullable UserHandle user)
8991                    throws PackageManagerException {
8992        boolean success = false;
8993        try {
8994            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8995                    currentTime, user);
8996            success = true;
8997            return res;
8998        } finally {
8999            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9000                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9001                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9002                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9003                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9004            }
9005        }
9006    }
9007
9008    /**
9009     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9010     */
9011    private static boolean apkHasCode(String fileName) {
9012        StrictJarFile jarFile = null;
9013        try {
9014            jarFile = new StrictJarFile(fileName,
9015                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9016            return jarFile.findEntry("classes.dex") != null;
9017        } catch (IOException ignore) {
9018        } finally {
9019            try {
9020                if (jarFile != null) {
9021                    jarFile.close();
9022                }
9023            } catch (IOException ignore) {}
9024        }
9025        return false;
9026    }
9027
9028    /**
9029     * Enforces code policy for the package. This ensures that if an APK has
9030     * declared hasCode="true" in its manifest that the APK actually contains
9031     * code.
9032     *
9033     * @throws PackageManagerException If bytecode could not be found when it should exist
9034     */
9035    private static void assertCodePolicy(PackageParser.Package pkg)
9036            throws PackageManagerException {
9037        final boolean shouldHaveCode =
9038                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9039        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9040            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9041                    "Package " + pkg.baseCodePath + " code is missing");
9042        }
9043
9044        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9045            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9046                final boolean splitShouldHaveCode =
9047                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9048                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9049                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9050                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9051                }
9052            }
9053        }
9054    }
9055
9056    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9057            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9058                    throws PackageManagerException {
9059        if (DEBUG_PACKAGE_SCANNING) {
9060            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9061                Log.d(TAG, "Scanning package " + pkg.packageName);
9062        }
9063
9064        applyPolicy(pkg, policyFlags);
9065
9066        assertPackageIsValid(pkg, policyFlags, scanFlags);
9067
9068        // Initialize package source and resource directories
9069        final File scanFile = new File(pkg.codePath);
9070        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9071        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9072
9073        SharedUserSetting suid = null;
9074        PackageSetting pkgSetting = null;
9075
9076        // Getting the package setting may have a side-effect, so if we
9077        // are only checking if scan would succeed, stash a copy of the
9078        // old setting to restore at the end.
9079        PackageSetting nonMutatedPs = null;
9080
9081        // We keep references to the derived CPU Abis from settings in oder to reuse
9082        // them in the case where we're not upgrading or booting for the first time.
9083        String primaryCpuAbiFromSettings = null;
9084        String secondaryCpuAbiFromSettings = null;
9085
9086        // writer
9087        synchronized (mPackages) {
9088            if (pkg.mSharedUserId != null) {
9089                // SIDE EFFECTS; may potentially allocate a new shared user
9090                suid = mSettings.getSharedUserLPw(
9091                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9092                if (DEBUG_PACKAGE_SCANNING) {
9093                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9094                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9095                                + "): packages=" + suid.packages);
9096                }
9097            }
9098
9099            // Check if we are renaming from an original package name.
9100            PackageSetting origPackage = null;
9101            String realName = null;
9102            if (pkg.mOriginalPackages != null) {
9103                // This package may need to be renamed to a previously
9104                // installed name.  Let's check on that...
9105                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9106                if (pkg.mOriginalPackages.contains(renamed)) {
9107                    // This package had originally been installed as the
9108                    // original name, and we have already taken care of
9109                    // transitioning to the new one.  Just update the new
9110                    // one to continue using the old name.
9111                    realName = pkg.mRealPackage;
9112                    if (!pkg.packageName.equals(renamed)) {
9113                        // Callers into this function may have already taken
9114                        // care of renaming the package; only do it here if
9115                        // it is not already done.
9116                        pkg.setPackageName(renamed);
9117                    }
9118                } else {
9119                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9120                        if ((origPackage = mSettings.getPackageLPr(
9121                                pkg.mOriginalPackages.get(i))) != null) {
9122                            // We do have the package already installed under its
9123                            // original name...  should we use it?
9124                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9125                                // New package is not compatible with original.
9126                                origPackage = null;
9127                                continue;
9128                            } else if (origPackage.sharedUser != null) {
9129                                // Make sure uid is compatible between packages.
9130                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9131                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9132                                            + " to " + pkg.packageName + ": old uid "
9133                                            + origPackage.sharedUser.name
9134                                            + " differs from " + pkg.mSharedUserId);
9135                                    origPackage = null;
9136                                    continue;
9137                                }
9138                                // TODO: Add case when shared user id is added [b/28144775]
9139                            } else {
9140                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9141                                        + pkg.packageName + " to old name " + origPackage.name);
9142                            }
9143                            break;
9144                        }
9145                    }
9146                }
9147            }
9148
9149            if (mTransferedPackages.contains(pkg.packageName)) {
9150                Slog.w(TAG, "Package " + pkg.packageName
9151                        + " was transferred to another, but its .apk remains");
9152            }
9153
9154            // See comments in nonMutatedPs declaration
9155            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9156                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9157                if (foundPs != null) {
9158                    nonMutatedPs = new PackageSetting(foundPs);
9159                }
9160            }
9161
9162            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9163                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9164                if (foundPs != null) {
9165                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9166                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9167                }
9168            }
9169
9170            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9171            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9172                PackageManagerService.reportSettingsProblem(Log.WARN,
9173                        "Package " + pkg.packageName + " shared user changed from "
9174                                + (pkgSetting.sharedUser != null
9175                                        ? pkgSetting.sharedUser.name : "<nothing>")
9176                                + " to "
9177                                + (suid != null ? suid.name : "<nothing>")
9178                                + "; replacing with new");
9179                pkgSetting = null;
9180            }
9181            final PackageSetting oldPkgSetting =
9182                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9183            final PackageSetting disabledPkgSetting =
9184                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9185
9186            String[] usesStaticLibraries = null;
9187            if (pkg.usesStaticLibraries != null) {
9188                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9189                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9190            }
9191
9192            if (pkgSetting == null) {
9193                final String parentPackageName = (pkg.parentPackage != null)
9194                        ? pkg.parentPackage.packageName : null;
9195                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9196                // REMOVE SharedUserSetting from method; update in a separate call
9197                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9198                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9199                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9200                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9201                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9202                        true /*allowInstall*/, instantApp, parentPackageName,
9203                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9204                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9205                // SIDE EFFECTS; updates system state; move elsewhere
9206                if (origPackage != null) {
9207                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9208                }
9209                mSettings.addUserToSettingLPw(pkgSetting);
9210            } else {
9211                // REMOVE SharedUserSetting from method; update in a separate call.
9212                //
9213                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9214                // secondaryCpuAbi are not known at this point so we always update them
9215                // to null here, only to reset them at a later point.
9216                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9217                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9218                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9219                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9220                        UserManagerService.getInstance(), usesStaticLibraries,
9221                        pkg.usesStaticLibrariesVersions);
9222            }
9223            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9224            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9225
9226            // SIDE EFFECTS; modifies system state; move elsewhere
9227            if (pkgSetting.origPackage != null) {
9228                // If we are first transitioning from an original package,
9229                // fix up the new package's name now.  We need to do this after
9230                // looking up the package under its new name, so getPackageLP
9231                // can take care of fiddling things correctly.
9232                pkg.setPackageName(origPackage.name);
9233
9234                // File a report about this.
9235                String msg = "New package " + pkgSetting.realName
9236                        + " renamed to replace old package " + pkgSetting.name;
9237                reportSettingsProblem(Log.WARN, msg);
9238
9239                // Make a note of it.
9240                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9241                    mTransferedPackages.add(origPackage.name);
9242                }
9243
9244                // No longer need to retain this.
9245                pkgSetting.origPackage = null;
9246            }
9247
9248            // SIDE EFFECTS; modifies system state; move elsewhere
9249            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9250                // Make a note of it.
9251                mTransferedPackages.add(pkg.packageName);
9252            }
9253
9254            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9255                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9256            }
9257
9258            if ((scanFlags & SCAN_BOOTING) == 0
9259                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9260                // Check all shared libraries and map to their actual file path.
9261                // We only do this here for apps not on a system dir, because those
9262                // are the only ones that can fail an install due to this.  We
9263                // will take care of the system apps by updating all of their
9264                // library paths after the scan is done. Also during the initial
9265                // scan don't update any libs as we do this wholesale after all
9266                // apps are scanned to avoid dependency based scanning.
9267                updateSharedLibrariesLPr(pkg, null);
9268            }
9269
9270            if (mFoundPolicyFile) {
9271                SELinuxMMAC.assignSeInfoValue(pkg);
9272            }
9273            pkg.applicationInfo.uid = pkgSetting.appId;
9274            pkg.mExtras = pkgSetting;
9275
9276
9277            // Static shared libs have same package with different versions where
9278            // we internally use a synthetic package name to allow multiple versions
9279            // of the same package, therefore we need to compare signatures against
9280            // the package setting for the latest library version.
9281            PackageSetting signatureCheckPs = pkgSetting;
9282            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9283                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9284                if (libraryEntry != null) {
9285                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9286                }
9287            }
9288
9289            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9290                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9291                    // We just determined the app is signed correctly, so bring
9292                    // over the latest parsed certs.
9293                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9294                } else {
9295                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9296                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9297                                "Package " + pkg.packageName + " upgrade keys do not match the "
9298                                + "previously installed version");
9299                    } else {
9300                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9301                        String msg = "System package " + pkg.packageName
9302                                + " signature changed; retaining data.";
9303                        reportSettingsProblem(Log.WARN, msg);
9304                    }
9305                }
9306            } else {
9307                try {
9308                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9309                    verifySignaturesLP(signatureCheckPs, pkg);
9310                    // We just determined the app is signed correctly, so bring
9311                    // over the latest parsed certs.
9312                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9313                } catch (PackageManagerException e) {
9314                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9315                        throw e;
9316                    }
9317                    // The signature has changed, but this package is in the system
9318                    // image...  let's recover!
9319                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9320                    // However...  if this package is part of a shared user, but it
9321                    // doesn't match the signature of the shared user, let's fail.
9322                    // What this means is that you can't change the signatures
9323                    // associated with an overall shared user, which doesn't seem all
9324                    // that unreasonable.
9325                    if (signatureCheckPs.sharedUser != null) {
9326                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9327                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9328                            throw new PackageManagerException(
9329                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9330                                    "Signature mismatch for shared user: "
9331                                            + pkgSetting.sharedUser);
9332                        }
9333                    }
9334                    // File a report about this.
9335                    String msg = "System package " + pkg.packageName
9336                            + " signature changed; retaining data.";
9337                    reportSettingsProblem(Log.WARN, msg);
9338                }
9339            }
9340
9341            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9342                // This package wants to adopt ownership of permissions from
9343                // another package.
9344                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9345                    final String origName = pkg.mAdoptPermissions.get(i);
9346                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9347                    if (orig != null) {
9348                        if (verifyPackageUpdateLPr(orig, pkg)) {
9349                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9350                                    + pkg.packageName);
9351                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9352                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9353                        }
9354                    }
9355                }
9356            }
9357        }
9358
9359        pkg.applicationInfo.processName = fixProcessName(
9360                pkg.applicationInfo.packageName,
9361                pkg.applicationInfo.processName);
9362
9363        if (pkg != mPlatformPackage) {
9364            // Get all of our default paths setup
9365            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9366        }
9367
9368        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9369
9370        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9371            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9372                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9373                derivePackageAbi(
9374                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9375                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9376
9377                // Some system apps still use directory structure for native libraries
9378                // in which case we might end up not detecting abi solely based on apk
9379                // structure. Try to detect abi based on directory structure.
9380                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9381                        pkg.applicationInfo.primaryCpuAbi == null) {
9382                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9383                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9384                }
9385            } else {
9386                // This is not a first boot or an upgrade, don't bother deriving the
9387                // ABI during the scan. Instead, trust the value that was stored in the
9388                // package setting.
9389                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9390                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9391
9392                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9393
9394                if (DEBUG_ABI_SELECTION) {
9395                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9396                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9397                        pkg.applicationInfo.secondaryCpuAbi);
9398                }
9399            }
9400        } else {
9401            if ((scanFlags & SCAN_MOVE) != 0) {
9402                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9403                // but we already have this packages package info in the PackageSetting. We just
9404                // use that and derive the native library path based on the new codepath.
9405                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9406                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9407            }
9408
9409            // Set native library paths again. For moves, the path will be updated based on the
9410            // ABIs we've determined above. For non-moves, the path will be updated based on the
9411            // ABIs we determined during compilation, but the path will depend on the final
9412            // package path (after the rename away from the stage path).
9413            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9414        }
9415
9416        // This is a special case for the "system" package, where the ABI is
9417        // dictated by the zygote configuration (and init.rc). We should keep track
9418        // of this ABI so that we can deal with "normal" applications that run under
9419        // the same UID correctly.
9420        if (mPlatformPackage == pkg) {
9421            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9422                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9423        }
9424
9425        // If there's a mismatch between the abi-override in the package setting
9426        // and the abiOverride specified for the install. Warn about this because we
9427        // would've already compiled the app without taking the package setting into
9428        // account.
9429        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9430            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9431                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9432                        " for package " + pkg.packageName);
9433            }
9434        }
9435
9436        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9437        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9438        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9439
9440        // Copy the derived override back to the parsed package, so that we can
9441        // update the package settings accordingly.
9442        pkg.cpuAbiOverride = cpuAbiOverride;
9443
9444        if (DEBUG_ABI_SELECTION) {
9445            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9446                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9447                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9448        }
9449
9450        // Push the derived path down into PackageSettings so we know what to
9451        // clean up at uninstall time.
9452        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9453
9454        if (DEBUG_ABI_SELECTION) {
9455            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9456                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9457                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9458        }
9459
9460        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9461        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9462            // We don't do this here during boot because we can do it all
9463            // at once after scanning all existing packages.
9464            //
9465            // We also do this *before* we perform dexopt on this package, so that
9466            // we can avoid redundant dexopts, and also to make sure we've got the
9467            // code and package path correct.
9468            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9469        }
9470
9471        if (mFactoryTest && pkg.requestedPermissions.contains(
9472                android.Manifest.permission.FACTORY_TEST)) {
9473            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9474        }
9475
9476        if (isSystemApp(pkg)) {
9477            pkgSetting.isOrphaned = true;
9478        }
9479
9480        // Take care of first install / last update times.
9481        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9482        if (currentTime != 0) {
9483            if (pkgSetting.firstInstallTime == 0) {
9484                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9485            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9486                pkgSetting.lastUpdateTime = currentTime;
9487            }
9488        } else if (pkgSetting.firstInstallTime == 0) {
9489            // We need *something*.  Take time time stamp of the file.
9490            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9491        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9492            if (scanFileTime != pkgSetting.timeStamp) {
9493                // A package on the system image has changed; consider this
9494                // to be an update.
9495                pkgSetting.lastUpdateTime = scanFileTime;
9496            }
9497        }
9498        pkgSetting.setTimeStamp(scanFileTime);
9499
9500        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9501            if (nonMutatedPs != null) {
9502                synchronized (mPackages) {
9503                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9504                }
9505            }
9506        } else {
9507            final int userId = user == null ? 0 : user.getIdentifier();
9508            // Modify state for the given package setting
9509            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9510                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9511            if (pkgSetting.getInstantApp(userId)) {
9512                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9513            }
9514        }
9515        return pkg;
9516    }
9517
9518    /**
9519     * Applies policy to the parsed package based upon the given policy flags.
9520     * Ensures the package is in a good state.
9521     * <p>
9522     * Implementation detail: This method must NOT have any side effect. It would
9523     * ideally be static, but, it requires locks to read system state.
9524     */
9525    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9526        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9527            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9528            if (pkg.applicationInfo.isDirectBootAware()) {
9529                // we're direct boot aware; set for all components
9530                for (PackageParser.Service s : pkg.services) {
9531                    s.info.encryptionAware = s.info.directBootAware = true;
9532                }
9533                for (PackageParser.Provider p : pkg.providers) {
9534                    p.info.encryptionAware = p.info.directBootAware = true;
9535                }
9536                for (PackageParser.Activity a : pkg.activities) {
9537                    a.info.encryptionAware = a.info.directBootAware = true;
9538                }
9539                for (PackageParser.Activity r : pkg.receivers) {
9540                    r.info.encryptionAware = r.info.directBootAware = true;
9541                }
9542            }
9543        } else {
9544            // Only allow system apps to be flagged as core apps.
9545            pkg.coreApp = false;
9546            // clear flags not applicable to regular apps
9547            pkg.applicationInfo.privateFlags &=
9548                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9549            pkg.applicationInfo.privateFlags &=
9550                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9551        }
9552        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9553
9554        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9555            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9556        }
9557
9558        if (!isSystemApp(pkg)) {
9559            // Only system apps can use these features.
9560            pkg.mOriginalPackages = null;
9561            pkg.mRealPackage = null;
9562            pkg.mAdoptPermissions = null;
9563        }
9564    }
9565
9566    /**
9567     * Asserts the parsed package is valid according to the given policy. If the
9568     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9569     * <p>
9570     * Implementation detail: This method must NOT have any side effects. It would
9571     * ideally be static, but, it requires locks to read system state.
9572     *
9573     * @throws PackageManagerException If the package fails any of the validation checks
9574     */
9575    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9576            throws PackageManagerException {
9577        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9578            assertCodePolicy(pkg);
9579        }
9580
9581        if (pkg.applicationInfo.getCodePath() == null ||
9582                pkg.applicationInfo.getResourcePath() == null) {
9583            // Bail out. The resource and code paths haven't been set.
9584            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9585                    "Code and resource paths haven't been set correctly");
9586        }
9587
9588        // Make sure we're not adding any bogus keyset info
9589        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9590        ksms.assertScannedPackageValid(pkg);
9591
9592        synchronized (mPackages) {
9593            // The special "android" package can only be defined once
9594            if (pkg.packageName.equals("android")) {
9595                if (mAndroidApplication != null) {
9596                    Slog.w(TAG, "*************************************************");
9597                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9598                    Slog.w(TAG, " codePath=" + pkg.codePath);
9599                    Slog.w(TAG, "*************************************************");
9600                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9601                            "Core android package being redefined.  Skipping.");
9602                }
9603            }
9604
9605            // A package name must be unique; don't allow duplicates
9606            if (mPackages.containsKey(pkg.packageName)) {
9607                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9608                        "Application package " + pkg.packageName
9609                        + " already installed.  Skipping duplicate.");
9610            }
9611
9612            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9613                // Static libs have a synthetic package name containing the version
9614                // but we still want the base name to be unique.
9615                if (mPackages.containsKey(pkg.manifestPackageName)) {
9616                    throw new PackageManagerException(
9617                            "Duplicate static shared lib provider package");
9618                }
9619
9620                // Static shared libraries should have at least O target SDK
9621                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9622                    throw new PackageManagerException(
9623                            "Packages declaring static-shared libs must target O SDK or higher");
9624                }
9625
9626                // Package declaring static a shared lib cannot be instant apps
9627                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9628                    throw new PackageManagerException(
9629                            "Packages declaring static-shared libs cannot be instant apps");
9630                }
9631
9632                // Package declaring static a shared lib cannot be renamed since the package
9633                // name is synthetic and apps can't code around package manager internals.
9634                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9635                    throw new PackageManagerException(
9636                            "Packages declaring static-shared libs cannot be renamed");
9637                }
9638
9639                // Package declaring static a shared lib cannot declare child packages
9640                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9641                    throw new PackageManagerException(
9642                            "Packages declaring static-shared libs cannot have child packages");
9643                }
9644
9645                // Package declaring static a shared lib cannot declare dynamic libs
9646                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9647                    throw new PackageManagerException(
9648                            "Packages declaring static-shared libs cannot declare dynamic libs");
9649                }
9650
9651                // Package declaring static a shared lib cannot declare shared users
9652                if (pkg.mSharedUserId != null) {
9653                    throw new PackageManagerException(
9654                            "Packages declaring static-shared libs cannot declare shared users");
9655                }
9656
9657                // Static shared libs cannot declare activities
9658                if (!pkg.activities.isEmpty()) {
9659                    throw new PackageManagerException(
9660                            "Static shared libs cannot declare activities");
9661                }
9662
9663                // Static shared libs cannot declare services
9664                if (!pkg.services.isEmpty()) {
9665                    throw new PackageManagerException(
9666                            "Static shared libs cannot declare services");
9667                }
9668
9669                // Static shared libs cannot declare providers
9670                if (!pkg.providers.isEmpty()) {
9671                    throw new PackageManagerException(
9672                            "Static shared libs cannot declare content providers");
9673                }
9674
9675                // Static shared libs cannot declare receivers
9676                if (!pkg.receivers.isEmpty()) {
9677                    throw new PackageManagerException(
9678                            "Static shared libs cannot declare broadcast receivers");
9679                }
9680
9681                // Static shared libs cannot declare permission groups
9682                if (!pkg.permissionGroups.isEmpty()) {
9683                    throw new PackageManagerException(
9684                            "Static shared libs cannot declare permission groups");
9685                }
9686
9687                // Static shared libs cannot declare permissions
9688                if (!pkg.permissions.isEmpty()) {
9689                    throw new PackageManagerException(
9690                            "Static shared libs cannot declare permissions");
9691                }
9692
9693                // Static shared libs cannot declare protected broadcasts
9694                if (pkg.protectedBroadcasts != null) {
9695                    throw new PackageManagerException(
9696                            "Static shared libs cannot declare protected broadcasts");
9697                }
9698
9699                // Static shared libs cannot be overlay targets
9700                if (pkg.mOverlayTarget != null) {
9701                    throw new PackageManagerException(
9702                            "Static shared libs cannot be overlay targets");
9703                }
9704
9705                // The version codes must be ordered as lib versions
9706                int minVersionCode = Integer.MIN_VALUE;
9707                int maxVersionCode = Integer.MAX_VALUE;
9708
9709                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9710                        pkg.staticSharedLibName);
9711                if (versionedLib != null) {
9712                    final int versionCount = versionedLib.size();
9713                    for (int i = 0; i < versionCount; i++) {
9714                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9715                        // TODO: We will change version code to long, so in the new API it is long
9716                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9717                                .getVersionCode();
9718                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9719                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9720                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9721                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9722                        } else {
9723                            minVersionCode = maxVersionCode = libVersionCode;
9724                            break;
9725                        }
9726                    }
9727                }
9728                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9729                    throw new PackageManagerException("Static shared"
9730                            + " lib version codes must be ordered as lib versions");
9731                }
9732            }
9733
9734            // Only privileged apps and updated privileged apps can add child packages.
9735            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9736                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9737                    throw new PackageManagerException("Only privileged apps can add child "
9738                            + "packages. Ignoring package " + pkg.packageName);
9739                }
9740                final int childCount = pkg.childPackages.size();
9741                for (int i = 0; i < childCount; i++) {
9742                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9743                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9744                            childPkg.packageName)) {
9745                        throw new PackageManagerException("Can't override child of "
9746                                + "another disabled app. Ignoring package " + pkg.packageName);
9747                    }
9748                }
9749            }
9750
9751            // If we're only installing presumed-existing packages, require that the
9752            // scanned APK is both already known and at the path previously established
9753            // for it.  Previously unknown packages we pick up normally, but if we have an
9754            // a priori expectation about this package's install presence, enforce it.
9755            // With a singular exception for new system packages. When an OTA contains
9756            // a new system package, we allow the codepath to change from a system location
9757            // to the user-installed location. If we don't allow this change, any newer,
9758            // user-installed version of the application will be ignored.
9759            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9760                if (mExpectingBetter.containsKey(pkg.packageName)) {
9761                    logCriticalInfo(Log.WARN,
9762                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9763                } else {
9764                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9765                    if (known != null) {
9766                        if (DEBUG_PACKAGE_SCANNING) {
9767                            Log.d(TAG, "Examining " + pkg.codePath
9768                                    + " and requiring known paths " + known.codePathString
9769                                    + " & " + known.resourcePathString);
9770                        }
9771                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9772                                || !pkg.applicationInfo.getResourcePath().equals(
9773                                        known.resourcePathString)) {
9774                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9775                                    "Application package " + pkg.packageName
9776                                    + " found at " + pkg.applicationInfo.getCodePath()
9777                                    + " but expected at " + known.codePathString
9778                                    + "; ignoring.");
9779                        }
9780                    }
9781                }
9782            }
9783
9784            // Verify that this new package doesn't have any content providers
9785            // that conflict with existing packages.  Only do this if the
9786            // package isn't already installed, since we don't want to break
9787            // things that are installed.
9788            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9789                final int N = pkg.providers.size();
9790                int i;
9791                for (i=0; i<N; i++) {
9792                    PackageParser.Provider p = pkg.providers.get(i);
9793                    if (p.info.authority != null) {
9794                        String names[] = p.info.authority.split(";");
9795                        for (int j = 0; j < names.length; j++) {
9796                            if (mProvidersByAuthority.containsKey(names[j])) {
9797                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9798                                final String otherPackageName =
9799                                        ((other != null && other.getComponentName() != null) ?
9800                                                other.getComponentName().getPackageName() : "?");
9801                                throw new PackageManagerException(
9802                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9803                                        "Can't install because provider name " + names[j]
9804                                                + " (in package " + pkg.applicationInfo.packageName
9805                                                + ") is already used by " + otherPackageName);
9806                            }
9807                        }
9808                    }
9809                }
9810            }
9811        }
9812    }
9813
9814    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9815            int type, String declaringPackageName, int declaringVersionCode) {
9816        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9817        if (versionedLib == null) {
9818            versionedLib = new SparseArray<>();
9819            mSharedLibraries.put(name, versionedLib);
9820            if (type == SharedLibraryInfo.TYPE_STATIC) {
9821                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9822            }
9823        } else if (versionedLib.indexOfKey(version) >= 0) {
9824            return false;
9825        }
9826        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9827                version, type, declaringPackageName, declaringVersionCode);
9828        versionedLib.put(version, libEntry);
9829        return true;
9830    }
9831
9832    private boolean removeSharedLibraryLPw(String name, int version) {
9833        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9834        if (versionedLib == null) {
9835            return false;
9836        }
9837        final int libIdx = versionedLib.indexOfKey(version);
9838        if (libIdx < 0) {
9839            return false;
9840        }
9841        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9842        versionedLib.remove(version);
9843        if (versionedLib.size() <= 0) {
9844            mSharedLibraries.remove(name);
9845            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9846                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9847                        .getPackageName());
9848            }
9849        }
9850        return true;
9851    }
9852
9853    /**
9854     * Adds a scanned package to the system. When this method is finished, the package will
9855     * be available for query, resolution, etc...
9856     */
9857    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9858            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9859        final String pkgName = pkg.packageName;
9860        if (mCustomResolverComponentName != null &&
9861                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9862            setUpCustomResolverActivity(pkg);
9863        }
9864
9865        if (pkg.packageName.equals("android")) {
9866            synchronized (mPackages) {
9867                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9868                    // Set up information for our fall-back user intent resolution activity.
9869                    mPlatformPackage = pkg;
9870                    pkg.mVersionCode = mSdkVersion;
9871                    mAndroidApplication = pkg.applicationInfo;
9872                    if (!mResolverReplaced) {
9873                        mResolveActivity.applicationInfo = mAndroidApplication;
9874                        mResolveActivity.name = ResolverActivity.class.getName();
9875                        mResolveActivity.packageName = mAndroidApplication.packageName;
9876                        mResolveActivity.processName = "system:ui";
9877                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9878                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9879                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9880                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9881                        mResolveActivity.exported = true;
9882                        mResolveActivity.enabled = true;
9883                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9884                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9885                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9886                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9887                                | ActivityInfo.CONFIG_ORIENTATION
9888                                | ActivityInfo.CONFIG_KEYBOARD
9889                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9890                        mResolveInfo.activityInfo = mResolveActivity;
9891                        mResolveInfo.priority = 0;
9892                        mResolveInfo.preferredOrder = 0;
9893                        mResolveInfo.match = 0;
9894                        mResolveComponentName = new ComponentName(
9895                                mAndroidApplication.packageName, mResolveActivity.name);
9896                    }
9897                }
9898            }
9899        }
9900
9901        ArrayList<PackageParser.Package> clientLibPkgs = null;
9902        // writer
9903        synchronized (mPackages) {
9904            boolean hasStaticSharedLibs = false;
9905
9906            // Any app can add new static shared libraries
9907            if (pkg.staticSharedLibName != null) {
9908                // Static shared libs don't allow renaming as they have synthetic package
9909                // names to allow install of multiple versions, so use name from manifest.
9910                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9911                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9912                        pkg.manifestPackageName, pkg.mVersionCode)) {
9913                    hasStaticSharedLibs = true;
9914                } else {
9915                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9916                                + pkg.staticSharedLibName + " already exists; skipping");
9917                }
9918                // Static shared libs cannot be updated once installed since they
9919                // use synthetic package name which includes the version code, so
9920                // not need to update other packages's shared lib dependencies.
9921            }
9922
9923            if (!hasStaticSharedLibs
9924                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9925                // Only system apps can add new dynamic shared libraries.
9926                if (pkg.libraryNames != null) {
9927                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9928                        String name = pkg.libraryNames.get(i);
9929                        boolean allowed = false;
9930                        if (pkg.isUpdatedSystemApp()) {
9931                            // New library entries can only be added through the
9932                            // system image.  This is important to get rid of a lot
9933                            // of nasty edge cases: for example if we allowed a non-
9934                            // system update of the app to add a library, then uninstalling
9935                            // the update would make the library go away, and assumptions
9936                            // we made such as through app install filtering would now
9937                            // have allowed apps on the device which aren't compatible
9938                            // with it.  Better to just have the restriction here, be
9939                            // conservative, and create many fewer cases that can negatively
9940                            // impact the user experience.
9941                            final PackageSetting sysPs = mSettings
9942                                    .getDisabledSystemPkgLPr(pkg.packageName);
9943                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9944                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9945                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9946                                        allowed = true;
9947                                        break;
9948                                    }
9949                                }
9950                            }
9951                        } else {
9952                            allowed = true;
9953                        }
9954                        if (allowed) {
9955                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9956                                    SharedLibraryInfo.VERSION_UNDEFINED,
9957                                    SharedLibraryInfo.TYPE_DYNAMIC,
9958                                    pkg.packageName, pkg.mVersionCode)) {
9959                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9960                                        + name + " already exists; skipping");
9961                            }
9962                        } else {
9963                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9964                                    + name + " that is not declared on system image; skipping");
9965                        }
9966                    }
9967
9968                    if ((scanFlags & SCAN_BOOTING) == 0) {
9969                        // If we are not booting, we need to update any applications
9970                        // that are clients of our shared library.  If we are booting,
9971                        // this will all be done once the scan is complete.
9972                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9973                    }
9974                }
9975            }
9976        }
9977
9978        if ((scanFlags & SCAN_BOOTING) != 0) {
9979            // No apps can run during boot scan, so they don't need to be frozen
9980        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9981            // Caller asked to not kill app, so it's probably not frozen
9982        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9983            // Caller asked us to ignore frozen check for some reason; they
9984            // probably didn't know the package name
9985        } else {
9986            // We're doing major surgery on this package, so it better be frozen
9987            // right now to keep it from launching
9988            checkPackageFrozen(pkgName);
9989        }
9990
9991        // Also need to kill any apps that are dependent on the library.
9992        if (clientLibPkgs != null) {
9993            for (int i=0; i<clientLibPkgs.size(); i++) {
9994                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9995                killApplication(clientPkg.applicationInfo.packageName,
9996                        clientPkg.applicationInfo.uid, "update lib");
9997            }
9998        }
9999
10000        // writer
10001        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10002
10003        synchronized (mPackages) {
10004            // We don't expect installation to fail beyond this point
10005
10006            // Add the new setting to mSettings
10007            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10008            // Add the new setting to mPackages
10009            mPackages.put(pkg.applicationInfo.packageName, pkg);
10010            // Make sure we don't accidentally delete its data.
10011            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10012            while (iter.hasNext()) {
10013                PackageCleanItem item = iter.next();
10014                if (pkgName.equals(item.packageName)) {
10015                    iter.remove();
10016                }
10017            }
10018
10019            // Add the package's KeySets to the global KeySetManagerService
10020            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10021            ksms.addScannedPackageLPw(pkg);
10022
10023            int N = pkg.providers.size();
10024            StringBuilder r = null;
10025            int i;
10026            for (i=0; i<N; i++) {
10027                PackageParser.Provider p = pkg.providers.get(i);
10028                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10029                        p.info.processName);
10030                mProviders.addProvider(p);
10031                p.syncable = p.info.isSyncable;
10032                if (p.info.authority != null) {
10033                    String names[] = p.info.authority.split(";");
10034                    p.info.authority = null;
10035                    for (int j = 0; j < names.length; j++) {
10036                        if (j == 1 && p.syncable) {
10037                            // We only want the first authority for a provider to possibly be
10038                            // syncable, so if we already added this provider using a different
10039                            // authority clear the syncable flag. We copy the provider before
10040                            // changing it because the mProviders object contains a reference
10041                            // to a provider that we don't want to change.
10042                            // Only do this for the second authority since the resulting provider
10043                            // object can be the same for all future authorities for this provider.
10044                            p = new PackageParser.Provider(p);
10045                            p.syncable = false;
10046                        }
10047                        if (!mProvidersByAuthority.containsKey(names[j])) {
10048                            mProvidersByAuthority.put(names[j], p);
10049                            if (p.info.authority == null) {
10050                                p.info.authority = names[j];
10051                            } else {
10052                                p.info.authority = p.info.authority + ";" + names[j];
10053                            }
10054                            if (DEBUG_PACKAGE_SCANNING) {
10055                                if (chatty)
10056                                    Log.d(TAG, "Registered content provider: " + names[j]
10057                                            + ", className = " + p.info.name + ", isSyncable = "
10058                                            + p.info.isSyncable);
10059                            }
10060                        } else {
10061                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10062                            Slog.w(TAG, "Skipping provider name " + names[j] +
10063                                    " (in package " + pkg.applicationInfo.packageName +
10064                                    "): name already used by "
10065                                    + ((other != null && other.getComponentName() != null)
10066                                            ? other.getComponentName().getPackageName() : "?"));
10067                        }
10068                    }
10069                }
10070                if (chatty) {
10071                    if (r == null) {
10072                        r = new StringBuilder(256);
10073                    } else {
10074                        r.append(' ');
10075                    }
10076                    r.append(p.info.name);
10077                }
10078            }
10079            if (r != null) {
10080                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10081            }
10082
10083            N = pkg.services.size();
10084            r = null;
10085            for (i=0; i<N; i++) {
10086                PackageParser.Service s = pkg.services.get(i);
10087                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10088                        s.info.processName);
10089                mServices.addService(s);
10090                if (chatty) {
10091                    if (r == null) {
10092                        r = new StringBuilder(256);
10093                    } else {
10094                        r.append(' ');
10095                    }
10096                    r.append(s.info.name);
10097                }
10098            }
10099            if (r != null) {
10100                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10101            }
10102
10103            N = pkg.receivers.size();
10104            r = null;
10105            for (i=0; i<N; i++) {
10106                PackageParser.Activity a = pkg.receivers.get(i);
10107                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10108                        a.info.processName);
10109                mReceivers.addActivity(a, "receiver");
10110                if (chatty) {
10111                    if (r == null) {
10112                        r = new StringBuilder(256);
10113                    } else {
10114                        r.append(' ');
10115                    }
10116                    r.append(a.info.name);
10117                }
10118            }
10119            if (r != null) {
10120                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10121            }
10122
10123            N = pkg.activities.size();
10124            r = null;
10125            for (i=0; i<N; i++) {
10126                PackageParser.Activity a = pkg.activities.get(i);
10127                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10128                        a.info.processName);
10129                mActivities.addActivity(a, "activity");
10130                if (chatty) {
10131                    if (r == null) {
10132                        r = new StringBuilder(256);
10133                    } else {
10134                        r.append(' ');
10135                    }
10136                    r.append(a.info.name);
10137                }
10138            }
10139            if (r != null) {
10140                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10141            }
10142
10143            N = pkg.permissionGroups.size();
10144            r = null;
10145            for (i=0; i<N; i++) {
10146                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10147                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10148                final String curPackageName = cur == null ? null : cur.info.packageName;
10149                // Dont allow ephemeral apps to define new permission groups.
10150                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10151                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10152                            + pg.info.packageName
10153                            + " ignored: instant apps cannot define new permission groups.");
10154                    continue;
10155                }
10156                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10157                if (cur == null || isPackageUpdate) {
10158                    mPermissionGroups.put(pg.info.name, pg);
10159                    if (chatty) {
10160                        if (r == null) {
10161                            r = new StringBuilder(256);
10162                        } else {
10163                            r.append(' ');
10164                        }
10165                        if (isPackageUpdate) {
10166                            r.append("UPD:");
10167                        }
10168                        r.append(pg.info.name);
10169                    }
10170                } else {
10171                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10172                            + pg.info.packageName + " ignored: original from "
10173                            + cur.info.packageName);
10174                    if (chatty) {
10175                        if (r == null) {
10176                            r = new StringBuilder(256);
10177                        } else {
10178                            r.append(' ');
10179                        }
10180                        r.append("DUP:");
10181                        r.append(pg.info.name);
10182                    }
10183                }
10184            }
10185            if (r != null) {
10186                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10187            }
10188
10189            N = pkg.permissions.size();
10190            r = null;
10191            for (i=0; i<N; i++) {
10192                PackageParser.Permission p = pkg.permissions.get(i);
10193
10194                // Dont allow ephemeral apps to define new permissions.
10195                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10196                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10197                            + p.info.packageName
10198                            + " ignored: instant apps cannot define new permissions.");
10199                    continue;
10200                }
10201
10202                // Assume by default that we did not install this permission into the system.
10203                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10204
10205                // Now that permission groups have a special meaning, we ignore permission
10206                // groups for legacy apps to prevent unexpected behavior. In particular,
10207                // permissions for one app being granted to someone just becase they happen
10208                // to be in a group defined by another app (before this had no implications).
10209                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10210                    p.group = mPermissionGroups.get(p.info.group);
10211                    // Warn for a permission in an unknown group.
10212                    if (p.info.group != null && p.group == null) {
10213                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10214                                + p.info.packageName + " in an unknown group " + p.info.group);
10215                    }
10216                }
10217
10218                ArrayMap<String, BasePermission> permissionMap =
10219                        p.tree ? mSettings.mPermissionTrees
10220                                : mSettings.mPermissions;
10221                BasePermission bp = permissionMap.get(p.info.name);
10222
10223                // Allow system apps to redefine non-system permissions
10224                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10225                    final boolean currentOwnerIsSystem = (bp.perm != null
10226                            && isSystemApp(bp.perm.owner));
10227                    if (isSystemApp(p.owner)) {
10228                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10229                            // It's a built-in permission and no owner, take ownership now
10230                            bp.packageSetting = pkgSetting;
10231                            bp.perm = p;
10232                            bp.uid = pkg.applicationInfo.uid;
10233                            bp.sourcePackage = p.info.packageName;
10234                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10235                        } else if (!currentOwnerIsSystem) {
10236                            String msg = "New decl " + p.owner + " of permission  "
10237                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10238                            reportSettingsProblem(Log.WARN, msg);
10239                            bp = null;
10240                        }
10241                    }
10242                }
10243
10244                if (bp == null) {
10245                    bp = new BasePermission(p.info.name, p.info.packageName,
10246                            BasePermission.TYPE_NORMAL);
10247                    permissionMap.put(p.info.name, bp);
10248                }
10249
10250                if (bp.perm == null) {
10251                    if (bp.sourcePackage == null
10252                            || bp.sourcePackage.equals(p.info.packageName)) {
10253                        BasePermission tree = findPermissionTreeLP(p.info.name);
10254                        if (tree == null
10255                                || tree.sourcePackage.equals(p.info.packageName)) {
10256                            bp.packageSetting = pkgSetting;
10257                            bp.perm = p;
10258                            bp.uid = pkg.applicationInfo.uid;
10259                            bp.sourcePackage = p.info.packageName;
10260                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10261                            if (chatty) {
10262                                if (r == null) {
10263                                    r = new StringBuilder(256);
10264                                } else {
10265                                    r.append(' ');
10266                                }
10267                                r.append(p.info.name);
10268                            }
10269                        } else {
10270                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10271                                    + p.info.packageName + " ignored: base tree "
10272                                    + tree.name + " is from package "
10273                                    + tree.sourcePackage);
10274                        }
10275                    } else {
10276                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10277                                + p.info.packageName + " ignored: original from "
10278                                + bp.sourcePackage);
10279                    }
10280                } else if (chatty) {
10281                    if (r == null) {
10282                        r = new StringBuilder(256);
10283                    } else {
10284                        r.append(' ');
10285                    }
10286                    r.append("DUP:");
10287                    r.append(p.info.name);
10288                }
10289                if (bp.perm == p) {
10290                    bp.protectionLevel = p.info.protectionLevel;
10291                }
10292            }
10293
10294            if (r != null) {
10295                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10296            }
10297
10298            N = pkg.instrumentation.size();
10299            r = null;
10300            for (i=0; i<N; i++) {
10301                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10302                a.info.packageName = pkg.applicationInfo.packageName;
10303                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10304                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10305                a.info.splitNames = pkg.splitNames;
10306                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10307                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10308                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10309                a.info.dataDir = pkg.applicationInfo.dataDir;
10310                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10311                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10312                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10313                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10314                mInstrumentation.put(a.getComponentName(), a);
10315                if (chatty) {
10316                    if (r == null) {
10317                        r = new StringBuilder(256);
10318                    } else {
10319                        r.append(' ');
10320                    }
10321                    r.append(a.info.name);
10322                }
10323            }
10324            if (r != null) {
10325                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10326            }
10327
10328            if (pkg.protectedBroadcasts != null) {
10329                N = pkg.protectedBroadcasts.size();
10330                for (i=0; i<N; i++) {
10331                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10332                }
10333            }
10334        }
10335
10336        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10337    }
10338
10339    /**
10340     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10341     * is derived purely on the basis of the contents of {@code scanFile} and
10342     * {@code cpuAbiOverride}.
10343     *
10344     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10345     */
10346    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10347                                 String cpuAbiOverride, boolean extractLibs,
10348                                 File appLib32InstallDir)
10349            throws PackageManagerException {
10350        // Give ourselves some initial paths; we'll come back for another
10351        // pass once we've determined ABI below.
10352        setNativeLibraryPaths(pkg, appLib32InstallDir);
10353
10354        // We would never need to extract libs for forward-locked and external packages,
10355        // since the container service will do it for us. We shouldn't attempt to
10356        // extract libs from system app when it was not updated.
10357        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10358                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10359            extractLibs = false;
10360        }
10361
10362        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10363        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10364
10365        NativeLibraryHelper.Handle handle = null;
10366        try {
10367            handle = NativeLibraryHelper.Handle.create(pkg);
10368            // TODO(multiArch): This can be null for apps that didn't go through the
10369            // usual installation process. We can calculate it again, like we
10370            // do during install time.
10371            //
10372            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10373            // unnecessary.
10374            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10375
10376            // Null out the abis so that they can be recalculated.
10377            pkg.applicationInfo.primaryCpuAbi = null;
10378            pkg.applicationInfo.secondaryCpuAbi = null;
10379            if (isMultiArch(pkg.applicationInfo)) {
10380                // Warn if we've set an abiOverride for multi-lib packages..
10381                // By definition, we need to copy both 32 and 64 bit libraries for
10382                // such packages.
10383                if (pkg.cpuAbiOverride != null
10384                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10385                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10386                }
10387
10388                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10389                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10390                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10391                    if (extractLibs) {
10392                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10393                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10394                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10395                                useIsaSpecificSubdirs);
10396                    } else {
10397                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10398                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10399                    }
10400                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10401                }
10402
10403                maybeThrowExceptionForMultiArchCopy(
10404                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10405
10406                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10407                    if (extractLibs) {
10408                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10409                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10410                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10411                                useIsaSpecificSubdirs);
10412                    } else {
10413                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10414                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10415                    }
10416                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10417                }
10418
10419                maybeThrowExceptionForMultiArchCopy(
10420                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10421
10422                if (abi64 >= 0) {
10423                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10424                }
10425
10426                if (abi32 >= 0) {
10427                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10428                    if (abi64 >= 0) {
10429                        if (pkg.use32bitAbi) {
10430                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10431                            pkg.applicationInfo.primaryCpuAbi = abi;
10432                        } else {
10433                            pkg.applicationInfo.secondaryCpuAbi = abi;
10434                        }
10435                    } else {
10436                        pkg.applicationInfo.primaryCpuAbi = abi;
10437                    }
10438                }
10439
10440            } else {
10441                String[] abiList = (cpuAbiOverride != null) ?
10442                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10443
10444                // Enable gross and lame hacks for apps that are built with old
10445                // SDK tools. We must scan their APKs for renderscript bitcode and
10446                // not launch them if it's present. Don't bother checking on devices
10447                // that don't have 64 bit support.
10448                boolean needsRenderScriptOverride = false;
10449                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10450                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10451                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10452                    needsRenderScriptOverride = true;
10453                }
10454
10455                final int copyRet;
10456                if (extractLibs) {
10457                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10458                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10459                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10460                } else {
10461                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10462                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10463                }
10464                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10465
10466                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10467                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10468                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10469                }
10470
10471                if (copyRet >= 0) {
10472                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10473                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10474                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10475                } else if (needsRenderScriptOverride) {
10476                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10477                }
10478            }
10479        } catch (IOException ioe) {
10480            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10481        } finally {
10482            IoUtils.closeQuietly(handle);
10483        }
10484
10485        // Now that we've calculated the ABIs and determined if it's an internal app,
10486        // we will go ahead and populate the nativeLibraryPath.
10487        setNativeLibraryPaths(pkg, appLib32InstallDir);
10488    }
10489
10490    /**
10491     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10492     * i.e, so that all packages can be run inside a single process if required.
10493     *
10494     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10495     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10496     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10497     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10498     * updating a package that belongs to a shared user.
10499     *
10500     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10501     * adds unnecessary complexity.
10502     */
10503    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10504            PackageParser.Package scannedPackage) {
10505        String requiredInstructionSet = null;
10506        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10507            requiredInstructionSet = VMRuntime.getInstructionSet(
10508                     scannedPackage.applicationInfo.primaryCpuAbi);
10509        }
10510
10511        PackageSetting requirer = null;
10512        for (PackageSetting ps : packagesForUser) {
10513            // If packagesForUser contains scannedPackage, we skip it. This will happen
10514            // when scannedPackage is an update of an existing package. Without this check,
10515            // we will never be able to change the ABI of any package belonging to a shared
10516            // user, even if it's compatible with other packages.
10517            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10518                if (ps.primaryCpuAbiString == null) {
10519                    continue;
10520                }
10521
10522                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10523                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10524                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10525                    // this but there's not much we can do.
10526                    String errorMessage = "Instruction set mismatch, "
10527                            + ((requirer == null) ? "[caller]" : requirer)
10528                            + " requires " + requiredInstructionSet + " whereas " + ps
10529                            + " requires " + instructionSet;
10530                    Slog.w(TAG, errorMessage);
10531                }
10532
10533                if (requiredInstructionSet == null) {
10534                    requiredInstructionSet = instructionSet;
10535                    requirer = ps;
10536                }
10537            }
10538        }
10539
10540        if (requiredInstructionSet != null) {
10541            String adjustedAbi;
10542            if (requirer != null) {
10543                // requirer != null implies that either scannedPackage was null or that scannedPackage
10544                // did not require an ABI, in which case we have to adjust scannedPackage to match
10545                // the ABI of the set (which is the same as requirer's ABI)
10546                adjustedAbi = requirer.primaryCpuAbiString;
10547                if (scannedPackage != null) {
10548                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10549                }
10550            } else {
10551                // requirer == null implies that we're updating all ABIs in the set to
10552                // match scannedPackage.
10553                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10554            }
10555
10556            for (PackageSetting ps : packagesForUser) {
10557                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10558                    if (ps.primaryCpuAbiString != null) {
10559                        continue;
10560                    }
10561
10562                    ps.primaryCpuAbiString = adjustedAbi;
10563                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10564                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10565                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10566                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10567                                + " (requirer="
10568                                + (requirer == null ? "null" : requirer.pkg.packageName)
10569                                + ", scannedPackage="
10570                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10571                                + ")");
10572                        try {
10573                            mInstaller.rmdex(ps.codePathString,
10574                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10575                        } catch (InstallerException ignored) {
10576                        }
10577                    }
10578                }
10579            }
10580        }
10581    }
10582
10583    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10584        synchronized (mPackages) {
10585            mResolverReplaced = true;
10586            // Set up information for custom user intent resolution activity.
10587            mResolveActivity.applicationInfo = pkg.applicationInfo;
10588            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10589            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10590            mResolveActivity.processName = pkg.applicationInfo.packageName;
10591            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10592            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10593                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10594            mResolveActivity.theme = 0;
10595            mResolveActivity.exported = true;
10596            mResolveActivity.enabled = true;
10597            mResolveInfo.activityInfo = mResolveActivity;
10598            mResolveInfo.priority = 0;
10599            mResolveInfo.preferredOrder = 0;
10600            mResolveInfo.match = 0;
10601            mResolveComponentName = mCustomResolverComponentName;
10602            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10603                    mResolveComponentName);
10604        }
10605    }
10606
10607    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10608        if (installerComponent == null) {
10609            if (DEBUG_EPHEMERAL) {
10610                Slog.d(TAG, "Clear ephemeral installer activity");
10611            }
10612            mInstantAppInstallerActivity.applicationInfo = null;
10613            return;
10614        }
10615
10616        if (DEBUG_EPHEMERAL) {
10617            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10618        }
10619        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10620        // Set up information for ephemeral installer activity
10621        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10622        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10623        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10624        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10625        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10626        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10627                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10628        mInstantAppInstallerActivity.theme = 0;
10629        mInstantAppInstallerActivity.exported = true;
10630        mInstantAppInstallerActivity.enabled = true;
10631        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10632        mInstantAppInstallerInfo.priority = 0;
10633        mInstantAppInstallerInfo.preferredOrder = 1;
10634        mInstantAppInstallerInfo.isDefault = true;
10635        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10636                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10637    }
10638
10639    private static String calculateBundledApkRoot(final String codePathString) {
10640        final File codePath = new File(codePathString);
10641        final File codeRoot;
10642        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10643            codeRoot = Environment.getRootDirectory();
10644        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10645            codeRoot = Environment.getOemDirectory();
10646        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10647            codeRoot = Environment.getVendorDirectory();
10648        } else {
10649            // Unrecognized code path; take its top real segment as the apk root:
10650            // e.g. /something/app/blah.apk => /something
10651            try {
10652                File f = codePath.getCanonicalFile();
10653                File parent = f.getParentFile();    // non-null because codePath is a file
10654                File tmp;
10655                while ((tmp = parent.getParentFile()) != null) {
10656                    f = parent;
10657                    parent = tmp;
10658                }
10659                codeRoot = f;
10660                Slog.w(TAG, "Unrecognized code path "
10661                        + codePath + " - using " + codeRoot);
10662            } catch (IOException e) {
10663                // Can't canonicalize the code path -- shenanigans?
10664                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10665                return Environment.getRootDirectory().getPath();
10666            }
10667        }
10668        return codeRoot.getPath();
10669    }
10670
10671    /**
10672     * Derive and set the location of native libraries for the given package,
10673     * which varies depending on where and how the package was installed.
10674     */
10675    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10676        final ApplicationInfo info = pkg.applicationInfo;
10677        final String codePath = pkg.codePath;
10678        final File codeFile = new File(codePath);
10679        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10680        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10681
10682        info.nativeLibraryRootDir = null;
10683        info.nativeLibraryRootRequiresIsa = false;
10684        info.nativeLibraryDir = null;
10685        info.secondaryNativeLibraryDir = null;
10686
10687        if (isApkFile(codeFile)) {
10688            // Monolithic install
10689            if (bundledApp) {
10690                // If "/system/lib64/apkname" exists, assume that is the per-package
10691                // native library directory to use; otherwise use "/system/lib/apkname".
10692                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10693                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10694                        getPrimaryInstructionSet(info));
10695
10696                // This is a bundled system app so choose the path based on the ABI.
10697                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10698                // is just the default path.
10699                final String apkName = deriveCodePathName(codePath);
10700                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10701                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10702                        apkName).getAbsolutePath();
10703
10704                if (info.secondaryCpuAbi != null) {
10705                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10706                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10707                            secondaryLibDir, apkName).getAbsolutePath();
10708                }
10709            } else if (asecApp) {
10710                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10711                        .getAbsolutePath();
10712            } else {
10713                final String apkName = deriveCodePathName(codePath);
10714                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10715                        .getAbsolutePath();
10716            }
10717
10718            info.nativeLibraryRootRequiresIsa = false;
10719            info.nativeLibraryDir = info.nativeLibraryRootDir;
10720        } else {
10721            // Cluster install
10722            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10723            info.nativeLibraryRootRequiresIsa = true;
10724
10725            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10726                    getPrimaryInstructionSet(info)).getAbsolutePath();
10727
10728            if (info.secondaryCpuAbi != null) {
10729                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10730                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10731            }
10732        }
10733    }
10734
10735    /**
10736     * Calculate the abis and roots for a bundled app. These can uniquely
10737     * be determined from the contents of the system partition, i.e whether
10738     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10739     * of this information, and instead assume that the system was built
10740     * sensibly.
10741     */
10742    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10743                                           PackageSetting pkgSetting) {
10744        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10745
10746        // If "/system/lib64/apkname" exists, assume that is the per-package
10747        // native library directory to use; otherwise use "/system/lib/apkname".
10748        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10749        setBundledAppAbi(pkg, apkRoot, apkName);
10750        // pkgSetting might be null during rescan following uninstall of updates
10751        // to a bundled app, so accommodate that possibility.  The settings in
10752        // that case will be established later from the parsed package.
10753        //
10754        // If the settings aren't null, sync them up with what we've just derived.
10755        // note that apkRoot isn't stored in the package settings.
10756        if (pkgSetting != null) {
10757            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10758            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10759        }
10760    }
10761
10762    /**
10763     * Deduces the ABI of a bundled app and sets the relevant fields on the
10764     * parsed pkg object.
10765     *
10766     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10767     *        under which system libraries are installed.
10768     * @param apkName the name of the installed package.
10769     */
10770    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10771        final File codeFile = new File(pkg.codePath);
10772
10773        final boolean has64BitLibs;
10774        final boolean has32BitLibs;
10775        if (isApkFile(codeFile)) {
10776            // Monolithic install
10777            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10778            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10779        } else {
10780            // Cluster install
10781            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10782            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10783                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10784                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10785                has64BitLibs = (new File(rootDir, isa)).exists();
10786            } else {
10787                has64BitLibs = false;
10788            }
10789            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10790                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10791                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10792                has32BitLibs = (new File(rootDir, isa)).exists();
10793            } else {
10794                has32BitLibs = false;
10795            }
10796        }
10797
10798        if (has64BitLibs && !has32BitLibs) {
10799            // The package has 64 bit libs, but not 32 bit libs. Its primary
10800            // ABI should be 64 bit. We can safely assume here that the bundled
10801            // native libraries correspond to the most preferred ABI in the list.
10802
10803            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10804            pkg.applicationInfo.secondaryCpuAbi = null;
10805        } else if (has32BitLibs && !has64BitLibs) {
10806            // The package has 32 bit libs but not 64 bit libs. Its primary
10807            // ABI should be 32 bit.
10808
10809            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10810            pkg.applicationInfo.secondaryCpuAbi = null;
10811        } else if (has32BitLibs && has64BitLibs) {
10812            // The application has both 64 and 32 bit bundled libraries. We check
10813            // here that the app declares multiArch support, and warn if it doesn't.
10814            //
10815            // We will be lenient here and record both ABIs. The primary will be the
10816            // ABI that's higher on the list, i.e, a device that's configured to prefer
10817            // 64 bit apps will see a 64 bit primary ABI,
10818
10819            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10820                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10821            }
10822
10823            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10824                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10825                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10826            } else {
10827                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10828                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10829            }
10830        } else {
10831            pkg.applicationInfo.primaryCpuAbi = null;
10832            pkg.applicationInfo.secondaryCpuAbi = null;
10833        }
10834    }
10835
10836    private void killApplication(String pkgName, int appId, String reason) {
10837        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10838    }
10839
10840    private void killApplication(String pkgName, int appId, int userId, String reason) {
10841        // Request the ActivityManager to kill the process(only for existing packages)
10842        // so that we do not end up in a confused state while the user is still using the older
10843        // version of the application while the new one gets installed.
10844        final long token = Binder.clearCallingIdentity();
10845        try {
10846            IActivityManager am = ActivityManager.getService();
10847            if (am != null) {
10848                try {
10849                    am.killApplication(pkgName, appId, userId, reason);
10850                } catch (RemoteException e) {
10851                }
10852            }
10853        } finally {
10854            Binder.restoreCallingIdentity(token);
10855        }
10856    }
10857
10858    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10859        // Remove the parent package setting
10860        PackageSetting ps = (PackageSetting) pkg.mExtras;
10861        if (ps != null) {
10862            removePackageLI(ps, chatty);
10863        }
10864        // Remove the child package setting
10865        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10866        for (int i = 0; i < childCount; i++) {
10867            PackageParser.Package childPkg = pkg.childPackages.get(i);
10868            ps = (PackageSetting) childPkg.mExtras;
10869            if (ps != null) {
10870                removePackageLI(ps, chatty);
10871            }
10872        }
10873    }
10874
10875    void removePackageLI(PackageSetting ps, boolean chatty) {
10876        if (DEBUG_INSTALL) {
10877            if (chatty)
10878                Log.d(TAG, "Removing package " + ps.name);
10879        }
10880
10881        // writer
10882        synchronized (mPackages) {
10883            mPackages.remove(ps.name);
10884            final PackageParser.Package pkg = ps.pkg;
10885            if (pkg != null) {
10886                cleanPackageDataStructuresLILPw(pkg, chatty);
10887            }
10888        }
10889    }
10890
10891    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10892        if (DEBUG_INSTALL) {
10893            if (chatty)
10894                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10895        }
10896
10897        // writer
10898        synchronized (mPackages) {
10899            // Remove the parent package
10900            mPackages.remove(pkg.applicationInfo.packageName);
10901            cleanPackageDataStructuresLILPw(pkg, chatty);
10902
10903            // Remove the child packages
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                mPackages.remove(childPkg.applicationInfo.packageName);
10908                cleanPackageDataStructuresLILPw(childPkg, chatty);
10909            }
10910        }
10911    }
10912
10913    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10914        int N = pkg.providers.size();
10915        StringBuilder r = null;
10916        int i;
10917        for (i=0; i<N; i++) {
10918            PackageParser.Provider p = pkg.providers.get(i);
10919            mProviders.removeProvider(p);
10920            if (p.info.authority == null) {
10921
10922                /* There was another ContentProvider with this authority when
10923                 * this app was installed so this authority is null,
10924                 * Ignore it as we don't have to unregister the provider.
10925                 */
10926                continue;
10927            }
10928            String names[] = p.info.authority.split(";");
10929            for (int j = 0; j < names.length; j++) {
10930                if (mProvidersByAuthority.get(names[j]) == p) {
10931                    mProvidersByAuthority.remove(names[j]);
10932                    if (DEBUG_REMOVE) {
10933                        if (chatty)
10934                            Log.d(TAG, "Unregistered content provider: " + names[j]
10935                                    + ", className = " + p.info.name + ", isSyncable = "
10936                                    + p.info.isSyncable);
10937                    }
10938                }
10939            }
10940            if (DEBUG_REMOVE && chatty) {
10941                if (r == null) {
10942                    r = new StringBuilder(256);
10943                } else {
10944                    r.append(' ');
10945                }
10946                r.append(p.info.name);
10947            }
10948        }
10949        if (r != null) {
10950            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10951        }
10952
10953        N = pkg.services.size();
10954        r = null;
10955        for (i=0; i<N; i++) {
10956            PackageParser.Service s = pkg.services.get(i);
10957            mServices.removeService(s);
10958            if (chatty) {
10959                if (r == null) {
10960                    r = new StringBuilder(256);
10961                } else {
10962                    r.append(' ');
10963                }
10964                r.append(s.info.name);
10965            }
10966        }
10967        if (r != null) {
10968            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10969        }
10970
10971        N = pkg.receivers.size();
10972        r = null;
10973        for (i=0; i<N; i++) {
10974            PackageParser.Activity a = pkg.receivers.get(i);
10975            mReceivers.removeActivity(a, "receiver");
10976            if (DEBUG_REMOVE && chatty) {
10977                if (r == null) {
10978                    r = new StringBuilder(256);
10979                } else {
10980                    r.append(' ');
10981                }
10982                r.append(a.info.name);
10983            }
10984        }
10985        if (r != null) {
10986            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10987        }
10988
10989        N = pkg.activities.size();
10990        r = null;
10991        for (i=0; i<N; i++) {
10992            PackageParser.Activity a = pkg.activities.get(i);
10993            mActivities.removeActivity(a, "activity");
10994            if (DEBUG_REMOVE && chatty) {
10995                if (r == null) {
10996                    r = new StringBuilder(256);
10997                } else {
10998                    r.append(' ');
10999                }
11000                r.append(a.info.name);
11001            }
11002        }
11003        if (r != null) {
11004            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11005        }
11006
11007        N = pkg.permissions.size();
11008        r = null;
11009        for (i=0; i<N; i++) {
11010            PackageParser.Permission p = pkg.permissions.get(i);
11011            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11012            if (bp == null) {
11013                bp = mSettings.mPermissionTrees.get(p.info.name);
11014            }
11015            if (bp != null && bp.perm == p) {
11016                bp.perm = null;
11017                if (DEBUG_REMOVE && chatty) {
11018                    if (r == null) {
11019                        r = new StringBuilder(256);
11020                    } else {
11021                        r.append(' ');
11022                    }
11023                    r.append(p.info.name);
11024                }
11025            }
11026            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11027                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11028                if (appOpPkgs != null) {
11029                    appOpPkgs.remove(pkg.packageName);
11030                }
11031            }
11032        }
11033        if (r != null) {
11034            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11035        }
11036
11037        N = pkg.requestedPermissions.size();
11038        r = null;
11039        for (i=0; i<N; i++) {
11040            String perm = pkg.requestedPermissions.get(i);
11041            BasePermission bp = mSettings.mPermissions.get(perm);
11042            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11043                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11044                if (appOpPkgs != null) {
11045                    appOpPkgs.remove(pkg.packageName);
11046                    if (appOpPkgs.isEmpty()) {
11047                        mAppOpPermissionPackages.remove(perm);
11048                    }
11049                }
11050            }
11051        }
11052        if (r != null) {
11053            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11054        }
11055
11056        N = pkg.instrumentation.size();
11057        r = null;
11058        for (i=0; i<N; i++) {
11059            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11060            mInstrumentation.remove(a.getComponentName());
11061            if (DEBUG_REMOVE && chatty) {
11062                if (r == null) {
11063                    r = new StringBuilder(256);
11064                } else {
11065                    r.append(' ');
11066                }
11067                r.append(a.info.name);
11068            }
11069        }
11070        if (r != null) {
11071            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11072        }
11073
11074        r = null;
11075        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11076            // Only system apps can hold shared libraries.
11077            if (pkg.libraryNames != null) {
11078                for (i = 0; i < pkg.libraryNames.size(); i++) {
11079                    String name = pkg.libraryNames.get(i);
11080                    if (removeSharedLibraryLPw(name, 0)) {
11081                        if (DEBUG_REMOVE && chatty) {
11082                            if (r == null) {
11083                                r = new StringBuilder(256);
11084                            } else {
11085                                r.append(' ');
11086                            }
11087                            r.append(name);
11088                        }
11089                    }
11090                }
11091            }
11092        }
11093
11094        r = null;
11095
11096        // Any package can hold static shared libraries.
11097        if (pkg.staticSharedLibName != null) {
11098            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11099                if (DEBUG_REMOVE && chatty) {
11100                    if (r == null) {
11101                        r = new StringBuilder(256);
11102                    } else {
11103                        r.append(' ');
11104                    }
11105                    r.append(pkg.staticSharedLibName);
11106                }
11107            }
11108        }
11109
11110        if (r != null) {
11111            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11112        }
11113    }
11114
11115    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11116        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11117            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11118                return true;
11119            }
11120        }
11121        return false;
11122    }
11123
11124    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11125    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11126    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11127
11128    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11129        // Update the parent permissions
11130        updatePermissionsLPw(pkg.packageName, pkg, flags);
11131        // Update the child permissions
11132        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11133        for (int i = 0; i < childCount; i++) {
11134            PackageParser.Package childPkg = pkg.childPackages.get(i);
11135            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11136        }
11137    }
11138
11139    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11140            int flags) {
11141        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11142        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11143    }
11144
11145    private void updatePermissionsLPw(String changingPkg,
11146            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11147        // Make sure there are no dangling permission trees.
11148        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11149        while (it.hasNext()) {
11150            final BasePermission bp = it.next();
11151            if (bp.packageSetting == null) {
11152                // We may not yet have parsed the package, so just see if
11153                // we still know about its settings.
11154                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11155            }
11156            if (bp.packageSetting == null) {
11157                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11158                        + " from package " + bp.sourcePackage);
11159                it.remove();
11160            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11161                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11162                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11163                            + " from package " + bp.sourcePackage);
11164                    flags |= UPDATE_PERMISSIONS_ALL;
11165                    it.remove();
11166                }
11167            }
11168        }
11169
11170        // Make sure all dynamic permissions have been assigned to a package,
11171        // and make sure there are no dangling permissions.
11172        it = mSettings.mPermissions.values().iterator();
11173        while (it.hasNext()) {
11174            final BasePermission bp = it.next();
11175            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11176                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11177                        + bp.name + " pkg=" + bp.sourcePackage
11178                        + " info=" + bp.pendingInfo);
11179                if (bp.packageSetting == null && bp.pendingInfo != null) {
11180                    final BasePermission tree = findPermissionTreeLP(bp.name);
11181                    if (tree != null && tree.perm != null) {
11182                        bp.packageSetting = tree.packageSetting;
11183                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11184                                new PermissionInfo(bp.pendingInfo));
11185                        bp.perm.info.packageName = tree.perm.info.packageName;
11186                        bp.perm.info.name = bp.name;
11187                        bp.uid = tree.uid;
11188                    }
11189                }
11190            }
11191            if (bp.packageSetting == null) {
11192                // We may not yet have parsed the package, so just see if
11193                // we still know about its settings.
11194                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11195            }
11196            if (bp.packageSetting == null) {
11197                Slog.w(TAG, "Removing dangling permission: " + bp.name
11198                        + " from package " + bp.sourcePackage);
11199                it.remove();
11200            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11201                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11202                    Slog.i(TAG, "Removing old permission: " + bp.name
11203                            + " from package " + bp.sourcePackage);
11204                    flags |= UPDATE_PERMISSIONS_ALL;
11205                    it.remove();
11206                }
11207            }
11208        }
11209
11210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11211        // Now update the permissions for all packages, in particular
11212        // replace the granted permissions of the system packages.
11213        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11214            for (PackageParser.Package pkg : mPackages.values()) {
11215                if (pkg != pkgInfo) {
11216                    // Only replace for packages on requested volume
11217                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11218                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11219                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11220                    grantPermissionsLPw(pkg, replace, changingPkg);
11221                }
11222            }
11223        }
11224
11225        if (pkgInfo != null) {
11226            // Only replace for packages on requested volume
11227            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11228            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11229                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11230            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11231        }
11232        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11233    }
11234
11235    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11236            String packageOfInterest) {
11237        // IMPORTANT: There are two types of permissions: install and runtime.
11238        // Install time permissions are granted when the app is installed to
11239        // all device users and users added in the future. Runtime permissions
11240        // are granted at runtime explicitly to specific users. Normal and signature
11241        // protected permissions are install time permissions. Dangerous permissions
11242        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11243        // otherwise they are runtime permissions. This function does not manage
11244        // runtime permissions except for the case an app targeting Lollipop MR1
11245        // being upgraded to target a newer SDK, in which case dangerous permissions
11246        // are transformed from install time to runtime ones.
11247
11248        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11249        if (ps == null) {
11250            return;
11251        }
11252
11253        PermissionsState permissionsState = ps.getPermissionsState();
11254        PermissionsState origPermissions = permissionsState;
11255
11256        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11257
11258        boolean runtimePermissionsRevoked = false;
11259        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11260
11261        boolean changedInstallPermission = false;
11262
11263        if (replace) {
11264            ps.installPermissionsFixed = false;
11265            if (!ps.isSharedUser()) {
11266                origPermissions = new PermissionsState(permissionsState);
11267                permissionsState.reset();
11268            } else {
11269                // We need to know only about runtime permission changes since the
11270                // calling code always writes the install permissions state but
11271                // the runtime ones are written only if changed. The only cases of
11272                // changed runtime permissions here are promotion of an install to
11273                // runtime and revocation of a runtime from a shared user.
11274                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11275                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11276                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11277                    runtimePermissionsRevoked = true;
11278                }
11279            }
11280        }
11281
11282        permissionsState.setGlobalGids(mGlobalGids);
11283
11284        final int N = pkg.requestedPermissions.size();
11285        for (int i=0; i<N; i++) {
11286            final String name = pkg.requestedPermissions.get(i);
11287            final BasePermission bp = mSettings.mPermissions.get(name);
11288
11289            if (DEBUG_INSTALL) {
11290                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11291            }
11292
11293            if (bp == null || bp.packageSetting == null) {
11294                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11295                    Slog.w(TAG, "Unknown permission " + name
11296                            + " in package " + pkg.packageName);
11297                }
11298                continue;
11299            }
11300
11301
11302            // Limit ephemeral apps to ephemeral allowed permissions.
11303            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11304                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11305                        + pkg.packageName);
11306                continue;
11307            }
11308
11309            final String perm = bp.name;
11310            boolean allowedSig = false;
11311            int grant = GRANT_DENIED;
11312
11313            // Keep track of app op permissions.
11314            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11315                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11316                if (pkgs == null) {
11317                    pkgs = new ArraySet<>();
11318                    mAppOpPermissionPackages.put(bp.name, pkgs);
11319                }
11320                pkgs.add(pkg.packageName);
11321            }
11322
11323            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11324            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11325                    >= Build.VERSION_CODES.M;
11326            switch (level) {
11327                case PermissionInfo.PROTECTION_NORMAL: {
11328                    // For all apps normal permissions are install time ones.
11329                    grant = GRANT_INSTALL;
11330                } break;
11331
11332                case PermissionInfo.PROTECTION_DANGEROUS: {
11333                    // If a permission review is required for legacy apps we represent
11334                    // their permissions as always granted runtime ones since we need
11335                    // to keep the review required permission flag per user while an
11336                    // install permission's state is shared across all users.
11337                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11338                        // For legacy apps dangerous permissions are install time ones.
11339                        grant = GRANT_INSTALL;
11340                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11341                        // For legacy apps that became modern, install becomes runtime.
11342                        grant = GRANT_UPGRADE;
11343                    } else if (mPromoteSystemApps
11344                            && isSystemApp(ps)
11345                            && mExistingSystemPackages.contains(ps.name)) {
11346                        // For legacy system apps, install becomes runtime.
11347                        // We cannot check hasInstallPermission() for system apps since those
11348                        // permissions were granted implicitly and not persisted pre-M.
11349                        grant = GRANT_UPGRADE;
11350                    } else {
11351                        // For modern apps keep runtime permissions unchanged.
11352                        grant = GRANT_RUNTIME;
11353                    }
11354                } break;
11355
11356                case PermissionInfo.PROTECTION_SIGNATURE: {
11357                    // For all apps signature permissions are install time ones.
11358                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11359                    if (allowedSig) {
11360                        grant = GRANT_INSTALL;
11361                    }
11362                } break;
11363            }
11364
11365            if (DEBUG_INSTALL) {
11366                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11367            }
11368
11369            if (grant != GRANT_DENIED) {
11370                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11371                    // If this is an existing, non-system package, then
11372                    // we can't add any new permissions to it.
11373                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11374                        // Except...  if this is a permission that was added
11375                        // to the platform (note: need to only do this when
11376                        // updating the platform).
11377                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11378                            grant = GRANT_DENIED;
11379                        }
11380                    }
11381                }
11382
11383                switch (grant) {
11384                    case GRANT_INSTALL: {
11385                        // Revoke this as runtime permission to handle the case of
11386                        // a runtime permission being downgraded to an install one.
11387                        // Also in permission review mode we keep dangerous permissions
11388                        // for legacy apps
11389                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11390                            if (origPermissions.getRuntimePermissionState(
11391                                    bp.name, userId) != null) {
11392                                // Revoke the runtime permission and clear the flags.
11393                                origPermissions.revokeRuntimePermission(bp, userId);
11394                                origPermissions.updatePermissionFlags(bp, userId,
11395                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11396                                // If we revoked a permission permission, we have to write.
11397                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11398                                        changedRuntimePermissionUserIds, userId);
11399                            }
11400                        }
11401                        // Grant an install permission.
11402                        if (permissionsState.grantInstallPermission(bp) !=
11403                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11404                            changedInstallPermission = true;
11405                        }
11406                    } break;
11407
11408                    case GRANT_RUNTIME: {
11409                        // Grant previously granted runtime permissions.
11410                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11411                            PermissionState permissionState = origPermissions
11412                                    .getRuntimePermissionState(bp.name, userId);
11413                            int flags = permissionState != null
11414                                    ? permissionState.getFlags() : 0;
11415                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11416                                // Don't propagate the permission in a permission review mode if
11417                                // the former was revoked, i.e. marked to not propagate on upgrade.
11418                                // Note that in a permission review mode install permissions are
11419                                // represented as constantly granted runtime ones since we need to
11420                                // keep a per user state associated with the permission. Also the
11421                                // revoke on upgrade flag is no longer applicable and is reset.
11422                                final boolean revokeOnUpgrade = (flags & PackageManager
11423                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11424                                if (revokeOnUpgrade) {
11425                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11426                                    // Since we changed the flags, we have to write.
11427                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11428                                            changedRuntimePermissionUserIds, userId);
11429                                }
11430                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11431                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11432                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11433                                        // If we cannot put the permission as it was,
11434                                        // we have to write.
11435                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11436                                                changedRuntimePermissionUserIds, userId);
11437                                    }
11438                                }
11439
11440                                // If the app supports runtime permissions no need for a review.
11441                                if (mPermissionReviewRequired
11442                                        && appSupportsRuntimePermissions
11443                                        && (flags & PackageManager
11444                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11445                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11446                                    // Since we changed the flags, we have to write.
11447                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11448                                            changedRuntimePermissionUserIds, userId);
11449                                }
11450                            } else if (mPermissionReviewRequired
11451                                    && !appSupportsRuntimePermissions) {
11452                                // For legacy apps that need a permission review, every new
11453                                // runtime permission is granted but it is pending a review.
11454                                // We also need to review only platform defined runtime
11455                                // permissions as these are the only ones the platform knows
11456                                // how to disable the API to simulate revocation as legacy
11457                                // apps don't expect to run with revoked permissions.
11458                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11459                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11460                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11461                                        // We changed the flags, hence have to write.
11462                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11463                                                changedRuntimePermissionUserIds, userId);
11464                                    }
11465                                }
11466                                if (permissionsState.grantRuntimePermission(bp, userId)
11467                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11468                                    // We changed the permission, hence have to write.
11469                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11470                                            changedRuntimePermissionUserIds, userId);
11471                                }
11472                            }
11473                            // Propagate the permission flags.
11474                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11475                        }
11476                    } break;
11477
11478                    case GRANT_UPGRADE: {
11479                        // Grant runtime permissions for a previously held install permission.
11480                        PermissionState permissionState = origPermissions
11481                                .getInstallPermissionState(bp.name);
11482                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11483
11484                        if (origPermissions.revokeInstallPermission(bp)
11485                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11486                            // We will be transferring the permission flags, so clear them.
11487                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11488                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11489                            changedInstallPermission = true;
11490                        }
11491
11492                        // If the permission is not to be promoted to runtime we ignore it and
11493                        // also its other flags as they are not applicable to install permissions.
11494                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11495                            for (int userId : currentUserIds) {
11496                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11497                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11498                                    // Transfer the permission flags.
11499                                    permissionsState.updatePermissionFlags(bp, userId,
11500                                            flags, flags);
11501                                    // If we granted the permission, we have to write.
11502                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11503                                            changedRuntimePermissionUserIds, userId);
11504                                }
11505                            }
11506                        }
11507                    } break;
11508
11509                    default: {
11510                        if (packageOfInterest == null
11511                                || packageOfInterest.equals(pkg.packageName)) {
11512                            Slog.w(TAG, "Not granting permission " + perm
11513                                    + " to package " + pkg.packageName
11514                                    + " because it was previously installed without");
11515                        }
11516                    } break;
11517                }
11518            } else {
11519                if (permissionsState.revokeInstallPermission(bp) !=
11520                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11521                    // Also drop the permission flags.
11522                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11523                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11524                    changedInstallPermission = true;
11525                    Slog.i(TAG, "Un-granting permission " + perm
11526                            + " from package " + pkg.packageName
11527                            + " (protectionLevel=" + bp.protectionLevel
11528                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11529                            + ")");
11530                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11531                    // Don't print warning for app op permissions, since it is fine for them
11532                    // not to be granted, there is a UI for the user to decide.
11533                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11534                        Slog.w(TAG, "Not granting permission " + perm
11535                                + " to package " + pkg.packageName
11536                                + " (protectionLevel=" + bp.protectionLevel
11537                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11538                                + ")");
11539                    }
11540                }
11541            }
11542        }
11543
11544        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11545                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11546            // This is the first that we have heard about this package, so the
11547            // permissions we have now selected are fixed until explicitly
11548            // changed.
11549            ps.installPermissionsFixed = true;
11550        }
11551
11552        // Persist the runtime permissions state for users with changes. If permissions
11553        // were revoked because no app in the shared user declares them we have to
11554        // write synchronously to avoid losing runtime permissions state.
11555        for (int userId : changedRuntimePermissionUserIds) {
11556            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11557        }
11558    }
11559
11560    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11561        boolean allowed = false;
11562        final int NP = PackageParser.NEW_PERMISSIONS.length;
11563        for (int ip=0; ip<NP; ip++) {
11564            final PackageParser.NewPermissionInfo npi
11565                    = PackageParser.NEW_PERMISSIONS[ip];
11566            if (npi.name.equals(perm)
11567                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11568                allowed = true;
11569                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11570                        + pkg.packageName);
11571                break;
11572            }
11573        }
11574        return allowed;
11575    }
11576
11577    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11578            BasePermission bp, PermissionsState origPermissions) {
11579        boolean privilegedPermission = (bp.protectionLevel
11580                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11581        boolean privappPermissionsDisable =
11582                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11583        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11584        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11585        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11586                && !platformPackage && platformPermission) {
11587            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11588                    .getPrivAppPermissions(pkg.packageName);
11589            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11590            if (!whitelisted) {
11591                Slog.w(TAG, "Privileged permission " + perm + " for package "
11592                        + pkg.packageName + " - not in privapp-permissions whitelist");
11593                // Only report violations for apps on system image
11594                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11595                    if (mPrivappPermissionsViolations == null) {
11596                        mPrivappPermissionsViolations = new ArraySet<>();
11597                    }
11598                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11599                }
11600                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11601                    return false;
11602                }
11603            }
11604        }
11605        boolean allowed = (compareSignatures(
11606                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11607                        == PackageManager.SIGNATURE_MATCH)
11608                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11609                        == PackageManager.SIGNATURE_MATCH);
11610        if (!allowed && privilegedPermission) {
11611            if (isSystemApp(pkg)) {
11612                // For updated system applications, a system permission
11613                // is granted only if it had been defined by the original application.
11614                if (pkg.isUpdatedSystemApp()) {
11615                    final PackageSetting sysPs = mSettings
11616                            .getDisabledSystemPkgLPr(pkg.packageName);
11617                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11618                        // If the original was granted this permission, we take
11619                        // that grant decision as read and propagate it to the
11620                        // update.
11621                        if (sysPs.isPrivileged()) {
11622                            allowed = true;
11623                        }
11624                    } else {
11625                        // The system apk may have been updated with an older
11626                        // version of the one on the data partition, but which
11627                        // granted a new system permission that it didn't have
11628                        // before.  In this case we do want to allow the app to
11629                        // now get the new permission if the ancestral apk is
11630                        // privileged to get it.
11631                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11632                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11633                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11634                                    allowed = true;
11635                                    break;
11636                                }
11637                            }
11638                        }
11639                        // Also if a privileged parent package on the system image or any of
11640                        // its children requested a privileged permission, the updated child
11641                        // packages can also get the permission.
11642                        if (pkg.parentPackage != null) {
11643                            final PackageSetting disabledSysParentPs = mSettings
11644                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11645                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11646                                    && disabledSysParentPs.isPrivileged()) {
11647                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11648                                    allowed = true;
11649                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11650                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11651                                    for (int i = 0; i < count; i++) {
11652                                        PackageParser.Package disabledSysChildPkg =
11653                                                disabledSysParentPs.pkg.childPackages.get(i);
11654                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11655                                                perm)) {
11656                                            allowed = true;
11657                                            break;
11658                                        }
11659                                    }
11660                                }
11661                            }
11662                        }
11663                    }
11664                } else {
11665                    allowed = isPrivilegedApp(pkg);
11666                }
11667            }
11668        }
11669        if (!allowed) {
11670            if (!allowed && (bp.protectionLevel
11671                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11672                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11673                // If this was a previously normal/dangerous permission that got moved
11674                // to a system permission as part of the runtime permission redesign, then
11675                // we still want to blindly grant it to old apps.
11676                allowed = true;
11677            }
11678            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11679                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11680                // If this permission is to be granted to the system installer and
11681                // this app is an installer, then it gets the permission.
11682                allowed = true;
11683            }
11684            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11685                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11686                // If this permission is to be granted to the system verifier and
11687                // this app is a verifier, then it gets the permission.
11688                allowed = true;
11689            }
11690            if (!allowed && (bp.protectionLevel
11691                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11692                    && isSystemApp(pkg)) {
11693                // Any pre-installed system app is allowed to get this permission.
11694                allowed = true;
11695            }
11696            if (!allowed && (bp.protectionLevel
11697                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11698                // For development permissions, a development permission
11699                // is granted only if it was already granted.
11700                allowed = origPermissions.hasInstallPermission(perm);
11701            }
11702            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11703                    && pkg.packageName.equals(mSetupWizardPackage)) {
11704                // If this permission is to be granted to the system setup wizard and
11705                // this app is a setup wizard, then it gets the permission.
11706                allowed = true;
11707            }
11708        }
11709        return allowed;
11710    }
11711
11712    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11713        final int permCount = pkg.requestedPermissions.size();
11714        for (int j = 0; j < permCount; j++) {
11715            String requestedPermission = pkg.requestedPermissions.get(j);
11716            if (permission.equals(requestedPermission)) {
11717                return true;
11718            }
11719        }
11720        return false;
11721    }
11722
11723    final class ActivityIntentResolver
11724            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11725        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11726                boolean defaultOnly, int userId) {
11727            if (!sUserManager.exists(userId)) return null;
11728            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11729            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11730        }
11731
11732        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11733                int userId) {
11734            if (!sUserManager.exists(userId)) return null;
11735            mFlags = flags;
11736            return super.queryIntent(intent, resolvedType,
11737                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11738                    userId);
11739        }
11740
11741        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11742                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11743            if (!sUserManager.exists(userId)) return null;
11744            if (packageActivities == null) {
11745                return null;
11746            }
11747            mFlags = flags;
11748            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11749            final int N = packageActivities.size();
11750            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11751                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11752
11753            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11754            for (int i = 0; i < N; ++i) {
11755                intentFilters = packageActivities.get(i).intents;
11756                if (intentFilters != null && intentFilters.size() > 0) {
11757                    PackageParser.ActivityIntentInfo[] array =
11758                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11759                    intentFilters.toArray(array);
11760                    listCut.add(array);
11761                }
11762            }
11763            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11764        }
11765
11766        /**
11767         * Finds a privileged activity that matches the specified activity names.
11768         */
11769        private PackageParser.Activity findMatchingActivity(
11770                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11771            for (PackageParser.Activity sysActivity : activityList) {
11772                if (sysActivity.info.name.equals(activityInfo.name)) {
11773                    return sysActivity;
11774                }
11775                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11776                    return sysActivity;
11777                }
11778                if (sysActivity.info.targetActivity != null) {
11779                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11780                        return sysActivity;
11781                    }
11782                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11783                        return sysActivity;
11784                    }
11785                }
11786            }
11787            return null;
11788        }
11789
11790        public class IterGenerator<E> {
11791            public Iterator<E> generate(ActivityIntentInfo info) {
11792                return null;
11793            }
11794        }
11795
11796        public class ActionIterGenerator extends IterGenerator<String> {
11797            @Override
11798            public Iterator<String> generate(ActivityIntentInfo info) {
11799                return info.actionsIterator();
11800            }
11801        }
11802
11803        public class CategoriesIterGenerator extends IterGenerator<String> {
11804            @Override
11805            public Iterator<String> generate(ActivityIntentInfo info) {
11806                return info.categoriesIterator();
11807            }
11808        }
11809
11810        public class SchemesIterGenerator extends IterGenerator<String> {
11811            @Override
11812            public Iterator<String> generate(ActivityIntentInfo info) {
11813                return info.schemesIterator();
11814            }
11815        }
11816
11817        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11818            @Override
11819            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11820                return info.authoritiesIterator();
11821            }
11822        }
11823
11824        /**
11825         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11826         * MODIFIED. Do not pass in a list that should not be changed.
11827         */
11828        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11829                IterGenerator<T> generator, Iterator<T> searchIterator) {
11830            // loop through the set of actions; every one must be found in the intent filter
11831            while (searchIterator.hasNext()) {
11832                // we must have at least one filter in the list to consider a match
11833                if (intentList.size() == 0) {
11834                    break;
11835                }
11836
11837                final T searchAction = searchIterator.next();
11838
11839                // loop through the set of intent filters
11840                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11841                while (intentIter.hasNext()) {
11842                    final ActivityIntentInfo intentInfo = intentIter.next();
11843                    boolean selectionFound = false;
11844
11845                    // loop through the intent filter's selection criteria; at least one
11846                    // of them must match the searched criteria
11847                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11848                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11849                        final T intentSelection = intentSelectionIter.next();
11850                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11851                            selectionFound = true;
11852                            break;
11853                        }
11854                    }
11855
11856                    // the selection criteria wasn't found in this filter's set; this filter
11857                    // is not a potential match
11858                    if (!selectionFound) {
11859                        intentIter.remove();
11860                    }
11861                }
11862            }
11863        }
11864
11865        private boolean isProtectedAction(ActivityIntentInfo filter) {
11866            final Iterator<String> actionsIter = filter.actionsIterator();
11867            while (actionsIter != null && actionsIter.hasNext()) {
11868                final String filterAction = actionsIter.next();
11869                if (PROTECTED_ACTIONS.contains(filterAction)) {
11870                    return true;
11871                }
11872            }
11873            return false;
11874        }
11875
11876        /**
11877         * Adjusts the priority of the given intent filter according to policy.
11878         * <p>
11879         * <ul>
11880         * <li>The priority for non privileged applications is capped to '0'</li>
11881         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11882         * <li>The priority for unbundled updates to privileged applications is capped to the
11883         *      priority defined on the system partition</li>
11884         * </ul>
11885         * <p>
11886         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11887         * allowed to obtain any priority on any action.
11888         */
11889        private void adjustPriority(
11890                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11891            // nothing to do; priority is fine as-is
11892            if (intent.getPriority() <= 0) {
11893                return;
11894            }
11895
11896            final ActivityInfo activityInfo = intent.activity.info;
11897            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11898
11899            final boolean privilegedApp =
11900                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11901            if (!privilegedApp) {
11902                // non-privileged applications can never define a priority >0
11903                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11904                        + " package: " + applicationInfo.packageName
11905                        + " activity: " + intent.activity.className
11906                        + " origPrio: " + intent.getPriority());
11907                intent.setPriority(0);
11908                return;
11909            }
11910
11911            if (systemActivities == null) {
11912                // the system package is not disabled; we're parsing the system partition
11913                if (isProtectedAction(intent)) {
11914                    if (mDeferProtectedFilters) {
11915                        // We can't deal with these just yet. No component should ever obtain a
11916                        // >0 priority for a protected actions, with ONE exception -- the setup
11917                        // wizard. The setup wizard, however, cannot be known until we're able to
11918                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11919                        // until all intent filters have been processed. Chicken, meet egg.
11920                        // Let the filter temporarily have a high priority and rectify the
11921                        // priorities after all system packages have been scanned.
11922                        mProtectedFilters.add(intent);
11923                        if (DEBUG_FILTERS) {
11924                            Slog.i(TAG, "Protected action; save for later;"
11925                                    + " package: " + applicationInfo.packageName
11926                                    + " activity: " + intent.activity.className
11927                                    + " origPrio: " + intent.getPriority());
11928                        }
11929                        return;
11930                    } else {
11931                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11932                            Slog.i(TAG, "No setup wizard;"
11933                                + " All protected intents capped to priority 0");
11934                        }
11935                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11936                            if (DEBUG_FILTERS) {
11937                                Slog.i(TAG, "Found setup wizard;"
11938                                    + " allow priority " + intent.getPriority() + ";"
11939                                    + " package: " + intent.activity.info.packageName
11940                                    + " activity: " + intent.activity.className
11941                                    + " priority: " + intent.getPriority());
11942                            }
11943                            // setup wizard gets whatever it wants
11944                            return;
11945                        }
11946                        Slog.w(TAG, "Protected action; cap priority to 0;"
11947                                + " package: " + intent.activity.info.packageName
11948                                + " activity: " + intent.activity.className
11949                                + " origPrio: " + intent.getPriority());
11950                        intent.setPriority(0);
11951                        return;
11952                    }
11953                }
11954                // privileged apps on the system image get whatever priority they request
11955                return;
11956            }
11957
11958            // privileged app unbundled update ... try to find the same activity
11959            final PackageParser.Activity foundActivity =
11960                    findMatchingActivity(systemActivities, activityInfo);
11961            if (foundActivity == null) {
11962                // this is a new activity; it cannot obtain >0 priority
11963                if (DEBUG_FILTERS) {
11964                    Slog.i(TAG, "New activity; cap priority to 0;"
11965                            + " package: " + applicationInfo.packageName
11966                            + " activity: " + intent.activity.className
11967                            + " origPrio: " + intent.getPriority());
11968                }
11969                intent.setPriority(0);
11970                return;
11971            }
11972
11973            // found activity, now check for filter equivalence
11974
11975            // a shallow copy is enough; we modify the list, not its contents
11976            final List<ActivityIntentInfo> intentListCopy =
11977                    new ArrayList<>(foundActivity.intents);
11978            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11979
11980            // find matching action subsets
11981            final Iterator<String> actionsIterator = intent.actionsIterator();
11982            if (actionsIterator != null) {
11983                getIntentListSubset(
11984                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11985                if (intentListCopy.size() == 0) {
11986                    // no more intents to match; we're not equivalent
11987                    if (DEBUG_FILTERS) {
11988                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11989                                + " package: " + applicationInfo.packageName
11990                                + " activity: " + intent.activity.className
11991                                + " origPrio: " + intent.getPriority());
11992                    }
11993                    intent.setPriority(0);
11994                    return;
11995                }
11996            }
11997
11998            // find matching category subsets
11999            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12000            if (categoriesIterator != null) {
12001                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12002                        categoriesIterator);
12003                if (intentListCopy.size() == 0) {
12004                    // no more intents to match; we're not equivalent
12005                    if (DEBUG_FILTERS) {
12006                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12007                                + " package: " + applicationInfo.packageName
12008                                + " activity: " + intent.activity.className
12009                                + " origPrio: " + intent.getPriority());
12010                    }
12011                    intent.setPriority(0);
12012                    return;
12013                }
12014            }
12015
12016            // find matching schemes subsets
12017            final Iterator<String> schemesIterator = intent.schemesIterator();
12018            if (schemesIterator != null) {
12019                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12020                        schemesIterator);
12021                if (intentListCopy.size() == 0) {
12022                    // no more intents to match; we're not equivalent
12023                    if (DEBUG_FILTERS) {
12024                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12025                                + " package: " + applicationInfo.packageName
12026                                + " activity: " + intent.activity.className
12027                                + " origPrio: " + intent.getPriority());
12028                    }
12029                    intent.setPriority(0);
12030                    return;
12031                }
12032            }
12033
12034            // find matching authorities subsets
12035            final Iterator<IntentFilter.AuthorityEntry>
12036                    authoritiesIterator = intent.authoritiesIterator();
12037            if (authoritiesIterator != null) {
12038                getIntentListSubset(intentListCopy,
12039                        new AuthoritiesIterGenerator(),
12040                        authoritiesIterator);
12041                if (intentListCopy.size() == 0) {
12042                    // no more intents to match; we're not equivalent
12043                    if (DEBUG_FILTERS) {
12044                        Slog.i(TAG, "Mismatched authority; 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            // we found matching filter(s); app gets the max priority of all intents
12055            int cappedPriority = 0;
12056            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12057                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12058            }
12059            if (intent.getPriority() > cappedPriority) {
12060                if (DEBUG_FILTERS) {
12061                    Slog.i(TAG, "Found matching filter(s);"
12062                            + " cap priority to " + cappedPriority + ";"
12063                            + " package: " + applicationInfo.packageName
12064                            + " activity: " + intent.activity.className
12065                            + " origPrio: " + intent.getPriority());
12066                }
12067                intent.setPriority(cappedPriority);
12068                return;
12069            }
12070            // all this for nothing; the requested priority was <= what was on the system
12071        }
12072
12073        public final void addActivity(PackageParser.Activity a, String type) {
12074            mActivities.put(a.getComponentName(), a);
12075            if (DEBUG_SHOW_INFO)
12076                Log.v(
12077                TAG, "  " + type + " " +
12078                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12079            if (DEBUG_SHOW_INFO)
12080                Log.v(TAG, "    Class=" + a.info.name);
12081            final int NI = a.intents.size();
12082            for (int j=0; j<NI; j++) {
12083                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12084                if ("activity".equals(type)) {
12085                    final PackageSetting ps =
12086                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12087                    final List<PackageParser.Activity> systemActivities =
12088                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12089                    adjustPriority(systemActivities, intent);
12090                }
12091                if (DEBUG_SHOW_INFO) {
12092                    Log.v(TAG, "    IntentFilter:");
12093                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12094                }
12095                if (!intent.debugCheck()) {
12096                    Log.w(TAG, "==> For Activity " + a.info.name);
12097                }
12098                addFilter(intent);
12099            }
12100        }
12101
12102        public final void removeActivity(PackageParser.Activity a, String type) {
12103            mActivities.remove(a.getComponentName());
12104            if (DEBUG_SHOW_INFO) {
12105                Log.v(TAG, "  " + type + " "
12106                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12107                                : a.info.name) + ":");
12108                Log.v(TAG, "    Class=" + a.info.name);
12109            }
12110            final int NI = a.intents.size();
12111            for (int j=0; j<NI; j++) {
12112                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12113                if (DEBUG_SHOW_INFO) {
12114                    Log.v(TAG, "    IntentFilter:");
12115                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12116                }
12117                removeFilter(intent);
12118            }
12119        }
12120
12121        @Override
12122        protected boolean allowFilterResult(
12123                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12124            ActivityInfo filterAi = filter.activity.info;
12125            for (int i=dest.size()-1; i>=0; i--) {
12126                ActivityInfo destAi = dest.get(i).activityInfo;
12127                if (destAi.name == filterAi.name
12128                        && destAi.packageName == filterAi.packageName) {
12129                    return false;
12130                }
12131            }
12132            return true;
12133        }
12134
12135        @Override
12136        protected ActivityIntentInfo[] newArray(int size) {
12137            return new ActivityIntentInfo[size];
12138        }
12139
12140        @Override
12141        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12142            if (!sUserManager.exists(userId)) return true;
12143            PackageParser.Package p = filter.activity.owner;
12144            if (p != null) {
12145                PackageSetting ps = (PackageSetting)p.mExtras;
12146                if (ps != null) {
12147                    // System apps are never considered stopped for purposes of
12148                    // filtering, because there may be no way for the user to
12149                    // actually re-launch them.
12150                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12151                            && ps.getStopped(userId);
12152                }
12153            }
12154            return false;
12155        }
12156
12157        @Override
12158        protected boolean isPackageForFilter(String packageName,
12159                PackageParser.ActivityIntentInfo info) {
12160            return packageName.equals(info.activity.owner.packageName);
12161        }
12162
12163        @Override
12164        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12165                int match, int userId) {
12166            if (!sUserManager.exists(userId)) return null;
12167            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12168                return null;
12169            }
12170            final PackageParser.Activity activity = info.activity;
12171            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12172            if (ps == null) {
12173                return null;
12174            }
12175            final PackageUserState userState = ps.readUserState(userId);
12176            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12177                    userState, userId);
12178            if (ai == null) {
12179                return null;
12180            }
12181            final boolean matchVisibleToInstantApp =
12182                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12183            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12184            // throw out filters that aren't visible to ephemeral apps
12185            if (matchVisibleToInstantApp
12186                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12187                return null;
12188            }
12189            // throw out ephemeral filters if we're not explicitly requesting them
12190            if (!isInstantApp && userState.instantApp) {
12191                return null;
12192            }
12193            final ResolveInfo res = new ResolveInfo();
12194            res.activityInfo = ai;
12195            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12196                res.filter = info;
12197            }
12198            if (info != null) {
12199                res.handleAllWebDataURI = info.handleAllWebDataURI();
12200            }
12201            res.priority = info.getPriority();
12202            res.preferredOrder = activity.owner.mPreferredOrder;
12203            //System.out.println("Result: " + res.activityInfo.className +
12204            //                   " = " + res.priority);
12205            res.match = match;
12206            res.isDefault = info.hasDefault;
12207            res.labelRes = info.labelRes;
12208            res.nonLocalizedLabel = info.nonLocalizedLabel;
12209            if (userNeedsBadging(userId)) {
12210                res.noResourceId = true;
12211            } else {
12212                res.icon = info.icon;
12213            }
12214            res.iconResourceId = info.icon;
12215            res.system = res.activityInfo.applicationInfo.isSystemApp();
12216            res.instantAppAvailable = userState.instantApp;
12217            return res;
12218        }
12219
12220        @Override
12221        protected void sortResults(List<ResolveInfo> results) {
12222            Collections.sort(results, mResolvePrioritySorter);
12223        }
12224
12225        @Override
12226        protected void dumpFilter(PrintWriter out, String prefix,
12227                PackageParser.ActivityIntentInfo filter) {
12228            out.print(prefix); out.print(
12229                    Integer.toHexString(System.identityHashCode(filter.activity)));
12230                    out.print(' ');
12231                    filter.activity.printComponentShortName(out);
12232                    out.print(" filter ");
12233                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12234        }
12235
12236        @Override
12237        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12238            return filter.activity;
12239        }
12240
12241        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12242            PackageParser.Activity activity = (PackageParser.Activity)label;
12243            out.print(prefix); out.print(
12244                    Integer.toHexString(System.identityHashCode(activity)));
12245                    out.print(' ');
12246                    activity.printComponentShortName(out);
12247            if (count > 1) {
12248                out.print(" ("); out.print(count); out.print(" filters)");
12249            }
12250            out.println();
12251        }
12252
12253        // Keys are String (activity class name), values are Activity.
12254        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12255                = new ArrayMap<ComponentName, PackageParser.Activity>();
12256        private int mFlags;
12257    }
12258
12259    private final class ServiceIntentResolver
12260            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12261        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12262                boolean defaultOnly, int userId) {
12263            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12264            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12265        }
12266
12267        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12268                int userId) {
12269            if (!sUserManager.exists(userId)) return null;
12270            mFlags = flags;
12271            return super.queryIntent(intent, resolvedType,
12272                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12273                    userId);
12274        }
12275
12276        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12277                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12278            if (!sUserManager.exists(userId)) return null;
12279            if (packageServices == null) {
12280                return null;
12281            }
12282            mFlags = flags;
12283            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12284            final int N = packageServices.size();
12285            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12286                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12287
12288            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12289            for (int i = 0; i < N; ++i) {
12290                intentFilters = packageServices.get(i).intents;
12291                if (intentFilters != null && intentFilters.size() > 0) {
12292                    PackageParser.ServiceIntentInfo[] array =
12293                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12294                    intentFilters.toArray(array);
12295                    listCut.add(array);
12296                }
12297            }
12298            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12299        }
12300
12301        public final void addService(PackageParser.Service s) {
12302            mServices.put(s.getComponentName(), s);
12303            if (DEBUG_SHOW_INFO) {
12304                Log.v(TAG, "  "
12305                        + (s.info.nonLocalizedLabel != null
12306                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12307                Log.v(TAG, "    Class=" + s.info.name);
12308            }
12309            final int NI = s.intents.size();
12310            int j;
12311            for (j=0; j<NI; j++) {
12312                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12313                if (DEBUG_SHOW_INFO) {
12314                    Log.v(TAG, "    IntentFilter:");
12315                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12316                }
12317                if (!intent.debugCheck()) {
12318                    Log.w(TAG, "==> For Service " + s.info.name);
12319                }
12320                addFilter(intent);
12321            }
12322        }
12323
12324        public final void removeService(PackageParser.Service s) {
12325            mServices.remove(s.getComponentName());
12326            if (DEBUG_SHOW_INFO) {
12327                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12328                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12329                Log.v(TAG, "    Class=" + s.info.name);
12330            }
12331            final int NI = s.intents.size();
12332            int j;
12333            for (j=0; j<NI; j++) {
12334                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12335                if (DEBUG_SHOW_INFO) {
12336                    Log.v(TAG, "    IntentFilter:");
12337                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12338                }
12339                removeFilter(intent);
12340            }
12341        }
12342
12343        @Override
12344        protected boolean allowFilterResult(
12345                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12346            ServiceInfo filterSi = filter.service.info;
12347            for (int i=dest.size()-1; i>=0; i--) {
12348                ServiceInfo destAi = dest.get(i).serviceInfo;
12349                if (destAi.name == filterSi.name
12350                        && destAi.packageName == filterSi.packageName) {
12351                    return false;
12352                }
12353            }
12354            return true;
12355        }
12356
12357        @Override
12358        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12359            return new PackageParser.ServiceIntentInfo[size];
12360        }
12361
12362        @Override
12363        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12364            if (!sUserManager.exists(userId)) return true;
12365            PackageParser.Package p = filter.service.owner;
12366            if (p != null) {
12367                PackageSetting ps = (PackageSetting)p.mExtras;
12368                if (ps != null) {
12369                    // System apps are never considered stopped for purposes of
12370                    // filtering, because there may be no way for the user to
12371                    // actually re-launch them.
12372                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12373                            && ps.getStopped(userId);
12374                }
12375            }
12376            return false;
12377        }
12378
12379        @Override
12380        protected boolean isPackageForFilter(String packageName,
12381                PackageParser.ServiceIntentInfo info) {
12382            return packageName.equals(info.service.owner.packageName);
12383        }
12384
12385        @Override
12386        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12387                int match, int userId) {
12388            if (!sUserManager.exists(userId)) return null;
12389            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12390            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12391                return null;
12392            }
12393            final PackageParser.Service service = info.service;
12394            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12395            if (ps == null) {
12396                return null;
12397            }
12398            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12399                    ps.readUserState(userId), userId);
12400            if (si == null) {
12401                return null;
12402            }
12403            final ResolveInfo res = new ResolveInfo();
12404            res.serviceInfo = si;
12405            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12406                res.filter = filter;
12407            }
12408            res.priority = info.getPriority();
12409            res.preferredOrder = service.owner.mPreferredOrder;
12410            res.match = match;
12411            res.isDefault = info.hasDefault;
12412            res.labelRes = info.labelRes;
12413            res.nonLocalizedLabel = info.nonLocalizedLabel;
12414            res.icon = info.icon;
12415            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12416            return res;
12417        }
12418
12419        @Override
12420        protected void sortResults(List<ResolveInfo> results) {
12421            Collections.sort(results, mResolvePrioritySorter);
12422        }
12423
12424        @Override
12425        protected void dumpFilter(PrintWriter out, String prefix,
12426                PackageParser.ServiceIntentInfo filter) {
12427            out.print(prefix); out.print(
12428                    Integer.toHexString(System.identityHashCode(filter.service)));
12429                    out.print(' ');
12430                    filter.service.printComponentShortName(out);
12431                    out.print(" filter ");
12432                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12433        }
12434
12435        @Override
12436        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12437            return filter.service;
12438        }
12439
12440        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12441            PackageParser.Service service = (PackageParser.Service)label;
12442            out.print(prefix); out.print(
12443                    Integer.toHexString(System.identityHashCode(service)));
12444                    out.print(' ');
12445                    service.printComponentShortName(out);
12446            if (count > 1) {
12447                out.print(" ("); out.print(count); out.print(" filters)");
12448            }
12449            out.println();
12450        }
12451
12452//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12453//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12454//            final List<ResolveInfo> retList = Lists.newArrayList();
12455//            while (i.hasNext()) {
12456//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12457//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12458//                    retList.add(resolveInfo);
12459//                }
12460//            }
12461//            return retList;
12462//        }
12463
12464        // Keys are String (activity class name), values are Activity.
12465        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12466                = new ArrayMap<ComponentName, PackageParser.Service>();
12467        private int mFlags;
12468    }
12469
12470    private final class ProviderIntentResolver
12471            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12472        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12473                boolean defaultOnly, int userId) {
12474            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12475            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12476        }
12477
12478        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12479                int userId) {
12480            if (!sUserManager.exists(userId))
12481                return null;
12482            mFlags = flags;
12483            return super.queryIntent(intent, resolvedType,
12484                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12485                    userId);
12486        }
12487
12488        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12489                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12490            if (!sUserManager.exists(userId))
12491                return null;
12492            if (packageProviders == null) {
12493                return null;
12494            }
12495            mFlags = flags;
12496            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12497            final int N = packageProviders.size();
12498            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12499                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12500
12501            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12502            for (int i = 0; i < N; ++i) {
12503                intentFilters = packageProviders.get(i).intents;
12504                if (intentFilters != null && intentFilters.size() > 0) {
12505                    PackageParser.ProviderIntentInfo[] array =
12506                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12507                    intentFilters.toArray(array);
12508                    listCut.add(array);
12509                }
12510            }
12511            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12512        }
12513
12514        public final void addProvider(PackageParser.Provider p) {
12515            if (mProviders.containsKey(p.getComponentName())) {
12516                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12517                return;
12518            }
12519
12520            mProviders.put(p.getComponentName(), p);
12521            if (DEBUG_SHOW_INFO) {
12522                Log.v(TAG, "  "
12523                        + (p.info.nonLocalizedLabel != null
12524                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12525                Log.v(TAG, "    Class=" + p.info.name);
12526            }
12527            final int NI = p.intents.size();
12528            int j;
12529            for (j = 0; j < NI; j++) {
12530                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12531                if (DEBUG_SHOW_INFO) {
12532                    Log.v(TAG, "    IntentFilter:");
12533                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12534                }
12535                if (!intent.debugCheck()) {
12536                    Log.w(TAG, "==> For Provider " + p.info.name);
12537                }
12538                addFilter(intent);
12539            }
12540        }
12541
12542        public final void removeProvider(PackageParser.Provider p) {
12543            mProviders.remove(p.getComponentName());
12544            if (DEBUG_SHOW_INFO) {
12545                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12546                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12547                Log.v(TAG, "    Class=" + p.info.name);
12548            }
12549            final int NI = p.intents.size();
12550            int j;
12551            for (j = 0; j < NI; j++) {
12552                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12553                if (DEBUG_SHOW_INFO) {
12554                    Log.v(TAG, "    IntentFilter:");
12555                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12556                }
12557                removeFilter(intent);
12558            }
12559        }
12560
12561        @Override
12562        protected boolean allowFilterResult(
12563                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12564            ProviderInfo filterPi = filter.provider.info;
12565            for (int i = dest.size() - 1; i >= 0; i--) {
12566                ProviderInfo destPi = dest.get(i).providerInfo;
12567                if (destPi.name == filterPi.name
12568                        && destPi.packageName == filterPi.packageName) {
12569                    return false;
12570                }
12571            }
12572            return true;
12573        }
12574
12575        @Override
12576        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12577            return new PackageParser.ProviderIntentInfo[size];
12578        }
12579
12580        @Override
12581        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12582            if (!sUserManager.exists(userId))
12583                return true;
12584            PackageParser.Package p = filter.provider.owner;
12585            if (p != null) {
12586                PackageSetting ps = (PackageSetting) p.mExtras;
12587                if (ps != null) {
12588                    // System apps are never considered stopped for purposes of
12589                    // filtering, because there may be no way for the user to
12590                    // actually re-launch them.
12591                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12592                            && ps.getStopped(userId);
12593                }
12594            }
12595            return false;
12596        }
12597
12598        @Override
12599        protected boolean isPackageForFilter(String packageName,
12600                PackageParser.ProviderIntentInfo info) {
12601            return packageName.equals(info.provider.owner.packageName);
12602        }
12603
12604        @Override
12605        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12606                int match, int userId) {
12607            if (!sUserManager.exists(userId))
12608                return null;
12609            final PackageParser.ProviderIntentInfo info = filter;
12610            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12611                return null;
12612            }
12613            final PackageParser.Provider provider = info.provider;
12614            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12615            if (ps == null) {
12616                return null;
12617            }
12618            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12619                    ps.readUserState(userId), userId);
12620            if (pi == null) {
12621                return null;
12622            }
12623            final ResolveInfo res = new ResolveInfo();
12624            res.providerInfo = pi;
12625            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12626                res.filter = filter;
12627            }
12628            res.priority = info.getPriority();
12629            res.preferredOrder = provider.owner.mPreferredOrder;
12630            res.match = match;
12631            res.isDefault = info.hasDefault;
12632            res.labelRes = info.labelRes;
12633            res.nonLocalizedLabel = info.nonLocalizedLabel;
12634            res.icon = info.icon;
12635            res.system = res.providerInfo.applicationInfo.isSystemApp();
12636            return res;
12637        }
12638
12639        @Override
12640        protected void sortResults(List<ResolveInfo> results) {
12641            Collections.sort(results, mResolvePrioritySorter);
12642        }
12643
12644        @Override
12645        protected void dumpFilter(PrintWriter out, String prefix,
12646                PackageParser.ProviderIntentInfo filter) {
12647            out.print(prefix);
12648            out.print(
12649                    Integer.toHexString(System.identityHashCode(filter.provider)));
12650            out.print(' ');
12651            filter.provider.printComponentShortName(out);
12652            out.print(" filter ");
12653            out.println(Integer.toHexString(System.identityHashCode(filter)));
12654        }
12655
12656        @Override
12657        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12658            return filter.provider;
12659        }
12660
12661        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12662            PackageParser.Provider provider = (PackageParser.Provider)label;
12663            out.print(prefix); out.print(
12664                    Integer.toHexString(System.identityHashCode(provider)));
12665                    out.print(' ');
12666                    provider.printComponentShortName(out);
12667            if (count > 1) {
12668                out.print(" ("); out.print(count); out.print(" filters)");
12669            }
12670            out.println();
12671        }
12672
12673        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12674                = new ArrayMap<ComponentName, PackageParser.Provider>();
12675        private int mFlags;
12676    }
12677
12678    static final class EphemeralIntentResolver
12679            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12680        /**
12681         * The result that has the highest defined order. Ordering applies on a
12682         * per-package basis. Mapping is from package name to Pair of order and
12683         * EphemeralResolveInfo.
12684         * <p>
12685         * NOTE: This is implemented as a field variable for convenience and efficiency.
12686         * By having a field variable, we're able to track filter ordering as soon as
12687         * a non-zero order is defined. Otherwise, multiple loops across the result set
12688         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12689         * this needs to be contained entirely within {@link #filterResults}.
12690         */
12691        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12692
12693        @Override
12694        protected AuxiliaryResolveInfo[] newArray(int size) {
12695            return new AuxiliaryResolveInfo[size];
12696        }
12697
12698        @Override
12699        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12700            return true;
12701        }
12702
12703        @Override
12704        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12705                int userId) {
12706            if (!sUserManager.exists(userId)) {
12707                return null;
12708            }
12709            final String packageName = responseObj.resolveInfo.getPackageName();
12710            final Integer order = responseObj.getOrder();
12711            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12712                    mOrderResult.get(packageName);
12713            // ordering is enabled and this item's order isn't high enough
12714            if (lastOrderResult != null && lastOrderResult.first >= order) {
12715                return null;
12716            }
12717            final InstantAppResolveInfo res = responseObj.resolveInfo;
12718            if (order > 0) {
12719                // non-zero order, enable ordering
12720                mOrderResult.put(packageName, new Pair<>(order, res));
12721            }
12722            return responseObj;
12723        }
12724
12725        @Override
12726        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12727            // only do work if ordering is enabled [most of the time it won't be]
12728            if (mOrderResult.size() == 0) {
12729                return;
12730            }
12731            int resultSize = results.size();
12732            for (int i = 0; i < resultSize; i++) {
12733                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12734                final String packageName = info.getPackageName();
12735                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12736                if (savedInfo == null) {
12737                    // package doesn't having ordering
12738                    continue;
12739                }
12740                if (savedInfo.second == info) {
12741                    // circled back to the highest ordered item; remove from order list
12742                    mOrderResult.remove(savedInfo);
12743                    if (mOrderResult.size() == 0) {
12744                        // no more ordered items
12745                        break;
12746                    }
12747                    continue;
12748                }
12749                // item has a worse order, remove it from the result list
12750                results.remove(i);
12751                resultSize--;
12752                i--;
12753            }
12754        }
12755    }
12756
12757    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12758            new Comparator<ResolveInfo>() {
12759        public int compare(ResolveInfo r1, ResolveInfo r2) {
12760            int v1 = r1.priority;
12761            int v2 = r2.priority;
12762            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12763            if (v1 != v2) {
12764                return (v1 > v2) ? -1 : 1;
12765            }
12766            v1 = r1.preferredOrder;
12767            v2 = r2.preferredOrder;
12768            if (v1 != v2) {
12769                return (v1 > v2) ? -1 : 1;
12770            }
12771            if (r1.isDefault != r2.isDefault) {
12772                return r1.isDefault ? -1 : 1;
12773            }
12774            v1 = r1.match;
12775            v2 = r2.match;
12776            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12777            if (v1 != v2) {
12778                return (v1 > v2) ? -1 : 1;
12779            }
12780            if (r1.system != r2.system) {
12781                return r1.system ? -1 : 1;
12782            }
12783            if (r1.activityInfo != null) {
12784                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12785            }
12786            if (r1.serviceInfo != null) {
12787                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12788            }
12789            if (r1.providerInfo != null) {
12790                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12791            }
12792            return 0;
12793        }
12794    };
12795
12796    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12797            new Comparator<ProviderInfo>() {
12798        public int compare(ProviderInfo p1, ProviderInfo p2) {
12799            final int v1 = p1.initOrder;
12800            final int v2 = p2.initOrder;
12801            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12802        }
12803    };
12804
12805    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12806            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12807            final int[] userIds) {
12808        mHandler.post(new Runnable() {
12809            @Override
12810            public void run() {
12811                try {
12812                    final IActivityManager am = ActivityManager.getService();
12813                    if (am == null) return;
12814                    final int[] resolvedUserIds;
12815                    if (userIds == null) {
12816                        resolvedUserIds = am.getRunningUserIds();
12817                    } else {
12818                        resolvedUserIds = userIds;
12819                    }
12820                    for (int id : resolvedUserIds) {
12821                        final Intent intent = new Intent(action,
12822                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12823                        if (extras != null) {
12824                            intent.putExtras(extras);
12825                        }
12826                        if (targetPkg != null) {
12827                            intent.setPackage(targetPkg);
12828                        }
12829                        // Modify the UID when posting to other users
12830                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12831                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12832                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12833                            intent.putExtra(Intent.EXTRA_UID, uid);
12834                        }
12835                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12836                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12837                        if (DEBUG_BROADCASTS) {
12838                            RuntimeException here = new RuntimeException("here");
12839                            here.fillInStackTrace();
12840                            Slog.d(TAG, "Sending to user " + id + ": "
12841                                    + intent.toShortString(false, true, false, false)
12842                                    + " " + intent.getExtras(), here);
12843                        }
12844                        am.broadcastIntent(null, intent, null, finishedReceiver,
12845                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12846                                null, finishedReceiver != null, false, id);
12847                    }
12848                } catch (RemoteException ex) {
12849                }
12850            }
12851        });
12852    }
12853
12854    /**
12855     * Check if the external storage media is available. This is true if there
12856     * is a mounted external storage medium or if the external storage is
12857     * emulated.
12858     */
12859    private boolean isExternalMediaAvailable() {
12860        return mMediaMounted || Environment.isExternalStorageEmulated();
12861    }
12862
12863    @Override
12864    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12865        // writer
12866        synchronized (mPackages) {
12867            if (!isExternalMediaAvailable()) {
12868                // If the external storage is no longer mounted at this point,
12869                // the caller may not have been able to delete all of this
12870                // packages files and can not delete any more.  Bail.
12871                return null;
12872            }
12873            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12874            if (lastPackage != null) {
12875                pkgs.remove(lastPackage);
12876            }
12877            if (pkgs.size() > 0) {
12878                return pkgs.get(0);
12879            }
12880        }
12881        return null;
12882    }
12883
12884    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12885        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12886                userId, andCode ? 1 : 0, packageName);
12887        if (mSystemReady) {
12888            msg.sendToTarget();
12889        } else {
12890            if (mPostSystemReadyMessages == null) {
12891                mPostSystemReadyMessages = new ArrayList<>();
12892            }
12893            mPostSystemReadyMessages.add(msg);
12894        }
12895    }
12896
12897    void startCleaningPackages() {
12898        // reader
12899        if (!isExternalMediaAvailable()) {
12900            return;
12901        }
12902        synchronized (mPackages) {
12903            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12904                return;
12905            }
12906        }
12907        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12908        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12909        IActivityManager am = ActivityManager.getService();
12910        if (am != null) {
12911            try {
12912                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12913                        UserHandle.USER_SYSTEM);
12914            } catch (RemoteException e) {
12915            }
12916        }
12917    }
12918
12919    @Override
12920    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12921            int installFlags, String installerPackageName, int userId) {
12922        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12923
12924        final int callingUid = Binder.getCallingUid();
12925        enforceCrossUserPermission(callingUid, userId,
12926                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12927
12928        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12929            try {
12930                if (observer != null) {
12931                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12932                }
12933            } catch (RemoteException re) {
12934            }
12935            return;
12936        }
12937
12938        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12939            installFlags |= PackageManager.INSTALL_FROM_ADB;
12940
12941        } else {
12942            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12943            // about installerPackageName.
12944
12945            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12946            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12947        }
12948
12949        UserHandle user;
12950        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12951            user = UserHandle.ALL;
12952        } else {
12953            user = new UserHandle(userId);
12954        }
12955
12956        // Only system components can circumvent runtime permissions when installing.
12957        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12958                && mContext.checkCallingOrSelfPermission(Manifest.permission
12959                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12960            throw new SecurityException("You need the "
12961                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12962                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12963        }
12964
12965        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12966                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12967            throw new IllegalArgumentException(
12968                    "New installs into ASEC containers no longer supported");
12969        }
12970
12971        final File originFile = new File(originPath);
12972        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12973
12974        final Message msg = mHandler.obtainMessage(INIT_COPY);
12975        final VerificationInfo verificationInfo = new VerificationInfo(
12976                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12977        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12978                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12979                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12980                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12981        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12982        msg.obj = params;
12983
12984        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12985                System.identityHashCode(msg.obj));
12986        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12987                System.identityHashCode(msg.obj));
12988
12989        mHandler.sendMessage(msg);
12990    }
12991
12992
12993    /**
12994     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12995     * it is acting on behalf on an enterprise or the user).
12996     *
12997     * Note that the ordering of the conditionals in this method is important. The checks we perform
12998     * are as follows, in this order:
12999     *
13000     * 1) If the install is being performed by a system app, we can trust the app to have set the
13001     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13002     *    what it is.
13003     * 2) If the install is being performed by a device or profile owner app, the install reason
13004     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13005     *    set the install reason correctly. If the app targets an older SDK version where install
13006     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13007     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13008     * 3) In all other cases, the install is being performed by a regular app that is neither part
13009     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13010     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13011     *    set to enterprise policy and if so, change it to unknown instead.
13012     */
13013    private int fixUpInstallReason(String installerPackageName, int installerUid,
13014            int installReason) {
13015        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13016                == PERMISSION_GRANTED) {
13017            // If the install is being performed by a system app, we trust that app to have set the
13018            // install reason correctly.
13019            return installReason;
13020        }
13021
13022        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13023            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13024        if (dpm != null) {
13025            ComponentName owner = null;
13026            try {
13027                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13028                if (owner == null) {
13029                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13030                }
13031            } catch (RemoteException e) {
13032            }
13033            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13034                // If the install is being performed by a device or profile owner, the install
13035                // reason should be enterprise policy.
13036                return PackageManager.INSTALL_REASON_POLICY;
13037            }
13038        }
13039
13040        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13041            // If the install is being performed by a regular app (i.e. neither system app nor
13042            // device or profile owner), we have no reason to believe that the app is acting on
13043            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13044            // change it to unknown instead.
13045            return PackageManager.INSTALL_REASON_UNKNOWN;
13046        }
13047
13048        // If the install is being performed by a regular app and the install reason was set to any
13049        // value but enterprise policy, leave the install reason unchanged.
13050        return installReason;
13051    }
13052
13053    void installStage(String packageName, File stagedDir, String stagedCid,
13054            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13055            String installerPackageName, int installerUid, UserHandle user,
13056            Certificate[][] certificates) {
13057        if (DEBUG_EPHEMERAL) {
13058            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13059                Slog.d(TAG, "Ephemeral install of " + packageName);
13060            }
13061        }
13062        final VerificationInfo verificationInfo = new VerificationInfo(
13063                sessionParams.originatingUri, sessionParams.referrerUri,
13064                sessionParams.originatingUid, installerUid);
13065
13066        final OriginInfo origin;
13067        if (stagedDir != null) {
13068            origin = OriginInfo.fromStagedFile(stagedDir);
13069        } else {
13070            origin = OriginInfo.fromStagedContainer(stagedCid);
13071        }
13072
13073        final Message msg = mHandler.obtainMessage(INIT_COPY);
13074        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13075                sessionParams.installReason);
13076        final InstallParams params = new InstallParams(origin, null, observer,
13077                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13078                verificationInfo, user, sessionParams.abiOverride,
13079                sessionParams.grantedRuntimePermissions, certificates, installReason);
13080        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13081        msg.obj = params;
13082
13083        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13084                System.identityHashCode(msg.obj));
13085        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13086                System.identityHashCode(msg.obj));
13087
13088        mHandler.sendMessage(msg);
13089    }
13090
13091    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13092            int userId) {
13093        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13094        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13095    }
13096
13097    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13098            int appId, int... userIds) {
13099        if (ArrayUtils.isEmpty(userIds)) {
13100            return;
13101        }
13102        Bundle extras = new Bundle(1);
13103        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13104        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13105
13106        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13107                packageName, extras, 0, null, null, userIds);
13108        if (isSystem) {
13109            mHandler.post(() -> {
13110                        for (int userId : userIds) {
13111                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13112                        }
13113                    }
13114            );
13115        }
13116    }
13117
13118    /**
13119     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13120     * automatically without needing an explicit launch.
13121     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13122     */
13123    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13124        // If user is not running, the app didn't miss any broadcast
13125        if (!mUserManagerInternal.isUserRunning(userId)) {
13126            return;
13127        }
13128        final IActivityManager am = ActivityManager.getService();
13129        try {
13130            // Deliver LOCKED_BOOT_COMPLETED first
13131            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13132                    .setPackage(packageName);
13133            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13134            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13135                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13136
13137            // Deliver BOOT_COMPLETED only if user is unlocked
13138            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13139                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13140                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13141                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13142            }
13143        } catch (RemoteException e) {
13144            throw e.rethrowFromSystemServer();
13145        }
13146    }
13147
13148    @Override
13149    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13150            int userId) {
13151        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13152        PackageSetting pkgSetting;
13153        final int uid = Binder.getCallingUid();
13154        enforceCrossUserPermission(uid, userId,
13155                true /* requireFullPermission */, true /* checkShell */,
13156                "setApplicationHiddenSetting for user " + userId);
13157
13158        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13159            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13160            return false;
13161        }
13162
13163        long callingId = Binder.clearCallingIdentity();
13164        try {
13165            boolean sendAdded = false;
13166            boolean sendRemoved = false;
13167            // writer
13168            synchronized (mPackages) {
13169                pkgSetting = mSettings.mPackages.get(packageName);
13170                if (pkgSetting == null) {
13171                    return false;
13172                }
13173                // Do not allow "android" is being disabled
13174                if ("android".equals(packageName)) {
13175                    Slog.w(TAG, "Cannot hide package: android");
13176                    return false;
13177                }
13178                // Cannot hide static shared libs as they are considered
13179                // a part of the using app (emulating static linking). Also
13180                // static libs are installed always on internal storage.
13181                PackageParser.Package pkg = mPackages.get(packageName);
13182                if (pkg != null && pkg.staticSharedLibName != null) {
13183                    Slog.w(TAG, "Cannot hide package: " + packageName
13184                            + " providing static shared library: "
13185                            + pkg.staticSharedLibName);
13186                    return false;
13187                }
13188                // Only allow protected packages to hide themselves.
13189                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13190                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13191                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13192                    return false;
13193                }
13194
13195                if (pkgSetting.getHidden(userId) != hidden) {
13196                    pkgSetting.setHidden(hidden, userId);
13197                    mSettings.writePackageRestrictionsLPr(userId);
13198                    if (hidden) {
13199                        sendRemoved = true;
13200                    } else {
13201                        sendAdded = true;
13202                    }
13203                }
13204            }
13205            if (sendAdded) {
13206                sendPackageAddedForUser(packageName, pkgSetting, userId);
13207                return true;
13208            }
13209            if (sendRemoved) {
13210                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13211                        "hiding pkg");
13212                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13213                return true;
13214            }
13215        } finally {
13216            Binder.restoreCallingIdentity(callingId);
13217        }
13218        return false;
13219    }
13220
13221    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13222            int userId) {
13223        final PackageRemovedInfo info = new PackageRemovedInfo();
13224        info.removedPackage = packageName;
13225        info.removedUsers = new int[] {userId};
13226        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13227        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13228    }
13229
13230    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13231        if (pkgList.length > 0) {
13232            Bundle extras = new Bundle(1);
13233            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13234
13235            sendPackageBroadcast(
13236                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13237                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13238                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13239                    new int[] {userId});
13240        }
13241    }
13242
13243    /**
13244     * Returns true if application is not found or there was an error. Otherwise it returns
13245     * the hidden state of the package for the given user.
13246     */
13247    @Override
13248    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13249        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13250        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13251                true /* requireFullPermission */, false /* checkShell */,
13252                "getApplicationHidden for user " + userId);
13253        PackageSetting pkgSetting;
13254        long callingId = Binder.clearCallingIdentity();
13255        try {
13256            // writer
13257            synchronized (mPackages) {
13258                pkgSetting = mSettings.mPackages.get(packageName);
13259                if (pkgSetting == null) {
13260                    return true;
13261                }
13262                return pkgSetting.getHidden(userId);
13263            }
13264        } finally {
13265            Binder.restoreCallingIdentity(callingId);
13266        }
13267    }
13268
13269    /**
13270     * @hide
13271     */
13272    @Override
13273    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13274            int installReason) {
13275        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13276                null);
13277        PackageSetting pkgSetting;
13278        final int uid = Binder.getCallingUid();
13279        enforceCrossUserPermission(uid, userId,
13280                true /* requireFullPermission */, true /* checkShell */,
13281                "installExistingPackage for user " + userId);
13282        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13283            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13284        }
13285
13286        long callingId = Binder.clearCallingIdentity();
13287        try {
13288            boolean installed = false;
13289            final boolean instantApp =
13290                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13291            final boolean fullApp =
13292                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13293
13294            // writer
13295            synchronized (mPackages) {
13296                pkgSetting = mSettings.mPackages.get(packageName);
13297                if (pkgSetting == null) {
13298                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13299                }
13300                if (!pkgSetting.getInstalled(userId)) {
13301                    pkgSetting.setInstalled(true, userId);
13302                    pkgSetting.setHidden(false, userId);
13303                    pkgSetting.setInstallReason(installReason, userId);
13304                    mSettings.writePackageRestrictionsLPr(userId);
13305                    mSettings.writeKernelMappingLPr(pkgSetting);
13306                    installed = true;
13307                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13308                    // upgrade app from instant to full; we don't allow app downgrade
13309                    installed = true;
13310                }
13311                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13312            }
13313
13314            if (installed) {
13315                if (pkgSetting.pkg != null) {
13316                    synchronized (mInstallLock) {
13317                        // We don't need to freeze for a brand new install
13318                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13319                    }
13320                }
13321                sendPackageAddedForUser(packageName, pkgSetting, userId);
13322                synchronized (mPackages) {
13323                    updateSequenceNumberLP(packageName, new int[]{ userId });
13324                }
13325            }
13326        } finally {
13327            Binder.restoreCallingIdentity(callingId);
13328        }
13329
13330        return PackageManager.INSTALL_SUCCEEDED;
13331    }
13332
13333    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13334            boolean instantApp, boolean fullApp) {
13335        // no state specified; do nothing
13336        if (!instantApp && !fullApp) {
13337            return;
13338        }
13339        if (userId != UserHandle.USER_ALL) {
13340            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13341                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13342            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13343                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13344            }
13345        } else {
13346            for (int currentUserId : sUserManager.getUserIds()) {
13347                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13348                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13349                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13350                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13351                }
13352            }
13353        }
13354    }
13355
13356    boolean isUserRestricted(int userId, String restrictionKey) {
13357        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13358        if (restrictions.getBoolean(restrictionKey, false)) {
13359            Log.w(TAG, "User is restricted: " + restrictionKey);
13360            return true;
13361        }
13362        return false;
13363    }
13364
13365    @Override
13366    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13367            int userId) {
13368        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13369        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13370                true /* requireFullPermission */, true /* checkShell */,
13371                "setPackagesSuspended for user " + userId);
13372
13373        if (ArrayUtils.isEmpty(packageNames)) {
13374            return packageNames;
13375        }
13376
13377        // List of package names for whom the suspended state has changed.
13378        List<String> changedPackages = new ArrayList<>(packageNames.length);
13379        // List of package names for whom the suspended state is not set as requested in this
13380        // method.
13381        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13382        long callingId = Binder.clearCallingIdentity();
13383        try {
13384            for (int i = 0; i < packageNames.length; i++) {
13385                String packageName = packageNames[i];
13386                boolean changed = false;
13387                final int appId;
13388                synchronized (mPackages) {
13389                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13390                    if (pkgSetting == null) {
13391                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13392                                + "\". Skipping suspending/un-suspending.");
13393                        unactionedPackages.add(packageName);
13394                        continue;
13395                    }
13396                    appId = pkgSetting.appId;
13397                    if (pkgSetting.getSuspended(userId) != suspended) {
13398                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13399                            unactionedPackages.add(packageName);
13400                            continue;
13401                        }
13402                        pkgSetting.setSuspended(suspended, userId);
13403                        mSettings.writePackageRestrictionsLPr(userId);
13404                        changed = true;
13405                        changedPackages.add(packageName);
13406                    }
13407                }
13408
13409                if (changed && suspended) {
13410                    killApplication(packageName, UserHandle.getUid(userId, appId),
13411                            "suspending package");
13412                }
13413            }
13414        } finally {
13415            Binder.restoreCallingIdentity(callingId);
13416        }
13417
13418        if (!changedPackages.isEmpty()) {
13419            sendPackagesSuspendedForUser(changedPackages.toArray(
13420                    new String[changedPackages.size()]), userId, suspended);
13421        }
13422
13423        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13424    }
13425
13426    @Override
13427    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13428        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13429                true /* requireFullPermission */, false /* checkShell */,
13430                "isPackageSuspendedForUser for user " + userId);
13431        synchronized (mPackages) {
13432            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13433            if (pkgSetting == null) {
13434                throw new IllegalArgumentException("Unknown target package: " + packageName);
13435            }
13436            return pkgSetting.getSuspended(userId);
13437        }
13438    }
13439
13440    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13441        if (isPackageDeviceAdmin(packageName, userId)) {
13442            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13443                    + "\": has an active device admin");
13444            return false;
13445        }
13446
13447        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13448        if (packageName.equals(activeLauncherPackageName)) {
13449            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13450                    + "\": contains the active launcher");
13451            return false;
13452        }
13453
13454        if (packageName.equals(mRequiredInstallerPackage)) {
13455            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13456                    + "\": required for package installation");
13457            return false;
13458        }
13459
13460        if (packageName.equals(mRequiredUninstallerPackage)) {
13461            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13462                    + "\": required for package uninstallation");
13463            return false;
13464        }
13465
13466        if (packageName.equals(mRequiredVerifierPackage)) {
13467            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13468                    + "\": required for package verification");
13469            return false;
13470        }
13471
13472        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13473            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13474                    + "\": is the default dialer");
13475            return false;
13476        }
13477
13478        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13479            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13480                    + "\": protected package");
13481            return false;
13482        }
13483
13484        // Cannot suspend static shared libs as they are considered
13485        // a part of the using app (emulating static linking). Also
13486        // static libs are installed always on internal storage.
13487        PackageParser.Package pkg = mPackages.get(packageName);
13488        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13489            Slog.w(TAG, "Cannot suspend package: " + packageName
13490                    + " providing static shared library: "
13491                    + pkg.staticSharedLibName);
13492            return false;
13493        }
13494
13495        return true;
13496    }
13497
13498    private String getActiveLauncherPackageName(int userId) {
13499        Intent intent = new Intent(Intent.ACTION_MAIN);
13500        intent.addCategory(Intent.CATEGORY_HOME);
13501        ResolveInfo resolveInfo = resolveIntent(
13502                intent,
13503                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13504                PackageManager.MATCH_DEFAULT_ONLY,
13505                userId);
13506
13507        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13508    }
13509
13510    private String getDefaultDialerPackageName(int userId) {
13511        synchronized (mPackages) {
13512            return mSettings.getDefaultDialerPackageNameLPw(userId);
13513        }
13514    }
13515
13516    @Override
13517    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13518        mContext.enforceCallingOrSelfPermission(
13519                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13520                "Only package verification agents can verify applications");
13521
13522        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13523        final PackageVerificationResponse response = new PackageVerificationResponse(
13524                verificationCode, Binder.getCallingUid());
13525        msg.arg1 = id;
13526        msg.obj = response;
13527        mHandler.sendMessage(msg);
13528    }
13529
13530    @Override
13531    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13532            long millisecondsToDelay) {
13533        mContext.enforceCallingOrSelfPermission(
13534                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13535                "Only package verification agents can extend verification timeouts");
13536
13537        final PackageVerificationState state = mPendingVerification.get(id);
13538        final PackageVerificationResponse response = new PackageVerificationResponse(
13539                verificationCodeAtTimeout, Binder.getCallingUid());
13540
13541        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13542            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13543        }
13544        if (millisecondsToDelay < 0) {
13545            millisecondsToDelay = 0;
13546        }
13547        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13548                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13549            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13550        }
13551
13552        if ((state != null) && !state.timeoutExtended()) {
13553            state.extendTimeout();
13554
13555            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13556            msg.arg1 = id;
13557            msg.obj = response;
13558            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13559        }
13560    }
13561
13562    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13563            int verificationCode, UserHandle user) {
13564        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13565        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13566        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13567        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13568        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13569
13570        mContext.sendBroadcastAsUser(intent, user,
13571                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13572    }
13573
13574    private ComponentName matchComponentForVerifier(String packageName,
13575            List<ResolveInfo> receivers) {
13576        ActivityInfo targetReceiver = null;
13577
13578        final int NR = receivers.size();
13579        for (int i = 0; i < NR; i++) {
13580            final ResolveInfo info = receivers.get(i);
13581            if (info.activityInfo == null) {
13582                continue;
13583            }
13584
13585            if (packageName.equals(info.activityInfo.packageName)) {
13586                targetReceiver = info.activityInfo;
13587                break;
13588            }
13589        }
13590
13591        if (targetReceiver == null) {
13592            return null;
13593        }
13594
13595        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13596    }
13597
13598    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13599            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13600        if (pkgInfo.verifiers.length == 0) {
13601            return null;
13602        }
13603
13604        final int N = pkgInfo.verifiers.length;
13605        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13606        for (int i = 0; i < N; i++) {
13607            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13608
13609            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13610                    receivers);
13611            if (comp == null) {
13612                continue;
13613            }
13614
13615            final int verifierUid = getUidForVerifier(verifierInfo);
13616            if (verifierUid == -1) {
13617                continue;
13618            }
13619
13620            if (DEBUG_VERIFY) {
13621                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13622                        + " with the correct signature");
13623            }
13624            sufficientVerifiers.add(comp);
13625            verificationState.addSufficientVerifier(verifierUid);
13626        }
13627
13628        return sufficientVerifiers;
13629    }
13630
13631    private int getUidForVerifier(VerifierInfo verifierInfo) {
13632        synchronized (mPackages) {
13633            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13634            if (pkg == null) {
13635                return -1;
13636            } else if (pkg.mSignatures.length != 1) {
13637                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13638                        + " has more than one signature; ignoring");
13639                return -1;
13640            }
13641
13642            /*
13643             * If the public key of the package's signature does not match
13644             * our expected public key, then this is a different package and
13645             * we should skip.
13646             */
13647
13648            final byte[] expectedPublicKey;
13649            try {
13650                final Signature verifierSig = pkg.mSignatures[0];
13651                final PublicKey publicKey = verifierSig.getPublicKey();
13652                expectedPublicKey = publicKey.getEncoded();
13653            } catch (CertificateException e) {
13654                return -1;
13655            }
13656
13657            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13658
13659            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13660                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13661                        + " does not have the expected public key; ignoring");
13662                return -1;
13663            }
13664
13665            return pkg.applicationInfo.uid;
13666        }
13667    }
13668
13669    @Override
13670    public void finishPackageInstall(int token, boolean didLaunch) {
13671        enforceSystemOrRoot("Only the system is allowed to finish installs");
13672
13673        if (DEBUG_INSTALL) {
13674            Slog.v(TAG, "BM finishing package install for " + token);
13675        }
13676        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13677
13678        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13679        mHandler.sendMessage(msg);
13680    }
13681
13682    /**
13683     * Get the verification agent timeout.
13684     *
13685     * @return verification timeout in milliseconds
13686     */
13687    private long getVerificationTimeout() {
13688        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13689                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13690                DEFAULT_VERIFICATION_TIMEOUT);
13691    }
13692
13693    /**
13694     * Get the default verification agent response code.
13695     *
13696     * @return default verification response code
13697     */
13698    private int getDefaultVerificationResponse() {
13699        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13700                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13701                DEFAULT_VERIFICATION_RESPONSE);
13702    }
13703
13704    /**
13705     * Check whether or not package verification has been enabled.
13706     *
13707     * @return true if verification should be performed
13708     */
13709    private boolean isVerificationEnabled(int userId, int installFlags) {
13710        if (!DEFAULT_VERIFY_ENABLE) {
13711            return false;
13712        }
13713
13714        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13715
13716        // Check if installing from ADB
13717        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13718            // Do not run verification in a test harness environment
13719            if (ActivityManager.isRunningInTestHarness()) {
13720                return false;
13721            }
13722            if (ensureVerifyAppsEnabled) {
13723                return true;
13724            }
13725            // Check if the developer does not want package verification for ADB installs
13726            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13727                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13728                return false;
13729            }
13730        }
13731
13732        if (ensureVerifyAppsEnabled) {
13733            return true;
13734        }
13735
13736        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13737                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13738    }
13739
13740    @Override
13741    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13742            throws RemoteException {
13743        mContext.enforceCallingOrSelfPermission(
13744                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13745                "Only intentfilter verification agents can verify applications");
13746
13747        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13748        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13749                Binder.getCallingUid(), verificationCode, failedDomains);
13750        msg.arg1 = id;
13751        msg.obj = response;
13752        mHandler.sendMessage(msg);
13753    }
13754
13755    @Override
13756    public int getIntentVerificationStatus(String packageName, int userId) {
13757        synchronized (mPackages) {
13758            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13759        }
13760    }
13761
13762    @Override
13763    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13764        mContext.enforceCallingOrSelfPermission(
13765                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13766
13767        boolean result = false;
13768        synchronized (mPackages) {
13769            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13770        }
13771        if (result) {
13772            scheduleWritePackageRestrictionsLocked(userId);
13773        }
13774        return result;
13775    }
13776
13777    @Override
13778    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13779            String packageName) {
13780        synchronized (mPackages) {
13781            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13782        }
13783    }
13784
13785    @Override
13786    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13787        if (TextUtils.isEmpty(packageName)) {
13788            return ParceledListSlice.emptyList();
13789        }
13790        synchronized (mPackages) {
13791            PackageParser.Package pkg = mPackages.get(packageName);
13792            if (pkg == null || pkg.activities == null) {
13793                return ParceledListSlice.emptyList();
13794            }
13795            final int count = pkg.activities.size();
13796            ArrayList<IntentFilter> result = new ArrayList<>();
13797            for (int n=0; n<count; n++) {
13798                PackageParser.Activity activity = pkg.activities.get(n);
13799                if (activity.intents != null && activity.intents.size() > 0) {
13800                    result.addAll(activity.intents);
13801                }
13802            }
13803            return new ParceledListSlice<>(result);
13804        }
13805    }
13806
13807    @Override
13808    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13809        mContext.enforceCallingOrSelfPermission(
13810                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13811
13812        synchronized (mPackages) {
13813            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13814            if (packageName != null) {
13815                result |= updateIntentVerificationStatus(packageName,
13816                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13817                        userId);
13818                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13819                        packageName, userId);
13820            }
13821            return result;
13822        }
13823    }
13824
13825    @Override
13826    public String getDefaultBrowserPackageName(int userId) {
13827        synchronized (mPackages) {
13828            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13829        }
13830    }
13831
13832    /**
13833     * Get the "allow unknown sources" setting.
13834     *
13835     * @return the current "allow unknown sources" setting
13836     */
13837    private int getUnknownSourcesSettings() {
13838        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13839                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13840                -1);
13841    }
13842
13843    @Override
13844    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13845        final int uid = Binder.getCallingUid();
13846        // writer
13847        synchronized (mPackages) {
13848            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13849            if (targetPackageSetting == null) {
13850                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13851            }
13852
13853            PackageSetting installerPackageSetting;
13854            if (installerPackageName != null) {
13855                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13856                if (installerPackageSetting == null) {
13857                    throw new IllegalArgumentException("Unknown installer package: "
13858                            + installerPackageName);
13859                }
13860            } else {
13861                installerPackageSetting = null;
13862            }
13863
13864            Signature[] callerSignature;
13865            Object obj = mSettings.getUserIdLPr(uid);
13866            if (obj != null) {
13867                if (obj instanceof SharedUserSetting) {
13868                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13869                } else if (obj instanceof PackageSetting) {
13870                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13871                } else {
13872                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13873                }
13874            } else {
13875                throw new SecurityException("Unknown calling UID: " + uid);
13876            }
13877
13878            // Verify: can't set installerPackageName to a package that is
13879            // not signed with the same cert as the caller.
13880            if (installerPackageSetting != null) {
13881                if (compareSignatures(callerSignature,
13882                        installerPackageSetting.signatures.mSignatures)
13883                        != PackageManager.SIGNATURE_MATCH) {
13884                    throw new SecurityException(
13885                            "Caller does not have same cert as new installer package "
13886                            + installerPackageName);
13887                }
13888            }
13889
13890            // Verify: if target already has an installer package, it must
13891            // be signed with the same cert as the caller.
13892            if (targetPackageSetting.installerPackageName != null) {
13893                PackageSetting setting = mSettings.mPackages.get(
13894                        targetPackageSetting.installerPackageName);
13895                // If the currently set package isn't valid, then it's always
13896                // okay to change it.
13897                if (setting != null) {
13898                    if (compareSignatures(callerSignature,
13899                            setting.signatures.mSignatures)
13900                            != PackageManager.SIGNATURE_MATCH) {
13901                        throw new SecurityException(
13902                                "Caller does not have same cert as old installer package "
13903                                + targetPackageSetting.installerPackageName);
13904                    }
13905                }
13906            }
13907
13908            // Okay!
13909            targetPackageSetting.installerPackageName = installerPackageName;
13910            if (installerPackageName != null) {
13911                mSettings.mInstallerPackages.add(installerPackageName);
13912            }
13913            scheduleWriteSettingsLocked();
13914        }
13915    }
13916
13917    @Override
13918    public void setApplicationCategoryHint(String packageName, int categoryHint,
13919            String callerPackageName) {
13920        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13921                callerPackageName);
13922        synchronized (mPackages) {
13923            PackageSetting ps = mSettings.mPackages.get(packageName);
13924            if (ps == null) {
13925                throw new IllegalArgumentException("Unknown target package " + packageName);
13926            }
13927
13928            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13929                throw new IllegalArgumentException("Calling package " + callerPackageName
13930                        + " is not installer for " + packageName);
13931            }
13932
13933            if (ps.categoryHint != categoryHint) {
13934                ps.categoryHint = categoryHint;
13935                scheduleWriteSettingsLocked();
13936            }
13937        }
13938    }
13939
13940    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13941        // Queue up an async operation since the package installation may take a little while.
13942        mHandler.post(new Runnable() {
13943            public void run() {
13944                mHandler.removeCallbacks(this);
13945                 // Result object to be returned
13946                PackageInstalledInfo res = new PackageInstalledInfo();
13947                res.setReturnCode(currentStatus);
13948                res.uid = -1;
13949                res.pkg = null;
13950                res.removedInfo = null;
13951                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13952                    args.doPreInstall(res.returnCode);
13953                    synchronized (mInstallLock) {
13954                        installPackageTracedLI(args, res);
13955                    }
13956                    args.doPostInstall(res.returnCode, res.uid);
13957                }
13958
13959                // A restore should be performed at this point if (a) the install
13960                // succeeded, (b) the operation is not an update, and (c) the new
13961                // package has not opted out of backup participation.
13962                final boolean update = res.removedInfo != null
13963                        && res.removedInfo.removedPackage != null;
13964                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13965                boolean doRestore = !update
13966                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13967
13968                // Set up the post-install work request bookkeeping.  This will be used
13969                // and cleaned up by the post-install event handling regardless of whether
13970                // there's a restore pass performed.  Token values are >= 1.
13971                int token;
13972                if (mNextInstallToken < 0) mNextInstallToken = 1;
13973                token = mNextInstallToken++;
13974
13975                PostInstallData data = new PostInstallData(args, res);
13976                mRunningInstalls.put(token, data);
13977                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13978
13979                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13980                    // Pass responsibility to the Backup Manager.  It will perform a
13981                    // restore if appropriate, then pass responsibility back to the
13982                    // Package Manager to run the post-install observer callbacks
13983                    // and broadcasts.
13984                    IBackupManager bm = IBackupManager.Stub.asInterface(
13985                            ServiceManager.getService(Context.BACKUP_SERVICE));
13986                    if (bm != null) {
13987                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13988                                + " to BM for possible restore");
13989                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13990                        try {
13991                            // TODO: http://b/22388012
13992                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13993                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13994                            } else {
13995                                doRestore = false;
13996                            }
13997                        } catch (RemoteException e) {
13998                            // can't happen; the backup manager is local
13999                        } catch (Exception e) {
14000                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14001                            doRestore = false;
14002                        }
14003                    } else {
14004                        Slog.e(TAG, "Backup Manager not found!");
14005                        doRestore = false;
14006                    }
14007                }
14008
14009                if (!doRestore) {
14010                    // No restore possible, or the Backup Manager was mysteriously not
14011                    // available -- just fire the post-install work request directly.
14012                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14013
14014                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14015
14016                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14017                    mHandler.sendMessage(msg);
14018                }
14019            }
14020        });
14021    }
14022
14023    /**
14024     * Callback from PackageSettings whenever an app is first transitioned out of the
14025     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14026     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14027     * here whether the app is the target of an ongoing install, and only send the
14028     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14029     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14030     * handling.
14031     */
14032    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14033        // Serialize this with the rest of the install-process message chain.  In the
14034        // restore-at-install case, this Runnable will necessarily run before the
14035        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14036        // are coherent.  In the non-restore case, the app has already completed install
14037        // and been launched through some other means, so it is not in a problematic
14038        // state for observers to see the FIRST_LAUNCH signal.
14039        mHandler.post(new Runnable() {
14040            @Override
14041            public void run() {
14042                for (int i = 0; i < mRunningInstalls.size(); i++) {
14043                    final PostInstallData data = mRunningInstalls.valueAt(i);
14044                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14045                        continue;
14046                    }
14047                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14048                        // right package; but is it for the right user?
14049                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14050                            if (userId == data.res.newUsers[uIndex]) {
14051                                if (DEBUG_BACKUP) {
14052                                    Slog.i(TAG, "Package " + pkgName
14053                                            + " being restored so deferring FIRST_LAUNCH");
14054                                }
14055                                return;
14056                            }
14057                        }
14058                    }
14059                }
14060                // didn't find it, so not being restored
14061                if (DEBUG_BACKUP) {
14062                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14063                }
14064                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14065            }
14066        });
14067    }
14068
14069    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14070        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14071                installerPkg, null, userIds);
14072    }
14073
14074    private abstract class HandlerParams {
14075        private static final int MAX_RETRIES = 4;
14076
14077        /**
14078         * Number of times startCopy() has been attempted and had a non-fatal
14079         * error.
14080         */
14081        private int mRetries = 0;
14082
14083        /** User handle for the user requesting the information or installation. */
14084        private final UserHandle mUser;
14085        String traceMethod;
14086        int traceCookie;
14087
14088        HandlerParams(UserHandle user) {
14089            mUser = user;
14090        }
14091
14092        UserHandle getUser() {
14093            return mUser;
14094        }
14095
14096        HandlerParams setTraceMethod(String traceMethod) {
14097            this.traceMethod = traceMethod;
14098            return this;
14099        }
14100
14101        HandlerParams setTraceCookie(int traceCookie) {
14102            this.traceCookie = traceCookie;
14103            return this;
14104        }
14105
14106        final boolean startCopy() {
14107            boolean res;
14108            try {
14109                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14110
14111                if (++mRetries > MAX_RETRIES) {
14112                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14113                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14114                    handleServiceError();
14115                    return false;
14116                } else {
14117                    handleStartCopy();
14118                    res = true;
14119                }
14120            } catch (RemoteException e) {
14121                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14122                mHandler.sendEmptyMessage(MCS_RECONNECT);
14123                res = false;
14124            }
14125            handleReturnCode();
14126            return res;
14127        }
14128
14129        final void serviceError() {
14130            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14131            handleServiceError();
14132            handleReturnCode();
14133        }
14134
14135        abstract void handleStartCopy() throws RemoteException;
14136        abstract void handleServiceError();
14137        abstract void handleReturnCode();
14138    }
14139
14140    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14141        for (File path : paths) {
14142            try {
14143                mcs.clearDirectory(path.getAbsolutePath());
14144            } catch (RemoteException e) {
14145            }
14146        }
14147    }
14148
14149    static class OriginInfo {
14150        /**
14151         * Location where install is coming from, before it has been
14152         * copied/renamed into place. This could be a single monolithic APK
14153         * file, or a cluster directory. This location may be untrusted.
14154         */
14155        final File file;
14156        final String cid;
14157
14158        /**
14159         * Flag indicating that {@link #file} or {@link #cid} has already been
14160         * staged, meaning downstream users don't need to defensively copy the
14161         * contents.
14162         */
14163        final boolean staged;
14164
14165        /**
14166         * Flag indicating that {@link #file} or {@link #cid} is an already
14167         * installed app that is being moved.
14168         */
14169        final boolean existing;
14170
14171        final String resolvedPath;
14172        final File resolvedFile;
14173
14174        static OriginInfo fromNothing() {
14175            return new OriginInfo(null, null, false, false);
14176        }
14177
14178        static OriginInfo fromUntrustedFile(File file) {
14179            return new OriginInfo(file, null, false, false);
14180        }
14181
14182        static OriginInfo fromExistingFile(File file) {
14183            return new OriginInfo(file, null, false, true);
14184        }
14185
14186        static OriginInfo fromStagedFile(File file) {
14187            return new OriginInfo(file, null, true, false);
14188        }
14189
14190        static OriginInfo fromStagedContainer(String cid) {
14191            return new OriginInfo(null, cid, true, false);
14192        }
14193
14194        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14195            this.file = file;
14196            this.cid = cid;
14197            this.staged = staged;
14198            this.existing = existing;
14199
14200            if (cid != null) {
14201                resolvedPath = PackageHelper.getSdDir(cid);
14202                resolvedFile = new File(resolvedPath);
14203            } else if (file != null) {
14204                resolvedPath = file.getAbsolutePath();
14205                resolvedFile = file;
14206            } else {
14207                resolvedPath = null;
14208                resolvedFile = null;
14209            }
14210        }
14211    }
14212
14213    static class MoveInfo {
14214        final int moveId;
14215        final String fromUuid;
14216        final String toUuid;
14217        final String packageName;
14218        final String dataAppName;
14219        final int appId;
14220        final String seinfo;
14221        final int targetSdkVersion;
14222
14223        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14224                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14225            this.moveId = moveId;
14226            this.fromUuid = fromUuid;
14227            this.toUuid = toUuid;
14228            this.packageName = packageName;
14229            this.dataAppName = dataAppName;
14230            this.appId = appId;
14231            this.seinfo = seinfo;
14232            this.targetSdkVersion = targetSdkVersion;
14233        }
14234    }
14235
14236    static class VerificationInfo {
14237        /** A constant used to indicate that a uid value is not present. */
14238        public static final int NO_UID = -1;
14239
14240        /** URI referencing where the package was downloaded from. */
14241        final Uri originatingUri;
14242
14243        /** HTTP referrer URI associated with the originatingURI. */
14244        final Uri referrer;
14245
14246        /** UID of the application that the install request originated from. */
14247        final int originatingUid;
14248
14249        /** UID of application requesting the install */
14250        final int installerUid;
14251
14252        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14253            this.originatingUri = originatingUri;
14254            this.referrer = referrer;
14255            this.originatingUid = originatingUid;
14256            this.installerUid = installerUid;
14257        }
14258    }
14259
14260    class InstallParams extends HandlerParams {
14261        final OriginInfo origin;
14262        final MoveInfo move;
14263        final IPackageInstallObserver2 observer;
14264        int installFlags;
14265        final String installerPackageName;
14266        final String volumeUuid;
14267        private InstallArgs mArgs;
14268        private int mRet;
14269        final String packageAbiOverride;
14270        final String[] grantedRuntimePermissions;
14271        final VerificationInfo verificationInfo;
14272        final Certificate[][] certificates;
14273        final int installReason;
14274
14275        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14276                int installFlags, String installerPackageName, String volumeUuid,
14277                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14278                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14279            super(user);
14280            this.origin = origin;
14281            this.move = move;
14282            this.observer = observer;
14283            this.installFlags = installFlags;
14284            this.installerPackageName = installerPackageName;
14285            this.volumeUuid = volumeUuid;
14286            this.verificationInfo = verificationInfo;
14287            this.packageAbiOverride = packageAbiOverride;
14288            this.grantedRuntimePermissions = grantedPermissions;
14289            this.certificates = certificates;
14290            this.installReason = installReason;
14291        }
14292
14293        @Override
14294        public String toString() {
14295            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14296                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14297        }
14298
14299        private int installLocationPolicy(PackageInfoLite pkgLite) {
14300            String packageName = pkgLite.packageName;
14301            int installLocation = pkgLite.installLocation;
14302            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14303            // reader
14304            synchronized (mPackages) {
14305                // Currently installed package which the new package is attempting to replace or
14306                // null if no such package is installed.
14307                PackageParser.Package installedPkg = mPackages.get(packageName);
14308                // Package which currently owns the data which the new package will own if installed.
14309                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14310                // will be null whereas dataOwnerPkg will contain information about the package
14311                // which was uninstalled while keeping its data.
14312                PackageParser.Package dataOwnerPkg = installedPkg;
14313                if (dataOwnerPkg  == null) {
14314                    PackageSetting ps = mSettings.mPackages.get(packageName);
14315                    if (ps != null) {
14316                        dataOwnerPkg = ps.pkg;
14317                    }
14318                }
14319
14320                if (dataOwnerPkg != null) {
14321                    // If installed, the package will get access to data left on the device by its
14322                    // predecessor. As a security measure, this is permited only if this is not a
14323                    // version downgrade or if the predecessor package is marked as debuggable and
14324                    // a downgrade is explicitly requested.
14325                    //
14326                    // On debuggable platform builds, downgrades are permitted even for
14327                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14328                    // not offer security guarantees and thus it's OK to disable some security
14329                    // mechanisms to make debugging/testing easier on those builds. However, even on
14330                    // debuggable builds downgrades of packages are permitted only if requested via
14331                    // installFlags. This is because we aim to keep the behavior of debuggable
14332                    // platform builds as close as possible to the behavior of non-debuggable
14333                    // platform builds.
14334                    final boolean downgradeRequested =
14335                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14336                    final boolean packageDebuggable =
14337                                (dataOwnerPkg.applicationInfo.flags
14338                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14339                    final boolean downgradePermitted =
14340                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14341                    if (!downgradePermitted) {
14342                        try {
14343                            checkDowngrade(dataOwnerPkg, pkgLite);
14344                        } catch (PackageManagerException e) {
14345                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14346                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14347                        }
14348                    }
14349                }
14350
14351                if (installedPkg != null) {
14352                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14353                        // Check for updated system application.
14354                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14355                            if (onSd) {
14356                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14357                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14358                            }
14359                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14360                        } else {
14361                            if (onSd) {
14362                                // Install flag overrides everything.
14363                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14364                            }
14365                            // If current upgrade specifies particular preference
14366                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14367                                // Application explicitly specified internal.
14368                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14369                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14370                                // App explictly prefers external. Let policy decide
14371                            } else {
14372                                // Prefer previous location
14373                                if (isExternal(installedPkg)) {
14374                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14375                                }
14376                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14377                            }
14378                        }
14379                    } else {
14380                        // Invalid install. Return error code
14381                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14382                    }
14383                }
14384            }
14385            // All the special cases have been taken care of.
14386            // Return result based on recommended install location.
14387            if (onSd) {
14388                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14389            }
14390            return pkgLite.recommendedInstallLocation;
14391        }
14392
14393        /*
14394         * Invoke remote method to get package information and install
14395         * location values. Override install location based on default
14396         * policy if needed and then create install arguments based
14397         * on the install location.
14398         */
14399        public void handleStartCopy() throws RemoteException {
14400            int ret = PackageManager.INSTALL_SUCCEEDED;
14401
14402            // If we're already staged, we've firmly committed to an install location
14403            if (origin.staged) {
14404                if (origin.file != null) {
14405                    installFlags |= PackageManager.INSTALL_INTERNAL;
14406                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14407                } else if (origin.cid != null) {
14408                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14409                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14410                } else {
14411                    throw new IllegalStateException("Invalid stage location");
14412                }
14413            }
14414
14415            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14416            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14417            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14418            PackageInfoLite pkgLite = null;
14419
14420            if (onInt && onSd) {
14421                // Check if both bits are set.
14422                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14423                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14424            } else if (onSd && ephemeral) {
14425                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14426                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14427            } else {
14428                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14429                        packageAbiOverride);
14430
14431                if (DEBUG_EPHEMERAL && ephemeral) {
14432                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14433                }
14434
14435                /*
14436                 * If we have too little free space, try to free cache
14437                 * before giving up.
14438                 */
14439                if (!origin.staged && pkgLite.recommendedInstallLocation
14440                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14441                    // TODO: focus freeing disk space on the target device
14442                    final StorageManager storage = StorageManager.from(mContext);
14443                    final long lowThreshold = storage.getStorageLowBytes(
14444                            Environment.getDataDirectory());
14445
14446                    final long sizeBytes = mContainerService.calculateInstalledSize(
14447                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14448
14449                    try {
14450                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14451                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14452                                installFlags, packageAbiOverride);
14453                    } catch (InstallerException e) {
14454                        Slog.w(TAG, "Failed to free cache", e);
14455                    }
14456
14457                    /*
14458                     * The cache free must have deleted the file we
14459                     * downloaded to install.
14460                     *
14461                     * TODO: fix the "freeCache" call to not delete
14462                     *       the file we care about.
14463                     */
14464                    if (pkgLite.recommendedInstallLocation
14465                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14466                        pkgLite.recommendedInstallLocation
14467                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14468                    }
14469                }
14470            }
14471
14472            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14473                int loc = pkgLite.recommendedInstallLocation;
14474                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14475                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14476                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14477                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14478                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14479                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14480                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14481                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14482                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14483                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14484                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14485                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14486                } else {
14487                    // Override with defaults if needed.
14488                    loc = installLocationPolicy(pkgLite);
14489                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14490                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14491                    } else if (!onSd && !onInt) {
14492                        // Override install location with flags
14493                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14494                            // Set the flag to install on external media.
14495                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14496                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14497                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14498                            if (DEBUG_EPHEMERAL) {
14499                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14500                            }
14501                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14502                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14503                                    |PackageManager.INSTALL_INTERNAL);
14504                        } else {
14505                            // Make sure the flag for installing on external
14506                            // media is unset
14507                            installFlags |= PackageManager.INSTALL_INTERNAL;
14508                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14509                        }
14510                    }
14511                }
14512            }
14513
14514            final InstallArgs args = createInstallArgs(this);
14515            mArgs = args;
14516
14517            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14518                // TODO: http://b/22976637
14519                // Apps installed for "all" users use the device owner to verify the app
14520                UserHandle verifierUser = getUser();
14521                if (verifierUser == UserHandle.ALL) {
14522                    verifierUser = UserHandle.SYSTEM;
14523                }
14524
14525                /*
14526                 * Determine if we have any installed package verifiers. If we
14527                 * do, then we'll defer to them to verify the packages.
14528                 */
14529                final int requiredUid = mRequiredVerifierPackage == null ? -1
14530                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14531                                verifierUser.getIdentifier());
14532                if (!origin.existing && requiredUid != -1
14533                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14534                    final Intent verification = new Intent(
14535                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14536                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14537                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14538                            PACKAGE_MIME_TYPE);
14539                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14540
14541                    // Query all live verifiers based on current user state
14542                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14543                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14544
14545                    if (DEBUG_VERIFY) {
14546                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14547                                + verification.toString() + " with " + pkgLite.verifiers.length
14548                                + " optional verifiers");
14549                    }
14550
14551                    final int verificationId = mPendingVerificationToken++;
14552
14553                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14554
14555                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14556                            installerPackageName);
14557
14558                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14559                            installFlags);
14560
14561                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14562                            pkgLite.packageName);
14563
14564                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14565                            pkgLite.versionCode);
14566
14567                    if (verificationInfo != null) {
14568                        if (verificationInfo.originatingUri != null) {
14569                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14570                                    verificationInfo.originatingUri);
14571                        }
14572                        if (verificationInfo.referrer != null) {
14573                            verification.putExtra(Intent.EXTRA_REFERRER,
14574                                    verificationInfo.referrer);
14575                        }
14576                        if (verificationInfo.originatingUid >= 0) {
14577                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14578                                    verificationInfo.originatingUid);
14579                        }
14580                        if (verificationInfo.installerUid >= 0) {
14581                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14582                                    verificationInfo.installerUid);
14583                        }
14584                    }
14585
14586                    final PackageVerificationState verificationState = new PackageVerificationState(
14587                            requiredUid, args);
14588
14589                    mPendingVerification.append(verificationId, verificationState);
14590
14591                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14592                            receivers, verificationState);
14593
14594                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14595                    final long idleDuration = getVerificationTimeout();
14596
14597                    /*
14598                     * If any sufficient verifiers were listed in the package
14599                     * manifest, attempt to ask them.
14600                     */
14601                    if (sufficientVerifiers != null) {
14602                        final int N = sufficientVerifiers.size();
14603                        if (N == 0) {
14604                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14605                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14606                        } else {
14607                            for (int i = 0; i < N; i++) {
14608                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14609                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14610                                        verifierComponent.getPackageName(), idleDuration,
14611                                        verifierUser.getIdentifier(), false, "package verifier");
14612
14613                                final Intent sufficientIntent = new Intent(verification);
14614                                sufficientIntent.setComponent(verifierComponent);
14615                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14616                            }
14617                        }
14618                    }
14619
14620                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14621                            mRequiredVerifierPackage, receivers);
14622                    if (ret == PackageManager.INSTALL_SUCCEEDED
14623                            && mRequiredVerifierPackage != null) {
14624                        Trace.asyncTraceBegin(
14625                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14626                        /*
14627                         * Send the intent to the required verification agent,
14628                         * but only start the verification timeout after the
14629                         * target BroadcastReceivers have run.
14630                         */
14631                        verification.setComponent(requiredVerifierComponent);
14632                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14633                                mRequiredVerifierPackage, idleDuration,
14634                                verifierUser.getIdentifier(), false, "package verifier");
14635                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14636                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14637                                new BroadcastReceiver() {
14638                                    @Override
14639                                    public void onReceive(Context context, Intent intent) {
14640                                        final Message msg = mHandler
14641                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14642                                        msg.arg1 = verificationId;
14643                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14644                                    }
14645                                }, null, 0, null, null);
14646
14647                        /*
14648                         * We don't want the copy to proceed until verification
14649                         * succeeds, so null out this field.
14650                         */
14651                        mArgs = null;
14652                    }
14653                } else {
14654                    /*
14655                     * No package verification is enabled, so immediately start
14656                     * the remote call to initiate copy using temporary file.
14657                     */
14658                    ret = args.copyApk(mContainerService, true);
14659                }
14660            }
14661
14662            mRet = ret;
14663        }
14664
14665        @Override
14666        void handleReturnCode() {
14667            // If mArgs is null, then MCS couldn't be reached. When it
14668            // reconnects, it will try again to install. At that point, this
14669            // will succeed.
14670            if (mArgs != null) {
14671                processPendingInstall(mArgs, mRet);
14672            }
14673        }
14674
14675        @Override
14676        void handleServiceError() {
14677            mArgs = createInstallArgs(this);
14678            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14679        }
14680
14681        public boolean isForwardLocked() {
14682            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14683        }
14684    }
14685
14686    /**
14687     * Used during creation of InstallArgs
14688     *
14689     * @param installFlags package installation flags
14690     * @return true if should be installed on external storage
14691     */
14692    private static boolean installOnExternalAsec(int installFlags) {
14693        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14694            return false;
14695        }
14696        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14697            return true;
14698        }
14699        return false;
14700    }
14701
14702    /**
14703     * Used during creation of InstallArgs
14704     *
14705     * @param installFlags package installation flags
14706     * @return true if should be installed as forward locked
14707     */
14708    private static boolean installForwardLocked(int installFlags) {
14709        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14710    }
14711
14712    private InstallArgs createInstallArgs(InstallParams params) {
14713        if (params.move != null) {
14714            return new MoveInstallArgs(params);
14715        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14716            return new AsecInstallArgs(params);
14717        } else {
14718            return new FileInstallArgs(params);
14719        }
14720    }
14721
14722    /**
14723     * Create args that describe an existing installed package. Typically used
14724     * when cleaning up old installs, or used as a move source.
14725     */
14726    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14727            String resourcePath, String[] instructionSets) {
14728        final boolean isInAsec;
14729        if (installOnExternalAsec(installFlags)) {
14730            /* Apps on SD card are always in ASEC containers. */
14731            isInAsec = true;
14732        } else if (installForwardLocked(installFlags)
14733                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14734            /*
14735             * Forward-locked apps are only in ASEC containers if they're the
14736             * new style
14737             */
14738            isInAsec = true;
14739        } else {
14740            isInAsec = false;
14741        }
14742
14743        if (isInAsec) {
14744            return new AsecInstallArgs(codePath, instructionSets,
14745                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14746        } else {
14747            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14748        }
14749    }
14750
14751    static abstract class InstallArgs {
14752        /** @see InstallParams#origin */
14753        final OriginInfo origin;
14754        /** @see InstallParams#move */
14755        final MoveInfo move;
14756
14757        final IPackageInstallObserver2 observer;
14758        // Always refers to PackageManager flags only
14759        final int installFlags;
14760        final String installerPackageName;
14761        final String volumeUuid;
14762        final UserHandle user;
14763        final String abiOverride;
14764        final String[] installGrantPermissions;
14765        /** If non-null, drop an async trace when the install completes */
14766        final String traceMethod;
14767        final int traceCookie;
14768        final Certificate[][] certificates;
14769        final int installReason;
14770
14771        // The list of instruction sets supported by this app. This is currently
14772        // only used during the rmdex() phase to clean up resources. We can get rid of this
14773        // if we move dex files under the common app path.
14774        /* nullable */ String[] instructionSets;
14775
14776        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14777                int installFlags, String installerPackageName, String volumeUuid,
14778                UserHandle user, String[] instructionSets,
14779                String abiOverride, String[] installGrantPermissions,
14780                String traceMethod, int traceCookie, Certificate[][] certificates,
14781                int installReason) {
14782            this.origin = origin;
14783            this.move = move;
14784            this.installFlags = installFlags;
14785            this.observer = observer;
14786            this.installerPackageName = installerPackageName;
14787            this.volumeUuid = volumeUuid;
14788            this.user = user;
14789            this.instructionSets = instructionSets;
14790            this.abiOverride = abiOverride;
14791            this.installGrantPermissions = installGrantPermissions;
14792            this.traceMethod = traceMethod;
14793            this.traceCookie = traceCookie;
14794            this.certificates = certificates;
14795            this.installReason = installReason;
14796        }
14797
14798        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14799        abstract int doPreInstall(int status);
14800
14801        /**
14802         * Rename package into final resting place. All paths on the given
14803         * scanned package should be updated to reflect the rename.
14804         */
14805        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14806        abstract int doPostInstall(int status, int uid);
14807
14808        /** @see PackageSettingBase#codePathString */
14809        abstract String getCodePath();
14810        /** @see PackageSettingBase#resourcePathString */
14811        abstract String getResourcePath();
14812
14813        // Need installer lock especially for dex file removal.
14814        abstract void cleanUpResourcesLI();
14815        abstract boolean doPostDeleteLI(boolean delete);
14816
14817        /**
14818         * Called before the source arguments are copied. This is used mostly
14819         * for MoveParams when it needs to read the source file to put it in the
14820         * destination.
14821         */
14822        int doPreCopy() {
14823            return PackageManager.INSTALL_SUCCEEDED;
14824        }
14825
14826        /**
14827         * Called after the source arguments are copied. This is used mostly for
14828         * MoveParams when it needs to read the source file to put it in the
14829         * destination.
14830         */
14831        int doPostCopy(int uid) {
14832            return PackageManager.INSTALL_SUCCEEDED;
14833        }
14834
14835        protected boolean isFwdLocked() {
14836            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14837        }
14838
14839        protected boolean isExternalAsec() {
14840            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14841        }
14842
14843        protected boolean isEphemeral() {
14844            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14845        }
14846
14847        UserHandle getUser() {
14848            return user;
14849        }
14850    }
14851
14852    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14853        if (!allCodePaths.isEmpty()) {
14854            if (instructionSets == null) {
14855                throw new IllegalStateException("instructionSet == null");
14856            }
14857            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14858            for (String codePath : allCodePaths) {
14859                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14860                    try {
14861                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14862                    } catch (InstallerException ignored) {
14863                    }
14864                }
14865            }
14866        }
14867    }
14868
14869    /**
14870     * Logic to handle installation of non-ASEC applications, including copying
14871     * and renaming logic.
14872     */
14873    class FileInstallArgs extends InstallArgs {
14874        private File codeFile;
14875        private File resourceFile;
14876
14877        // Example topology:
14878        // /data/app/com.example/base.apk
14879        // /data/app/com.example/split_foo.apk
14880        // /data/app/com.example/lib/arm/libfoo.so
14881        // /data/app/com.example/lib/arm64/libfoo.so
14882        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14883
14884        /** New install */
14885        FileInstallArgs(InstallParams params) {
14886            super(params.origin, params.move, params.observer, params.installFlags,
14887                    params.installerPackageName, params.volumeUuid,
14888                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14889                    params.grantedRuntimePermissions,
14890                    params.traceMethod, params.traceCookie, params.certificates,
14891                    params.installReason);
14892            if (isFwdLocked()) {
14893                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14894            }
14895        }
14896
14897        /** Existing install */
14898        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14899            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14900                    null, null, null, 0, null /*certificates*/,
14901                    PackageManager.INSTALL_REASON_UNKNOWN);
14902            this.codeFile = (codePath != null) ? new File(codePath) : null;
14903            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14904        }
14905
14906        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14907            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14908            try {
14909                return doCopyApk(imcs, temp);
14910            } finally {
14911                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14912            }
14913        }
14914
14915        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14916            if (origin.staged) {
14917                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14918                codeFile = origin.file;
14919                resourceFile = origin.file;
14920                return PackageManager.INSTALL_SUCCEEDED;
14921            }
14922
14923            try {
14924                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14925                final File tempDir =
14926                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14927                codeFile = tempDir;
14928                resourceFile = tempDir;
14929            } catch (IOException e) {
14930                Slog.w(TAG, "Failed to create copy file: " + e);
14931                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14932            }
14933
14934            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14935                @Override
14936                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14937                    if (!FileUtils.isValidExtFilename(name)) {
14938                        throw new IllegalArgumentException("Invalid filename: " + name);
14939                    }
14940                    try {
14941                        final File file = new File(codeFile, name);
14942                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14943                                O_RDWR | O_CREAT, 0644);
14944                        Os.chmod(file.getAbsolutePath(), 0644);
14945                        return new ParcelFileDescriptor(fd);
14946                    } catch (ErrnoException e) {
14947                        throw new RemoteException("Failed to open: " + e.getMessage());
14948                    }
14949                }
14950            };
14951
14952            int ret = PackageManager.INSTALL_SUCCEEDED;
14953            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14954            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14955                Slog.e(TAG, "Failed to copy package");
14956                return ret;
14957            }
14958
14959            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14960            NativeLibraryHelper.Handle handle = null;
14961            try {
14962                handle = NativeLibraryHelper.Handle.create(codeFile);
14963                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14964                        abiOverride);
14965            } catch (IOException e) {
14966                Slog.e(TAG, "Copying native libraries failed", e);
14967                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14968            } finally {
14969                IoUtils.closeQuietly(handle);
14970            }
14971
14972            return ret;
14973        }
14974
14975        int doPreInstall(int status) {
14976            if (status != PackageManager.INSTALL_SUCCEEDED) {
14977                cleanUp();
14978            }
14979            return status;
14980        }
14981
14982        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14983            if (status != PackageManager.INSTALL_SUCCEEDED) {
14984                cleanUp();
14985                return false;
14986            }
14987
14988            final File targetDir = codeFile.getParentFile();
14989            final File beforeCodeFile = codeFile;
14990            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14991
14992            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14993            try {
14994                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14995            } catch (ErrnoException e) {
14996                Slog.w(TAG, "Failed to rename", e);
14997                return false;
14998            }
14999
15000            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15001                Slog.w(TAG, "Failed to restorecon");
15002                return false;
15003            }
15004
15005            // Reflect the rename internally
15006            codeFile = afterCodeFile;
15007            resourceFile = afterCodeFile;
15008
15009            // Reflect the rename in scanned details
15010            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15011            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15012                    afterCodeFile, pkg.baseCodePath));
15013            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15014                    afterCodeFile, pkg.splitCodePaths));
15015
15016            // Reflect the rename in app info
15017            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15018            pkg.setApplicationInfoCodePath(pkg.codePath);
15019            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15020            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15021            pkg.setApplicationInfoResourcePath(pkg.codePath);
15022            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15023            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15024
15025            return true;
15026        }
15027
15028        int doPostInstall(int status, int uid) {
15029            if (status != PackageManager.INSTALL_SUCCEEDED) {
15030                cleanUp();
15031            }
15032            return status;
15033        }
15034
15035        @Override
15036        String getCodePath() {
15037            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15038        }
15039
15040        @Override
15041        String getResourcePath() {
15042            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15043        }
15044
15045        private boolean cleanUp() {
15046            if (codeFile == null || !codeFile.exists()) {
15047                return false;
15048            }
15049
15050            removeCodePathLI(codeFile);
15051
15052            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15053                resourceFile.delete();
15054            }
15055
15056            return true;
15057        }
15058
15059        void cleanUpResourcesLI() {
15060            // Try enumerating all code paths before deleting
15061            List<String> allCodePaths = Collections.EMPTY_LIST;
15062            if (codeFile != null && codeFile.exists()) {
15063                try {
15064                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15065                    allCodePaths = pkg.getAllCodePaths();
15066                } catch (PackageParserException e) {
15067                    // Ignored; we tried our best
15068                }
15069            }
15070
15071            cleanUp();
15072            removeDexFiles(allCodePaths, instructionSets);
15073        }
15074
15075        boolean doPostDeleteLI(boolean delete) {
15076            // XXX err, shouldn't we respect the delete flag?
15077            cleanUpResourcesLI();
15078            return true;
15079        }
15080    }
15081
15082    private boolean isAsecExternal(String cid) {
15083        final String asecPath = PackageHelper.getSdFilesystem(cid);
15084        return !asecPath.startsWith(mAsecInternalPath);
15085    }
15086
15087    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15088            PackageManagerException {
15089        if (copyRet < 0) {
15090            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15091                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15092                throw new PackageManagerException(copyRet, message);
15093            }
15094        }
15095    }
15096
15097    /**
15098     * Extract the StorageManagerService "container ID" from the full code path of an
15099     * .apk.
15100     */
15101    static String cidFromCodePath(String fullCodePath) {
15102        int eidx = fullCodePath.lastIndexOf("/");
15103        String subStr1 = fullCodePath.substring(0, eidx);
15104        int sidx = subStr1.lastIndexOf("/");
15105        return subStr1.substring(sidx+1, eidx);
15106    }
15107
15108    /**
15109     * Logic to handle installation of ASEC applications, including copying and
15110     * renaming logic.
15111     */
15112    class AsecInstallArgs extends InstallArgs {
15113        static final String RES_FILE_NAME = "pkg.apk";
15114        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15115
15116        String cid;
15117        String packagePath;
15118        String resourcePath;
15119
15120        /** New install */
15121        AsecInstallArgs(InstallParams params) {
15122            super(params.origin, params.move, params.observer, params.installFlags,
15123                    params.installerPackageName, params.volumeUuid,
15124                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15125                    params.grantedRuntimePermissions,
15126                    params.traceMethod, params.traceCookie, params.certificates,
15127                    params.installReason);
15128        }
15129
15130        /** Existing install */
15131        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15132                        boolean isExternal, boolean isForwardLocked) {
15133            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15134                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15135                    instructionSets, null, null, null, 0, null /*certificates*/,
15136                    PackageManager.INSTALL_REASON_UNKNOWN);
15137            // Hackily pretend we're still looking at a full code path
15138            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15139                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15140            }
15141
15142            // Extract cid from fullCodePath
15143            int eidx = fullCodePath.lastIndexOf("/");
15144            String subStr1 = fullCodePath.substring(0, eidx);
15145            int sidx = subStr1.lastIndexOf("/");
15146            cid = subStr1.substring(sidx+1, eidx);
15147            setMountPath(subStr1);
15148        }
15149
15150        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15151            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15152                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15153                    instructionSets, null, null, null, 0, null /*certificates*/,
15154                    PackageManager.INSTALL_REASON_UNKNOWN);
15155            this.cid = cid;
15156            setMountPath(PackageHelper.getSdDir(cid));
15157        }
15158
15159        void createCopyFile() {
15160            cid = mInstallerService.allocateExternalStageCidLegacy();
15161        }
15162
15163        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15164            if (origin.staged && origin.cid != null) {
15165                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15166                cid = origin.cid;
15167                setMountPath(PackageHelper.getSdDir(cid));
15168                return PackageManager.INSTALL_SUCCEEDED;
15169            }
15170
15171            if (temp) {
15172                createCopyFile();
15173            } else {
15174                /*
15175                 * Pre-emptively destroy the container since it's destroyed if
15176                 * copying fails due to it existing anyway.
15177                 */
15178                PackageHelper.destroySdDir(cid);
15179            }
15180
15181            final String newMountPath = imcs.copyPackageToContainer(
15182                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15183                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15184
15185            if (newMountPath != null) {
15186                setMountPath(newMountPath);
15187                return PackageManager.INSTALL_SUCCEEDED;
15188            } else {
15189                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15190            }
15191        }
15192
15193        @Override
15194        String getCodePath() {
15195            return packagePath;
15196        }
15197
15198        @Override
15199        String getResourcePath() {
15200            return resourcePath;
15201        }
15202
15203        int doPreInstall(int status) {
15204            if (status != PackageManager.INSTALL_SUCCEEDED) {
15205                // Destroy container
15206                PackageHelper.destroySdDir(cid);
15207            } else {
15208                boolean mounted = PackageHelper.isContainerMounted(cid);
15209                if (!mounted) {
15210                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15211                            Process.SYSTEM_UID);
15212                    if (newMountPath != null) {
15213                        setMountPath(newMountPath);
15214                    } else {
15215                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15216                    }
15217                }
15218            }
15219            return status;
15220        }
15221
15222        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15223            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15224            String newMountPath = null;
15225            if (PackageHelper.isContainerMounted(cid)) {
15226                // Unmount the container
15227                if (!PackageHelper.unMountSdDir(cid)) {
15228                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15229                    return false;
15230                }
15231            }
15232            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15233                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15234                        " which might be stale. Will try to clean up.");
15235                // Clean up the stale container and proceed to recreate.
15236                if (!PackageHelper.destroySdDir(newCacheId)) {
15237                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15238                    return false;
15239                }
15240                // Successfully cleaned up stale container. Try to rename again.
15241                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15242                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15243                            + " inspite of cleaning it up.");
15244                    return false;
15245                }
15246            }
15247            if (!PackageHelper.isContainerMounted(newCacheId)) {
15248                Slog.w(TAG, "Mounting container " + newCacheId);
15249                newMountPath = PackageHelper.mountSdDir(newCacheId,
15250                        getEncryptKey(), Process.SYSTEM_UID);
15251            } else {
15252                newMountPath = PackageHelper.getSdDir(newCacheId);
15253            }
15254            if (newMountPath == null) {
15255                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15256                return false;
15257            }
15258            Log.i(TAG, "Succesfully renamed " + cid +
15259                    " to " + newCacheId +
15260                    " at new path: " + newMountPath);
15261            cid = newCacheId;
15262
15263            final File beforeCodeFile = new File(packagePath);
15264            setMountPath(newMountPath);
15265            final File afterCodeFile = new File(packagePath);
15266
15267            // Reflect the rename in scanned details
15268            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15269            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15270                    afterCodeFile, pkg.baseCodePath));
15271            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15272                    afterCodeFile, pkg.splitCodePaths));
15273
15274            // Reflect the rename in app info
15275            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15276            pkg.setApplicationInfoCodePath(pkg.codePath);
15277            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15278            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15279            pkg.setApplicationInfoResourcePath(pkg.codePath);
15280            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15281            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15282
15283            return true;
15284        }
15285
15286        private void setMountPath(String mountPath) {
15287            final File mountFile = new File(mountPath);
15288
15289            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15290            if (monolithicFile.exists()) {
15291                packagePath = monolithicFile.getAbsolutePath();
15292                if (isFwdLocked()) {
15293                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15294                } else {
15295                    resourcePath = packagePath;
15296                }
15297            } else {
15298                packagePath = mountFile.getAbsolutePath();
15299                resourcePath = packagePath;
15300            }
15301        }
15302
15303        int doPostInstall(int status, int uid) {
15304            if (status != PackageManager.INSTALL_SUCCEEDED) {
15305                cleanUp();
15306            } else {
15307                final int groupOwner;
15308                final String protectedFile;
15309                if (isFwdLocked()) {
15310                    groupOwner = UserHandle.getSharedAppGid(uid);
15311                    protectedFile = RES_FILE_NAME;
15312                } else {
15313                    groupOwner = -1;
15314                    protectedFile = null;
15315                }
15316
15317                if (uid < Process.FIRST_APPLICATION_UID
15318                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15319                    Slog.e(TAG, "Failed to finalize " + cid);
15320                    PackageHelper.destroySdDir(cid);
15321                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15322                }
15323
15324                boolean mounted = PackageHelper.isContainerMounted(cid);
15325                if (!mounted) {
15326                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15327                }
15328            }
15329            return status;
15330        }
15331
15332        private void cleanUp() {
15333            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15334
15335            // Destroy secure container
15336            PackageHelper.destroySdDir(cid);
15337        }
15338
15339        private List<String> getAllCodePaths() {
15340            final File codeFile = new File(getCodePath());
15341            if (codeFile != null && codeFile.exists()) {
15342                try {
15343                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15344                    return pkg.getAllCodePaths();
15345                } catch (PackageParserException e) {
15346                    // Ignored; we tried our best
15347                }
15348            }
15349            return Collections.EMPTY_LIST;
15350        }
15351
15352        void cleanUpResourcesLI() {
15353            // Enumerate all code paths before deleting
15354            cleanUpResourcesLI(getAllCodePaths());
15355        }
15356
15357        private void cleanUpResourcesLI(List<String> allCodePaths) {
15358            cleanUp();
15359            removeDexFiles(allCodePaths, instructionSets);
15360        }
15361
15362        String getPackageName() {
15363            return getAsecPackageName(cid);
15364        }
15365
15366        boolean doPostDeleteLI(boolean delete) {
15367            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15368            final List<String> allCodePaths = getAllCodePaths();
15369            boolean mounted = PackageHelper.isContainerMounted(cid);
15370            if (mounted) {
15371                // Unmount first
15372                if (PackageHelper.unMountSdDir(cid)) {
15373                    mounted = false;
15374                }
15375            }
15376            if (!mounted && delete) {
15377                cleanUpResourcesLI(allCodePaths);
15378            }
15379            return !mounted;
15380        }
15381
15382        @Override
15383        int doPreCopy() {
15384            if (isFwdLocked()) {
15385                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15386                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15387                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15388                }
15389            }
15390
15391            return PackageManager.INSTALL_SUCCEEDED;
15392        }
15393
15394        @Override
15395        int doPostCopy(int uid) {
15396            if (isFwdLocked()) {
15397                if (uid < Process.FIRST_APPLICATION_UID
15398                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15399                                RES_FILE_NAME)) {
15400                    Slog.e(TAG, "Failed to finalize " + cid);
15401                    PackageHelper.destroySdDir(cid);
15402                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15403                }
15404            }
15405
15406            return PackageManager.INSTALL_SUCCEEDED;
15407        }
15408    }
15409
15410    /**
15411     * Logic to handle movement of existing installed applications.
15412     */
15413    class MoveInstallArgs extends InstallArgs {
15414        private File codeFile;
15415        private File resourceFile;
15416
15417        /** New install */
15418        MoveInstallArgs(InstallParams params) {
15419            super(params.origin, params.move, params.observer, params.installFlags,
15420                    params.installerPackageName, params.volumeUuid,
15421                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15422                    params.grantedRuntimePermissions,
15423                    params.traceMethod, params.traceCookie, params.certificates,
15424                    params.installReason);
15425        }
15426
15427        int copyApk(IMediaContainerService imcs, boolean temp) {
15428            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15429                    + move.fromUuid + " to " + move.toUuid);
15430            synchronized (mInstaller) {
15431                try {
15432                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15433                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15434                } catch (InstallerException e) {
15435                    Slog.w(TAG, "Failed to move app", e);
15436                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15437                }
15438            }
15439
15440            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15441            resourceFile = codeFile;
15442            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15443
15444            return PackageManager.INSTALL_SUCCEEDED;
15445        }
15446
15447        int doPreInstall(int status) {
15448            if (status != PackageManager.INSTALL_SUCCEEDED) {
15449                cleanUp(move.toUuid);
15450            }
15451            return status;
15452        }
15453
15454        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15455            if (status != PackageManager.INSTALL_SUCCEEDED) {
15456                cleanUp(move.toUuid);
15457                return false;
15458            }
15459
15460            // Reflect the move in app info
15461            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15462            pkg.setApplicationInfoCodePath(pkg.codePath);
15463            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15464            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15465            pkg.setApplicationInfoResourcePath(pkg.codePath);
15466            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15467            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15468
15469            return true;
15470        }
15471
15472        int doPostInstall(int status, int uid) {
15473            if (status == PackageManager.INSTALL_SUCCEEDED) {
15474                cleanUp(move.fromUuid);
15475            } else {
15476                cleanUp(move.toUuid);
15477            }
15478            return status;
15479        }
15480
15481        @Override
15482        String getCodePath() {
15483            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15484        }
15485
15486        @Override
15487        String getResourcePath() {
15488            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15489        }
15490
15491        private boolean cleanUp(String volumeUuid) {
15492            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15493                    move.dataAppName);
15494            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15495            final int[] userIds = sUserManager.getUserIds();
15496            synchronized (mInstallLock) {
15497                // Clean up both app data and code
15498                // All package moves are frozen until finished
15499                for (int userId : userIds) {
15500                    try {
15501                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15502                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15503                    } catch (InstallerException e) {
15504                        Slog.w(TAG, String.valueOf(e));
15505                    }
15506                }
15507                removeCodePathLI(codeFile);
15508            }
15509            return true;
15510        }
15511
15512        void cleanUpResourcesLI() {
15513            throw new UnsupportedOperationException();
15514        }
15515
15516        boolean doPostDeleteLI(boolean delete) {
15517            throw new UnsupportedOperationException();
15518        }
15519    }
15520
15521    static String getAsecPackageName(String packageCid) {
15522        int idx = packageCid.lastIndexOf("-");
15523        if (idx == -1) {
15524            return packageCid;
15525        }
15526        return packageCid.substring(0, idx);
15527    }
15528
15529    // Utility method used to create code paths based on package name and available index.
15530    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15531        String idxStr = "";
15532        int idx = 1;
15533        // Fall back to default value of idx=1 if prefix is not
15534        // part of oldCodePath
15535        if (oldCodePath != null) {
15536            String subStr = oldCodePath;
15537            // Drop the suffix right away
15538            if (suffix != null && subStr.endsWith(suffix)) {
15539                subStr = subStr.substring(0, subStr.length() - suffix.length());
15540            }
15541            // If oldCodePath already contains prefix find out the
15542            // ending index to either increment or decrement.
15543            int sidx = subStr.lastIndexOf(prefix);
15544            if (sidx != -1) {
15545                subStr = subStr.substring(sidx + prefix.length());
15546                if (subStr != null) {
15547                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15548                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15549                    }
15550                    try {
15551                        idx = Integer.parseInt(subStr);
15552                        if (idx <= 1) {
15553                            idx++;
15554                        } else {
15555                            idx--;
15556                        }
15557                    } catch(NumberFormatException e) {
15558                    }
15559                }
15560            }
15561        }
15562        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15563        return prefix + idxStr;
15564    }
15565
15566    private File getNextCodePath(File targetDir, String packageName) {
15567        File result;
15568        SecureRandom random = new SecureRandom();
15569        byte[] bytes = new byte[16];
15570        do {
15571            random.nextBytes(bytes);
15572            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15573            result = new File(targetDir, packageName + "-" + suffix);
15574        } while (result.exists());
15575        return result;
15576    }
15577
15578    // Utility method that returns the relative package path with respect
15579    // to the installation directory. Like say for /data/data/com.test-1.apk
15580    // string com.test-1 is returned.
15581    static String deriveCodePathName(String codePath) {
15582        if (codePath == null) {
15583            return null;
15584        }
15585        final File codeFile = new File(codePath);
15586        final String name = codeFile.getName();
15587        if (codeFile.isDirectory()) {
15588            return name;
15589        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15590            final int lastDot = name.lastIndexOf('.');
15591            return name.substring(0, lastDot);
15592        } else {
15593            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15594            return null;
15595        }
15596    }
15597
15598    static class PackageInstalledInfo {
15599        String name;
15600        int uid;
15601        // The set of users that originally had this package installed.
15602        int[] origUsers;
15603        // The set of users that now have this package installed.
15604        int[] newUsers;
15605        PackageParser.Package pkg;
15606        int returnCode;
15607        String returnMsg;
15608        PackageRemovedInfo removedInfo;
15609        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15610
15611        public void setError(int code, String msg) {
15612            setReturnCode(code);
15613            setReturnMessage(msg);
15614            Slog.w(TAG, msg);
15615        }
15616
15617        public void setError(String msg, PackageParserException e) {
15618            setReturnCode(e.error);
15619            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15620            Slog.w(TAG, msg, e);
15621        }
15622
15623        public void setError(String msg, PackageManagerException e) {
15624            returnCode = e.error;
15625            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15626            Slog.w(TAG, msg, e);
15627        }
15628
15629        public void setReturnCode(int returnCode) {
15630            this.returnCode = returnCode;
15631            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15632            for (int i = 0; i < childCount; i++) {
15633                addedChildPackages.valueAt(i).returnCode = returnCode;
15634            }
15635        }
15636
15637        private void setReturnMessage(String returnMsg) {
15638            this.returnMsg = returnMsg;
15639            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15640            for (int i = 0; i < childCount; i++) {
15641                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15642            }
15643        }
15644
15645        // In some error cases we want to convey more info back to the observer
15646        String origPackage;
15647        String origPermission;
15648    }
15649
15650    /*
15651     * Install a non-existing package.
15652     */
15653    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15654            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15655            PackageInstalledInfo res, int installReason) {
15656        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15657
15658        // Remember this for later, in case we need to rollback this install
15659        String pkgName = pkg.packageName;
15660
15661        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15662
15663        synchronized(mPackages) {
15664            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15665            if (renamedPackage != null) {
15666                // A package with the same name is already installed, though
15667                // it has been renamed to an older name.  The package we
15668                // are trying to install should be installed as an update to
15669                // the existing one, but that has not been requested, so bail.
15670                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15671                        + " without first uninstalling package running as "
15672                        + renamedPackage);
15673                return;
15674            }
15675            if (mPackages.containsKey(pkgName)) {
15676                // Don't allow installation over an existing package with the same name.
15677                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15678                        + " without first uninstalling.");
15679                return;
15680            }
15681        }
15682
15683        try {
15684            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15685                    System.currentTimeMillis(), user);
15686
15687            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15688
15689            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15690                prepareAppDataAfterInstallLIF(newPackage);
15691
15692            } else {
15693                // Remove package from internal structures, but keep around any
15694                // data that might have already existed
15695                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15696                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15697            }
15698        } catch (PackageManagerException e) {
15699            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15700        }
15701
15702        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15703    }
15704
15705    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15706        // Can't rotate keys during boot or if sharedUser.
15707        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15708                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15709            return false;
15710        }
15711        // app is using upgradeKeySets; make sure all are valid
15712        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15713        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15714        for (int i = 0; i < upgradeKeySets.length; i++) {
15715            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15716                Slog.wtf(TAG, "Package "
15717                         + (oldPs.name != null ? oldPs.name : "<null>")
15718                         + " contains upgrade-key-set reference to unknown key-set: "
15719                         + upgradeKeySets[i]
15720                         + " reverting to signatures check.");
15721                return false;
15722            }
15723        }
15724        return true;
15725    }
15726
15727    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15728        // Upgrade keysets are being used.  Determine if new package has a superset of the
15729        // required keys.
15730        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15731        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15732        for (int i = 0; i < upgradeKeySets.length; i++) {
15733            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15734            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15735                return true;
15736            }
15737        }
15738        return false;
15739    }
15740
15741    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15742        try (DigestInputStream digestStream =
15743                new DigestInputStream(new FileInputStream(file), digest)) {
15744            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15745        }
15746    }
15747
15748    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15749            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15750            int installReason) {
15751        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15752
15753        final PackageParser.Package oldPackage;
15754        final String pkgName = pkg.packageName;
15755        final int[] allUsers;
15756        final int[] installedUsers;
15757
15758        synchronized(mPackages) {
15759            oldPackage = mPackages.get(pkgName);
15760            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15761
15762            // don't allow upgrade to target a release SDK from a pre-release SDK
15763            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15764                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15765            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15766                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15767            if (oldTargetsPreRelease
15768                    && !newTargetsPreRelease
15769                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15770                Slog.w(TAG, "Can't install package targeting released sdk");
15771                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15772                return;
15773            }
15774
15775            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15776
15777            // verify signatures are valid
15778            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15779                if (!checkUpgradeKeySetLP(ps, pkg)) {
15780                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15781                            "New package not signed by keys specified by upgrade-keysets: "
15782                                    + pkgName);
15783                    return;
15784                }
15785            } else {
15786                // default to original signature matching
15787                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15788                        != PackageManager.SIGNATURE_MATCH) {
15789                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15790                            "New package has a different signature: " + pkgName);
15791                    return;
15792                }
15793            }
15794
15795            // don't allow a system upgrade unless the upgrade hash matches
15796            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15797                byte[] digestBytes = null;
15798                try {
15799                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15800                    updateDigest(digest, new File(pkg.baseCodePath));
15801                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15802                        for (String path : pkg.splitCodePaths) {
15803                            updateDigest(digest, new File(path));
15804                        }
15805                    }
15806                    digestBytes = digest.digest();
15807                } catch (NoSuchAlgorithmException | IOException e) {
15808                    res.setError(INSTALL_FAILED_INVALID_APK,
15809                            "Could not compute hash: " + pkgName);
15810                    return;
15811                }
15812                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15813                    res.setError(INSTALL_FAILED_INVALID_APK,
15814                            "New package fails restrict-update check: " + pkgName);
15815                    return;
15816                }
15817                // retain upgrade restriction
15818                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15819            }
15820
15821            // Check for shared user id changes
15822            String invalidPackageName =
15823                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15824            if (invalidPackageName != null) {
15825                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15826                        "Package " + invalidPackageName + " tried to change user "
15827                                + oldPackage.mSharedUserId);
15828                return;
15829            }
15830
15831            // In case of rollback, remember per-user/profile install state
15832            allUsers = sUserManager.getUserIds();
15833            installedUsers = ps.queryInstalledUsers(allUsers, true);
15834
15835            // don't allow an upgrade from full to ephemeral
15836            if (isInstantApp) {
15837                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15838                    for (int currentUser : allUsers) {
15839                        if (!ps.getInstantApp(currentUser)) {
15840                            // can't downgrade from full to instant
15841                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15842                                    + " for user: " + currentUser);
15843                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15844                            return;
15845                        }
15846                    }
15847                } else if (!ps.getInstantApp(user.getIdentifier())) {
15848                    // can't downgrade from full to instant
15849                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15850                            + " for user: " + user.getIdentifier());
15851                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15852                    return;
15853                }
15854            }
15855        }
15856
15857        // Update what is removed
15858        res.removedInfo = new PackageRemovedInfo();
15859        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15860        res.removedInfo.removedPackage = oldPackage.packageName;
15861        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15862        res.removedInfo.isUpdate = true;
15863        res.removedInfo.origUsers = installedUsers;
15864        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15865        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15866        for (int i = 0; i < installedUsers.length; i++) {
15867            final int userId = installedUsers[i];
15868            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15869        }
15870
15871        final int childCount = (oldPackage.childPackages != null)
15872                ? oldPackage.childPackages.size() : 0;
15873        for (int i = 0; i < childCount; i++) {
15874            boolean childPackageUpdated = false;
15875            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15876            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15877            if (res.addedChildPackages != null) {
15878                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15879                if (childRes != null) {
15880                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15881                    childRes.removedInfo.removedPackage = childPkg.packageName;
15882                    childRes.removedInfo.isUpdate = true;
15883                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15884                    childPackageUpdated = true;
15885                }
15886            }
15887            if (!childPackageUpdated) {
15888                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15889                childRemovedRes.removedPackage = childPkg.packageName;
15890                childRemovedRes.isUpdate = false;
15891                childRemovedRes.dataRemoved = true;
15892                synchronized (mPackages) {
15893                    if (childPs != null) {
15894                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15895                    }
15896                }
15897                if (res.removedInfo.removedChildPackages == null) {
15898                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15899                }
15900                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15901            }
15902        }
15903
15904        boolean sysPkg = (isSystemApp(oldPackage));
15905        if (sysPkg) {
15906            // Set the system/privileged flags as needed
15907            final boolean privileged =
15908                    (oldPackage.applicationInfo.privateFlags
15909                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15910            final int systemPolicyFlags = policyFlags
15911                    | PackageParser.PARSE_IS_SYSTEM
15912                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15913
15914            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15915                    user, allUsers, installerPackageName, res, installReason);
15916        } else {
15917            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15918                    user, allUsers, installerPackageName, res, installReason);
15919        }
15920    }
15921
15922    public List<String> getPreviousCodePaths(String packageName) {
15923        final PackageSetting ps = mSettings.mPackages.get(packageName);
15924        final List<String> result = new ArrayList<String>();
15925        if (ps != null && ps.oldCodePaths != null) {
15926            result.addAll(ps.oldCodePaths);
15927        }
15928        return result;
15929    }
15930
15931    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15932            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15933            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15934            int installReason) {
15935        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15936                + deletedPackage);
15937
15938        String pkgName = deletedPackage.packageName;
15939        boolean deletedPkg = true;
15940        boolean addedPkg = false;
15941        boolean updatedSettings = false;
15942        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15943        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15944                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15945
15946        final long origUpdateTime = (pkg.mExtras != null)
15947                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15948
15949        // First delete the existing package while retaining the data directory
15950        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15951                res.removedInfo, true, pkg)) {
15952            // If the existing package wasn't successfully deleted
15953            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15954            deletedPkg = false;
15955        } else {
15956            // Successfully deleted the old package; proceed with replace.
15957
15958            // If deleted package lived in a container, give users a chance to
15959            // relinquish resources before killing.
15960            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15961                if (DEBUG_INSTALL) {
15962                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15963                }
15964                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15965                final ArrayList<String> pkgList = new ArrayList<String>(1);
15966                pkgList.add(deletedPackage.applicationInfo.packageName);
15967                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15968            }
15969
15970            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15971                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15972            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15973
15974            try {
15975                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15976                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15977                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15978                        installReason);
15979
15980                // Update the in-memory copy of the previous code paths.
15981                PackageSetting ps = mSettings.mPackages.get(pkgName);
15982                if (!killApp) {
15983                    if (ps.oldCodePaths == null) {
15984                        ps.oldCodePaths = new ArraySet<>();
15985                    }
15986                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15987                    if (deletedPackage.splitCodePaths != null) {
15988                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15989                    }
15990                } else {
15991                    ps.oldCodePaths = null;
15992                }
15993                if (ps.childPackageNames != null) {
15994                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15995                        final String childPkgName = ps.childPackageNames.get(i);
15996                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15997                        childPs.oldCodePaths = ps.oldCodePaths;
15998                    }
15999                }
16000                // set instant app status, but, only if it's explicitly specified
16001                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16002                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16003                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16004                prepareAppDataAfterInstallLIF(newPackage);
16005                addedPkg = true;
16006                mDexManager.notifyPackageUpdated(newPackage.packageName,
16007                        newPackage.baseCodePath, newPackage.splitCodePaths);
16008            } catch (PackageManagerException e) {
16009                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16010            }
16011        }
16012
16013        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16014            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16015
16016            // Revert all internal state mutations and added folders for the failed install
16017            if (addedPkg) {
16018                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16019                        res.removedInfo, true, null);
16020            }
16021
16022            // Restore the old package
16023            if (deletedPkg) {
16024                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16025                File restoreFile = new File(deletedPackage.codePath);
16026                // Parse old package
16027                boolean oldExternal = isExternal(deletedPackage);
16028                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16029                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16030                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16031                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16032                try {
16033                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16034                            null);
16035                } catch (PackageManagerException e) {
16036                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16037                            + e.getMessage());
16038                    return;
16039                }
16040
16041                synchronized (mPackages) {
16042                    // Ensure the installer package name up to date
16043                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16044
16045                    // Update permissions for restored package
16046                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16047
16048                    mSettings.writeLPr();
16049                }
16050
16051                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16052            }
16053        } else {
16054            synchronized (mPackages) {
16055                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16056                if (ps != null) {
16057                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16058                    if (res.removedInfo.removedChildPackages != null) {
16059                        final int childCount = res.removedInfo.removedChildPackages.size();
16060                        // Iterate in reverse as we may modify the collection
16061                        for (int i = childCount - 1; i >= 0; i--) {
16062                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16063                            if (res.addedChildPackages.containsKey(childPackageName)) {
16064                                res.removedInfo.removedChildPackages.removeAt(i);
16065                            } else {
16066                                PackageRemovedInfo childInfo = res.removedInfo
16067                                        .removedChildPackages.valueAt(i);
16068                                childInfo.removedForAllUsers = mPackages.get(
16069                                        childInfo.removedPackage) == null;
16070                            }
16071                        }
16072                    }
16073                }
16074            }
16075        }
16076    }
16077
16078    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16079            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16080            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16081            int installReason) {
16082        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16083                + ", old=" + deletedPackage);
16084
16085        final boolean disabledSystem;
16086
16087        // Remove existing system package
16088        removePackageLI(deletedPackage, true);
16089
16090        synchronized (mPackages) {
16091            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16092        }
16093        if (!disabledSystem) {
16094            // We didn't need to disable the .apk as a current system package,
16095            // which means we are replacing another update that is already
16096            // installed.  We need to make sure to delete the older one's .apk.
16097            res.removedInfo.args = createInstallArgsForExisting(0,
16098                    deletedPackage.applicationInfo.getCodePath(),
16099                    deletedPackage.applicationInfo.getResourcePath(),
16100                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16101        } else {
16102            res.removedInfo.args = null;
16103        }
16104
16105        // Successfully disabled the old package. Now proceed with re-installation
16106        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16107                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16108        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16109
16110        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16111        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16112                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16113
16114        PackageParser.Package newPackage = null;
16115        try {
16116            // Add the package to the internal data structures
16117            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16118
16119            // Set the update and install times
16120            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16121            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16122                    System.currentTimeMillis());
16123
16124            // Update the package dynamic state if succeeded
16125            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16126                // Now that the install succeeded make sure we remove data
16127                // directories for any child package the update removed.
16128                final int deletedChildCount = (deletedPackage.childPackages != null)
16129                        ? deletedPackage.childPackages.size() : 0;
16130                final int newChildCount = (newPackage.childPackages != null)
16131                        ? newPackage.childPackages.size() : 0;
16132                for (int i = 0; i < deletedChildCount; i++) {
16133                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16134                    boolean childPackageDeleted = true;
16135                    for (int j = 0; j < newChildCount; j++) {
16136                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16137                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16138                            childPackageDeleted = false;
16139                            break;
16140                        }
16141                    }
16142                    if (childPackageDeleted) {
16143                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16144                                deletedChildPkg.packageName);
16145                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16146                            PackageRemovedInfo removedChildRes = res.removedInfo
16147                                    .removedChildPackages.get(deletedChildPkg.packageName);
16148                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16149                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16150                        }
16151                    }
16152                }
16153
16154                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16155                        installReason);
16156                prepareAppDataAfterInstallLIF(newPackage);
16157
16158                mDexManager.notifyPackageUpdated(newPackage.packageName,
16159                            newPackage.baseCodePath, newPackage.splitCodePaths);
16160            }
16161        } catch (PackageManagerException e) {
16162            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16163            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16164        }
16165
16166        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16167            // Re installation failed. Restore old information
16168            // Remove new pkg information
16169            if (newPackage != null) {
16170                removeInstalledPackageLI(newPackage, true);
16171            }
16172            // Add back the old system package
16173            try {
16174                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16175            } catch (PackageManagerException e) {
16176                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16177            }
16178
16179            synchronized (mPackages) {
16180                if (disabledSystem) {
16181                    enableSystemPackageLPw(deletedPackage);
16182                }
16183
16184                // Ensure the installer package name up to date
16185                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16186
16187                // Update permissions for restored package
16188                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16189
16190                mSettings.writeLPr();
16191            }
16192
16193            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16194                    + " after failed upgrade");
16195        }
16196    }
16197
16198    /**
16199     * Checks whether the parent or any of the child packages have a change shared
16200     * user. For a package to be a valid update the shred users of the parent and
16201     * the children should match. We may later support changing child shared users.
16202     * @param oldPkg The updated package.
16203     * @param newPkg The update package.
16204     * @return The shared user that change between the versions.
16205     */
16206    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16207            PackageParser.Package newPkg) {
16208        // Check parent shared user
16209        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16210            return newPkg.packageName;
16211        }
16212        // Check child shared users
16213        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16214        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16215        for (int i = 0; i < newChildCount; i++) {
16216            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16217            // If this child was present, did it have the same shared user?
16218            for (int j = 0; j < oldChildCount; j++) {
16219                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16220                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16221                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16222                    return newChildPkg.packageName;
16223                }
16224            }
16225        }
16226        return null;
16227    }
16228
16229    private void removeNativeBinariesLI(PackageSetting ps) {
16230        // Remove the lib path for the parent package
16231        if (ps != null) {
16232            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16233            // Remove the lib path for the child packages
16234            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16235            for (int i = 0; i < childCount; i++) {
16236                PackageSetting childPs = null;
16237                synchronized (mPackages) {
16238                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16239                }
16240                if (childPs != null) {
16241                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16242                            .legacyNativeLibraryPathString);
16243                }
16244            }
16245        }
16246    }
16247
16248    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16249        // Enable the parent package
16250        mSettings.enableSystemPackageLPw(pkg.packageName);
16251        // Enable the child packages
16252        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16253        for (int i = 0; i < childCount; i++) {
16254            PackageParser.Package childPkg = pkg.childPackages.get(i);
16255            mSettings.enableSystemPackageLPw(childPkg.packageName);
16256        }
16257    }
16258
16259    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16260            PackageParser.Package newPkg) {
16261        // Disable the parent package (parent always replaced)
16262        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16263        // Disable the child packages
16264        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16265        for (int i = 0; i < childCount; i++) {
16266            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16267            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16268            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16269        }
16270        return disabled;
16271    }
16272
16273    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16274            String installerPackageName) {
16275        // Enable the parent package
16276        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16277        // Enable the child packages
16278        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16279        for (int i = 0; i < childCount; i++) {
16280            PackageParser.Package childPkg = pkg.childPackages.get(i);
16281            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16282        }
16283    }
16284
16285    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16286        // Collect all used permissions in the UID
16287        ArraySet<String> usedPermissions = new ArraySet<>();
16288        final int packageCount = su.packages.size();
16289        for (int i = 0; i < packageCount; i++) {
16290            PackageSetting ps = su.packages.valueAt(i);
16291            if (ps.pkg == null) {
16292                continue;
16293            }
16294            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16295            for (int j = 0; j < requestedPermCount; j++) {
16296                String permission = ps.pkg.requestedPermissions.get(j);
16297                BasePermission bp = mSettings.mPermissions.get(permission);
16298                if (bp != null) {
16299                    usedPermissions.add(permission);
16300                }
16301            }
16302        }
16303
16304        PermissionsState permissionsState = su.getPermissionsState();
16305        // Prune install permissions
16306        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16307        final int installPermCount = installPermStates.size();
16308        for (int i = installPermCount - 1; i >= 0;  i--) {
16309            PermissionState permissionState = installPermStates.get(i);
16310            if (!usedPermissions.contains(permissionState.getName())) {
16311                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16312                if (bp != null) {
16313                    permissionsState.revokeInstallPermission(bp);
16314                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16315                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16316                }
16317            }
16318        }
16319
16320        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16321
16322        // Prune runtime permissions
16323        for (int userId : allUserIds) {
16324            List<PermissionState> runtimePermStates = permissionsState
16325                    .getRuntimePermissionStates(userId);
16326            final int runtimePermCount = runtimePermStates.size();
16327            for (int i = runtimePermCount - 1; i >= 0; i--) {
16328                PermissionState permissionState = runtimePermStates.get(i);
16329                if (!usedPermissions.contains(permissionState.getName())) {
16330                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16331                    if (bp != null) {
16332                        permissionsState.revokeRuntimePermission(bp, userId);
16333                        permissionsState.updatePermissionFlags(bp, userId,
16334                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16335                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16336                                runtimePermissionChangedUserIds, userId);
16337                    }
16338                }
16339            }
16340        }
16341
16342        return runtimePermissionChangedUserIds;
16343    }
16344
16345    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16346            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16347        // Update the parent package setting
16348        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16349                res, user, installReason);
16350        // Update the child packages setting
16351        final int childCount = (newPackage.childPackages != null)
16352                ? newPackage.childPackages.size() : 0;
16353        for (int i = 0; i < childCount; i++) {
16354            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16355            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16356            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16357                    childRes.origUsers, childRes, user, installReason);
16358        }
16359    }
16360
16361    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16362            String installerPackageName, int[] allUsers, int[] installedForUsers,
16363            PackageInstalledInfo res, UserHandle user, int installReason) {
16364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16365
16366        String pkgName = newPackage.packageName;
16367        synchronized (mPackages) {
16368            //write settings. the installStatus will be incomplete at this stage.
16369            //note that the new package setting would have already been
16370            //added to mPackages. It hasn't been persisted yet.
16371            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16372            // TODO: Remove this write? It's also written at the end of this method
16373            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16374            mSettings.writeLPr();
16375            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16376        }
16377
16378        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16379        synchronized (mPackages) {
16380            updatePermissionsLPw(newPackage.packageName, newPackage,
16381                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16382                            ? UPDATE_PERMISSIONS_ALL : 0));
16383            // For system-bundled packages, we assume that installing an upgraded version
16384            // of the package implies that the user actually wants to run that new code,
16385            // so we enable the package.
16386            PackageSetting ps = mSettings.mPackages.get(pkgName);
16387            final int userId = user.getIdentifier();
16388            if (ps != null) {
16389                if (isSystemApp(newPackage)) {
16390                    if (DEBUG_INSTALL) {
16391                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16392                    }
16393                    // Enable system package for requested users
16394                    if (res.origUsers != null) {
16395                        for (int origUserId : res.origUsers) {
16396                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16397                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16398                                        origUserId, installerPackageName);
16399                            }
16400                        }
16401                    }
16402                    // Also convey the prior install/uninstall state
16403                    if (allUsers != null && installedForUsers != null) {
16404                        for (int currentUserId : allUsers) {
16405                            final boolean installed = ArrayUtils.contains(
16406                                    installedForUsers, currentUserId);
16407                            if (DEBUG_INSTALL) {
16408                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16409                            }
16410                            ps.setInstalled(installed, currentUserId);
16411                        }
16412                        // these install state changes will be persisted in the
16413                        // upcoming call to mSettings.writeLPr().
16414                    }
16415                }
16416                // It's implied that when a user requests installation, they want the app to be
16417                // installed and enabled.
16418                if (userId != UserHandle.USER_ALL) {
16419                    ps.setInstalled(true, userId);
16420                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16421                }
16422
16423                // When replacing an existing package, preserve the original install reason for all
16424                // users that had the package installed before.
16425                final Set<Integer> previousUserIds = new ArraySet<>();
16426                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16427                    final int installReasonCount = res.removedInfo.installReasons.size();
16428                    for (int i = 0; i < installReasonCount; i++) {
16429                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16430                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16431                        ps.setInstallReason(previousInstallReason, previousUserId);
16432                        previousUserIds.add(previousUserId);
16433                    }
16434                }
16435
16436                // Set install reason for users that are having the package newly installed.
16437                if (userId == UserHandle.USER_ALL) {
16438                    for (int currentUserId : sUserManager.getUserIds()) {
16439                        if (!previousUserIds.contains(currentUserId)) {
16440                            ps.setInstallReason(installReason, currentUserId);
16441                        }
16442                    }
16443                } else if (!previousUserIds.contains(userId)) {
16444                    ps.setInstallReason(installReason, userId);
16445                }
16446                mSettings.writeKernelMappingLPr(ps);
16447            }
16448            res.name = pkgName;
16449            res.uid = newPackage.applicationInfo.uid;
16450            res.pkg = newPackage;
16451            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16452            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16453            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16454            //to update install status
16455            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16456            mSettings.writeLPr();
16457            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16458        }
16459
16460        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16461    }
16462
16463    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16464        try {
16465            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16466            installPackageLI(args, res);
16467        } finally {
16468            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16469        }
16470    }
16471
16472    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16473        final int installFlags = args.installFlags;
16474        final String installerPackageName = args.installerPackageName;
16475        final String volumeUuid = args.volumeUuid;
16476        final File tmpPackageFile = new File(args.getCodePath());
16477        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16478        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16479                || (args.volumeUuid != null));
16480        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16481        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16482        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16483        boolean replace = false;
16484        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16485        if (args.move != null) {
16486            // moving a complete application; perform an initial scan on the new install location
16487            scanFlags |= SCAN_INITIAL;
16488        }
16489        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16490            scanFlags |= SCAN_DONT_KILL_APP;
16491        }
16492        if (instantApp) {
16493            scanFlags |= SCAN_AS_INSTANT_APP;
16494        }
16495        if (fullApp) {
16496            scanFlags |= SCAN_AS_FULL_APP;
16497        }
16498
16499        // Result object to be returned
16500        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16501
16502        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16503
16504        // Sanity check
16505        if (instantApp && (forwardLocked || onExternal)) {
16506            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16507                    + " external=" + onExternal);
16508            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16509            return;
16510        }
16511
16512        // Retrieve PackageSettings and parse package
16513        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16514                | PackageParser.PARSE_ENFORCE_CODE
16515                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16516                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16517                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16518                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16519        PackageParser pp = new PackageParser();
16520        pp.setSeparateProcesses(mSeparateProcesses);
16521        pp.setDisplayMetrics(mMetrics);
16522        pp.setCallback(mPackageParserCallback);
16523
16524        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16525        final PackageParser.Package pkg;
16526        try {
16527            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16528        } catch (PackageParserException e) {
16529            res.setError("Failed parse during installPackageLI", e);
16530            return;
16531        } finally {
16532            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16533        }
16534
16535        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16536        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16537            Slog.w(TAG, "Instant app package " + pkg.packageName
16538                    + " does not target O, this will be a fatal error.");
16539            // STOPSHIP: Make this a fatal error
16540            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16541        }
16542        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16543            Slog.w(TAG, "Instant app package " + pkg.packageName
16544                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16545            // STOPSHIP: Make this a fatal error
16546            pkg.applicationInfo.targetSandboxVersion = 2;
16547        }
16548
16549        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16550            // Static shared libraries have synthetic package names
16551            renameStaticSharedLibraryPackage(pkg);
16552
16553            // No static shared libs on external storage
16554            if (onExternal) {
16555                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16556                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16557                        "Packages declaring static-shared libs cannot be updated");
16558                return;
16559            }
16560        }
16561
16562        // If we are installing a clustered package add results for the children
16563        if (pkg.childPackages != null) {
16564            synchronized (mPackages) {
16565                final int childCount = pkg.childPackages.size();
16566                for (int i = 0; i < childCount; i++) {
16567                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16568                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16569                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16570                    childRes.pkg = childPkg;
16571                    childRes.name = childPkg.packageName;
16572                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16573                    if (childPs != null) {
16574                        childRes.origUsers = childPs.queryInstalledUsers(
16575                                sUserManager.getUserIds(), true);
16576                    }
16577                    if ((mPackages.containsKey(childPkg.packageName))) {
16578                        childRes.removedInfo = new PackageRemovedInfo();
16579                        childRes.removedInfo.removedPackage = childPkg.packageName;
16580                    }
16581                    if (res.addedChildPackages == null) {
16582                        res.addedChildPackages = new ArrayMap<>();
16583                    }
16584                    res.addedChildPackages.put(childPkg.packageName, childRes);
16585                }
16586            }
16587        }
16588
16589        // If package doesn't declare API override, mark that we have an install
16590        // time CPU ABI override.
16591        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16592            pkg.cpuAbiOverride = args.abiOverride;
16593        }
16594
16595        String pkgName = res.name = pkg.packageName;
16596        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16597            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16598                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16599                return;
16600            }
16601        }
16602
16603        try {
16604            // either use what we've been given or parse directly from the APK
16605            if (args.certificates != null) {
16606                try {
16607                    PackageParser.populateCertificates(pkg, args.certificates);
16608                } catch (PackageParserException e) {
16609                    // there was something wrong with the certificates we were given;
16610                    // try to pull them from the APK
16611                    PackageParser.collectCertificates(pkg, parseFlags);
16612                }
16613            } else {
16614                PackageParser.collectCertificates(pkg, parseFlags);
16615            }
16616        } catch (PackageParserException e) {
16617            res.setError("Failed collect during installPackageLI", e);
16618            return;
16619        }
16620
16621        // Get rid of all references to package scan path via parser.
16622        pp = null;
16623        String oldCodePath = null;
16624        boolean systemApp = false;
16625        synchronized (mPackages) {
16626            // Check if installing already existing package
16627            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16628                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16629                if (pkg.mOriginalPackages != null
16630                        && pkg.mOriginalPackages.contains(oldName)
16631                        && mPackages.containsKey(oldName)) {
16632                    // This package is derived from an original package,
16633                    // and this device has been updating from that original
16634                    // name.  We must continue using the original name, so
16635                    // rename the new package here.
16636                    pkg.setPackageName(oldName);
16637                    pkgName = pkg.packageName;
16638                    replace = true;
16639                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16640                            + oldName + " pkgName=" + pkgName);
16641                } else if (mPackages.containsKey(pkgName)) {
16642                    // This package, under its official name, already exists
16643                    // on the device; we should replace it.
16644                    replace = true;
16645                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16646                }
16647
16648                // Child packages are installed through the parent package
16649                if (pkg.parentPackage != null) {
16650                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16651                            "Package " + pkg.packageName + " is child of package "
16652                                    + pkg.parentPackage.parentPackage + ". Child packages "
16653                                    + "can be updated only through the parent package.");
16654                    return;
16655                }
16656
16657                if (replace) {
16658                    // Prevent apps opting out from runtime permissions
16659                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16660                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16661                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16662                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16663                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16664                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16665                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16666                                        + " doesn't support runtime permissions but the old"
16667                                        + " target SDK " + oldTargetSdk + " does.");
16668                        return;
16669                    }
16670
16671                    // Prevent installing of child packages
16672                    if (oldPackage.parentPackage != null) {
16673                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16674                                "Package " + pkg.packageName + " is child of package "
16675                                        + oldPackage.parentPackage + ". Child packages "
16676                                        + "can be updated only through the parent package.");
16677                        return;
16678                    }
16679                }
16680            }
16681
16682            PackageSetting ps = mSettings.mPackages.get(pkgName);
16683            if (ps != null) {
16684                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16685
16686                // Static shared libs have same package with different versions where
16687                // we internally use a synthetic package name to allow multiple versions
16688                // of the same package, therefore we need to compare signatures against
16689                // the package setting for the latest library version.
16690                PackageSetting signatureCheckPs = ps;
16691                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16692                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16693                    if (libraryEntry != null) {
16694                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16695                    }
16696                }
16697
16698                // Quick sanity check that we're signed correctly if updating;
16699                // we'll check this again later when scanning, but we want to
16700                // bail early here before tripping over redefined permissions.
16701                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16702                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16703                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16704                                + pkg.packageName + " upgrade keys do not match the "
16705                                + "previously installed version");
16706                        return;
16707                    }
16708                } else {
16709                    try {
16710                        verifySignaturesLP(signatureCheckPs, pkg);
16711                    } catch (PackageManagerException e) {
16712                        res.setError(e.error, e.getMessage());
16713                        return;
16714                    }
16715                }
16716
16717                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16718                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16719                    systemApp = (ps.pkg.applicationInfo.flags &
16720                            ApplicationInfo.FLAG_SYSTEM) != 0;
16721                }
16722                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16723            }
16724
16725            int N = pkg.permissions.size();
16726            for (int i = N-1; i >= 0; i--) {
16727                PackageParser.Permission perm = pkg.permissions.get(i);
16728                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16729
16730                // Don't allow anyone but the platform to define ephemeral permissions.
16731                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16732                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16733                    Slog.w(TAG, "Package " + pkg.packageName
16734                            + " attempting to delcare ephemeral permission "
16735                            + perm.info.name + "; Removing ephemeral.");
16736                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16737                }
16738                // Check whether the newly-scanned package wants to define an already-defined perm
16739                if (bp != null) {
16740                    // If the defining package is signed with our cert, it's okay.  This
16741                    // also includes the "updating the same package" case, of course.
16742                    // "updating same package" could also involve key-rotation.
16743                    final boolean sigsOk;
16744                    if (bp.sourcePackage.equals(pkg.packageName)
16745                            && (bp.packageSetting instanceof PackageSetting)
16746                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16747                                    scanFlags))) {
16748                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16749                    } else {
16750                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16751                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16752                    }
16753                    if (!sigsOk) {
16754                        // If the owning package is the system itself, we log but allow
16755                        // install to proceed; we fail the install on all other permission
16756                        // redefinitions.
16757                        if (!bp.sourcePackage.equals("android")) {
16758                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16759                                    + pkg.packageName + " attempting to redeclare permission "
16760                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16761                            res.origPermission = perm.info.name;
16762                            res.origPackage = bp.sourcePackage;
16763                            return;
16764                        } else {
16765                            Slog.w(TAG, "Package " + pkg.packageName
16766                                    + " attempting to redeclare system permission "
16767                                    + perm.info.name + "; ignoring new declaration");
16768                            pkg.permissions.remove(i);
16769                        }
16770                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16771                        // Prevent apps to change protection level to dangerous from any other
16772                        // type as this would allow a privilege escalation where an app adds a
16773                        // normal/signature permission in other app's group and later redefines
16774                        // it as dangerous leading to the group auto-grant.
16775                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16776                                == PermissionInfo.PROTECTION_DANGEROUS) {
16777                            if (bp != null && !bp.isRuntime()) {
16778                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16779                                        + "non-runtime permission " + perm.info.name
16780                                        + " to runtime; keeping old protection level");
16781                                perm.info.protectionLevel = bp.protectionLevel;
16782                            }
16783                        }
16784                    }
16785                }
16786            }
16787        }
16788
16789        if (systemApp) {
16790            if (onExternal) {
16791                // Abort update; system app can't be replaced with app on sdcard
16792                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16793                        "Cannot install updates to system apps on sdcard");
16794                return;
16795            } else if (instantApp) {
16796                // Abort update; system app can't be replaced with an instant app
16797                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16798                        "Cannot update a system app with an instant app");
16799                return;
16800            }
16801        }
16802
16803        if (args.move != null) {
16804            // We did an in-place move, so dex is ready to roll
16805            scanFlags |= SCAN_NO_DEX;
16806            scanFlags |= SCAN_MOVE;
16807
16808            synchronized (mPackages) {
16809                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16810                if (ps == null) {
16811                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16812                            "Missing settings for moved package " + pkgName);
16813                }
16814
16815                // We moved the entire application as-is, so bring over the
16816                // previously derived ABI information.
16817                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16818                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16819            }
16820
16821        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16822            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16823            scanFlags |= SCAN_NO_DEX;
16824
16825            try {
16826                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16827                    args.abiOverride : pkg.cpuAbiOverride);
16828                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16829                        true /*extractLibs*/, mAppLib32InstallDir);
16830            } catch (PackageManagerException pme) {
16831                Slog.e(TAG, "Error deriving application ABI", pme);
16832                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16833                return;
16834            }
16835
16836            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16837            // Do not run PackageDexOptimizer through the local performDexOpt
16838            // method because `pkg` may not be in `mPackages` yet.
16839            //
16840            // Also, don't fail application installs if the dexopt step fails.
16841            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16842                    null /* instructionSets */, false /* checkProfiles */,
16843                    getCompilerFilterForReason(REASON_INSTALL),
16844                    getOrCreateCompilerPackageStats(pkg),
16845                    mDexManager.isUsedByOtherApps(pkg.packageName));
16846            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16847
16848            // Notify BackgroundDexOptJobService that the package has been changed.
16849            // If this is an update of a package which used to fail to compile,
16850            // BDOS will remove it from its blacklist.
16851            // TODO: Layering violation
16852            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16853        }
16854
16855        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16856            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16857            return;
16858        }
16859
16860        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16861
16862        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16863                "installPackageLI")) {
16864            if (replace) {
16865                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16866                    // Static libs have a synthetic package name containing the version
16867                    // and cannot be updated as an update would get a new package name,
16868                    // unless this is the exact same version code which is useful for
16869                    // development.
16870                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16871                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16872                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16873                                + "static-shared libs cannot be updated");
16874                        return;
16875                    }
16876                }
16877                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16878                        installerPackageName, res, args.installReason);
16879            } else {
16880                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16881                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16882            }
16883        }
16884        synchronized (mPackages) {
16885            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16886            if (ps != null) {
16887                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16888            }
16889
16890            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16891            for (int i = 0; i < childCount; i++) {
16892                PackageParser.Package childPkg = pkg.childPackages.get(i);
16893                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16894                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16895                if (childPs != null) {
16896                    childRes.newUsers = childPs.queryInstalledUsers(
16897                            sUserManager.getUserIds(), true);
16898                }
16899            }
16900
16901            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16902                updateSequenceNumberLP(pkgName, res.newUsers);
16903            }
16904        }
16905    }
16906
16907    private void startIntentFilterVerifications(int userId, boolean replacing,
16908            PackageParser.Package pkg) {
16909        if (mIntentFilterVerifierComponent == null) {
16910            Slog.w(TAG, "No IntentFilter verification will not be done as "
16911                    + "there is no IntentFilterVerifier available!");
16912            return;
16913        }
16914
16915        final int verifierUid = getPackageUid(
16916                mIntentFilterVerifierComponent.getPackageName(),
16917                MATCH_DEBUG_TRIAGED_MISSING,
16918                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16919
16920        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16921        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16922        mHandler.sendMessage(msg);
16923
16924        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16925        for (int i = 0; i < childCount; i++) {
16926            PackageParser.Package childPkg = pkg.childPackages.get(i);
16927            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16928            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16929            mHandler.sendMessage(msg);
16930        }
16931    }
16932
16933    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16934            PackageParser.Package pkg) {
16935        int size = pkg.activities.size();
16936        if (size == 0) {
16937            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16938                    "No activity, so no need to verify any IntentFilter!");
16939            return;
16940        }
16941
16942        final boolean hasDomainURLs = hasDomainURLs(pkg);
16943        if (!hasDomainURLs) {
16944            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16945                    "No domain URLs, so no need to verify any IntentFilter!");
16946            return;
16947        }
16948
16949        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16950                + " if any IntentFilter from the " + size
16951                + " Activities needs verification ...");
16952
16953        int count = 0;
16954        final String packageName = pkg.packageName;
16955
16956        synchronized (mPackages) {
16957            // If this is a new install and we see that we've already run verification for this
16958            // package, we have nothing to do: it means the state was restored from backup.
16959            if (!replacing) {
16960                IntentFilterVerificationInfo ivi =
16961                        mSettings.getIntentFilterVerificationLPr(packageName);
16962                if (ivi != null) {
16963                    if (DEBUG_DOMAIN_VERIFICATION) {
16964                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16965                                + ivi.getStatusString());
16966                    }
16967                    return;
16968                }
16969            }
16970
16971            // If any filters need to be verified, then all need to be.
16972            boolean needToVerify = false;
16973            for (PackageParser.Activity a : pkg.activities) {
16974                for (ActivityIntentInfo filter : a.intents) {
16975                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16976                        if (DEBUG_DOMAIN_VERIFICATION) {
16977                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16978                        }
16979                        needToVerify = true;
16980                        break;
16981                    }
16982                }
16983            }
16984
16985            if (needToVerify) {
16986                final int verificationId = mIntentFilterVerificationToken++;
16987                for (PackageParser.Activity a : pkg.activities) {
16988                    for (ActivityIntentInfo filter : a.intents) {
16989                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16990                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16991                                    "Verification needed for IntentFilter:" + filter.toString());
16992                            mIntentFilterVerifier.addOneIntentFilterVerification(
16993                                    verifierUid, userId, verificationId, filter, packageName);
16994                            count++;
16995                        }
16996                    }
16997                }
16998            }
16999        }
17000
17001        if (count > 0) {
17002            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17003                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17004                    +  " for userId:" + userId);
17005            mIntentFilterVerifier.startVerifications(userId);
17006        } else {
17007            if (DEBUG_DOMAIN_VERIFICATION) {
17008                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17009            }
17010        }
17011    }
17012
17013    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17014        final ComponentName cn  = filter.activity.getComponentName();
17015        final String packageName = cn.getPackageName();
17016
17017        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17018                packageName);
17019        if (ivi == null) {
17020            return true;
17021        }
17022        int status = ivi.getStatus();
17023        switch (status) {
17024            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17025            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17026                return true;
17027
17028            default:
17029                // Nothing to do
17030                return false;
17031        }
17032    }
17033
17034    private static boolean isMultiArch(ApplicationInfo info) {
17035        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17036    }
17037
17038    private static boolean isExternal(PackageParser.Package pkg) {
17039        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17040    }
17041
17042    private static boolean isExternal(PackageSetting ps) {
17043        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17044    }
17045
17046    private static boolean isSystemApp(PackageParser.Package pkg) {
17047        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17048    }
17049
17050    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17051        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17052    }
17053
17054    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17055        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17056    }
17057
17058    private static boolean isSystemApp(PackageSetting ps) {
17059        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17060    }
17061
17062    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17063        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17064    }
17065
17066    private int packageFlagsToInstallFlags(PackageSetting ps) {
17067        int installFlags = 0;
17068        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17069            // This existing package was an external ASEC install when we have
17070            // the external flag without a UUID
17071            installFlags |= PackageManager.INSTALL_EXTERNAL;
17072        }
17073        if (ps.isForwardLocked()) {
17074            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17075        }
17076        return installFlags;
17077    }
17078
17079    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17080        if (isExternal(pkg)) {
17081            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17082                return StorageManager.UUID_PRIMARY_PHYSICAL;
17083            } else {
17084                return pkg.volumeUuid;
17085            }
17086        } else {
17087            return StorageManager.UUID_PRIVATE_INTERNAL;
17088        }
17089    }
17090
17091    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17092        if (isExternal(pkg)) {
17093            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17094                return mSettings.getExternalVersion();
17095            } else {
17096                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17097            }
17098        } else {
17099            return mSettings.getInternalVersion();
17100        }
17101    }
17102
17103    private void deleteTempPackageFiles() {
17104        final FilenameFilter filter = new FilenameFilter() {
17105            public boolean accept(File dir, String name) {
17106                return name.startsWith("vmdl") && name.endsWith(".tmp");
17107            }
17108        };
17109        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17110            file.delete();
17111        }
17112    }
17113
17114    @Override
17115    public void deletePackageAsUser(String packageName, int versionCode,
17116            IPackageDeleteObserver observer, int userId, int flags) {
17117        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17118                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17119    }
17120
17121    @Override
17122    public void deletePackageVersioned(VersionedPackage versionedPackage,
17123            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17124        mContext.enforceCallingOrSelfPermission(
17125                android.Manifest.permission.DELETE_PACKAGES, null);
17126        Preconditions.checkNotNull(versionedPackage);
17127        Preconditions.checkNotNull(observer);
17128        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17129                PackageManager.VERSION_CODE_HIGHEST,
17130                Integer.MAX_VALUE, "versionCode must be >= -1");
17131
17132        final String packageName = versionedPackage.getPackageName();
17133        // TODO: We will change version code to long, so in the new API it is long
17134        final int versionCode = (int) versionedPackage.getVersionCode();
17135        final String internalPackageName;
17136        synchronized (mPackages) {
17137            // Normalize package name to handle renamed packages and static libs
17138            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17139                    // TODO: We will change version code to long, so in the new API it is long
17140                    (int) versionedPackage.getVersionCode());
17141        }
17142
17143        final int uid = Binder.getCallingUid();
17144        if (!isOrphaned(internalPackageName)
17145                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17146            try {
17147                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17148                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17149                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17150                observer.onUserActionRequired(intent);
17151            } catch (RemoteException re) {
17152            }
17153            return;
17154        }
17155        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17156        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17157        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17158            mContext.enforceCallingOrSelfPermission(
17159                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17160                    "deletePackage for user " + userId);
17161        }
17162
17163        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17164            try {
17165                observer.onPackageDeleted(packageName,
17166                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17167            } catch (RemoteException re) {
17168            }
17169            return;
17170        }
17171
17172        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17173            try {
17174                observer.onPackageDeleted(packageName,
17175                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17176            } catch (RemoteException re) {
17177            }
17178            return;
17179        }
17180
17181        if (DEBUG_REMOVE) {
17182            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17183                    + " deleteAllUsers: " + deleteAllUsers + " version="
17184                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17185                    ? "VERSION_CODE_HIGHEST" : versionCode));
17186        }
17187        // Queue up an async operation since the package deletion may take a little while.
17188        mHandler.post(new Runnable() {
17189            public void run() {
17190                mHandler.removeCallbacks(this);
17191                int returnCode;
17192                if (!deleteAllUsers) {
17193                    returnCode = deletePackageX(internalPackageName, versionCode,
17194                            userId, deleteFlags);
17195                } else {
17196                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17197                            internalPackageName, users);
17198                    // If nobody is blocking uninstall, proceed with delete for all users
17199                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17200                        returnCode = deletePackageX(internalPackageName, versionCode,
17201                                userId, deleteFlags);
17202                    } else {
17203                        // Otherwise uninstall individually for users with blockUninstalls=false
17204                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17205                        for (int userId : users) {
17206                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17207                                returnCode = deletePackageX(internalPackageName, versionCode,
17208                                        userId, userFlags);
17209                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17210                                    Slog.w(TAG, "Package delete failed for user " + userId
17211                                            + ", returnCode " + returnCode);
17212                                }
17213                            }
17214                        }
17215                        // The app has only been marked uninstalled for certain users.
17216                        // We still need to report that delete was blocked
17217                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17218                    }
17219                }
17220                try {
17221                    observer.onPackageDeleted(packageName, returnCode, null);
17222                } catch (RemoteException e) {
17223                    Log.i(TAG, "Observer no longer exists.");
17224                } //end catch
17225            } //end run
17226        });
17227    }
17228
17229    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17230        if (pkg.staticSharedLibName != null) {
17231            return pkg.manifestPackageName;
17232        }
17233        return pkg.packageName;
17234    }
17235
17236    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17237        // Handle renamed packages
17238        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17239        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17240
17241        // Is this a static library?
17242        SparseArray<SharedLibraryEntry> versionedLib =
17243                mStaticLibsByDeclaringPackage.get(packageName);
17244        if (versionedLib == null || versionedLib.size() <= 0) {
17245            return packageName;
17246        }
17247
17248        // Figure out which lib versions the caller can see
17249        SparseIntArray versionsCallerCanSee = null;
17250        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17251        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17252                && callingAppId != Process.ROOT_UID) {
17253            versionsCallerCanSee = new SparseIntArray();
17254            String libName = versionedLib.valueAt(0).info.getName();
17255            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17256            if (uidPackages != null) {
17257                for (String uidPackage : uidPackages) {
17258                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17259                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17260                    if (libIdx >= 0) {
17261                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17262                        versionsCallerCanSee.append(libVersion, libVersion);
17263                    }
17264                }
17265            }
17266        }
17267
17268        // Caller can see nothing - done
17269        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17270            return packageName;
17271        }
17272
17273        // Find the version the caller can see and the app version code
17274        SharedLibraryEntry highestVersion = null;
17275        final int versionCount = versionedLib.size();
17276        for (int i = 0; i < versionCount; i++) {
17277            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17278            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17279                    libEntry.info.getVersion()) < 0) {
17280                continue;
17281            }
17282            // TODO: We will change version code to long, so in the new API it is long
17283            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17284            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17285                if (libVersionCode == versionCode) {
17286                    return libEntry.apk;
17287                }
17288            } else if (highestVersion == null) {
17289                highestVersion = libEntry;
17290            } else if (libVersionCode  > highestVersion.info
17291                    .getDeclaringPackage().getVersionCode()) {
17292                highestVersion = libEntry;
17293            }
17294        }
17295
17296        if (highestVersion != null) {
17297            return highestVersion.apk;
17298        }
17299
17300        return packageName;
17301    }
17302
17303    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17304        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17305              || callingUid == Process.SYSTEM_UID) {
17306            return true;
17307        }
17308        final int callingUserId = UserHandle.getUserId(callingUid);
17309        // If the caller installed the pkgName, then allow it to silently uninstall.
17310        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17311            return true;
17312        }
17313
17314        // Allow package verifier to silently uninstall.
17315        if (mRequiredVerifierPackage != null &&
17316                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17317            return true;
17318        }
17319
17320        // Allow package uninstaller to silently uninstall.
17321        if (mRequiredUninstallerPackage != null &&
17322                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17323            return true;
17324        }
17325
17326        // Allow storage manager to silently uninstall.
17327        if (mStorageManagerPackage != null &&
17328                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17329            return true;
17330        }
17331        return false;
17332    }
17333
17334    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17335        int[] result = EMPTY_INT_ARRAY;
17336        for (int userId : userIds) {
17337            if (getBlockUninstallForUser(packageName, userId)) {
17338                result = ArrayUtils.appendInt(result, userId);
17339            }
17340        }
17341        return result;
17342    }
17343
17344    @Override
17345    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17346        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17347    }
17348
17349    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17350        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17351                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17352        try {
17353            if (dpm != null) {
17354                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17355                        /* callingUserOnly =*/ false);
17356                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17357                        : deviceOwnerComponentName.getPackageName();
17358                // Does the package contains the device owner?
17359                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17360                // this check is probably not needed, since DO should be registered as a device
17361                // admin on some user too. (Original bug for this: b/17657954)
17362                if (packageName.equals(deviceOwnerPackageName)) {
17363                    return true;
17364                }
17365                // Does it contain a device admin for any user?
17366                int[] users;
17367                if (userId == UserHandle.USER_ALL) {
17368                    users = sUserManager.getUserIds();
17369                } else {
17370                    users = new int[]{userId};
17371                }
17372                for (int i = 0; i < users.length; ++i) {
17373                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17374                        return true;
17375                    }
17376                }
17377            }
17378        } catch (RemoteException e) {
17379        }
17380        return false;
17381    }
17382
17383    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17384        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17385    }
17386
17387    /**
17388     *  This method is an internal method that could be get invoked either
17389     *  to delete an installed package or to clean up a failed installation.
17390     *  After deleting an installed package, a broadcast is sent to notify any
17391     *  listeners that the package has been removed. For cleaning up a failed
17392     *  installation, the broadcast is not necessary since the package's
17393     *  installation wouldn't have sent the initial broadcast either
17394     *  The key steps in deleting a package are
17395     *  deleting the package information in internal structures like mPackages,
17396     *  deleting the packages base directories through installd
17397     *  updating mSettings to reflect current status
17398     *  persisting settings for later use
17399     *  sending a broadcast if necessary
17400     */
17401    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17402        final PackageRemovedInfo info = new PackageRemovedInfo();
17403        final boolean res;
17404
17405        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17406                ? UserHandle.USER_ALL : userId;
17407
17408        if (isPackageDeviceAdmin(packageName, removeUser)) {
17409            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17410            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17411        }
17412
17413        PackageSetting uninstalledPs = null;
17414        PackageParser.Package pkg = null;
17415
17416        // for the uninstall-updates case and restricted profiles, remember the per-
17417        // user handle installed state
17418        int[] allUsers;
17419        synchronized (mPackages) {
17420            uninstalledPs = mSettings.mPackages.get(packageName);
17421            if (uninstalledPs == null) {
17422                Slog.w(TAG, "Not removing non-existent package " + packageName);
17423                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17424            }
17425
17426            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17427                    && uninstalledPs.versionCode != versionCode) {
17428                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17429                        + uninstalledPs.versionCode + " != " + versionCode);
17430                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17431            }
17432
17433            // Static shared libs can be declared by any package, so let us not
17434            // allow removing a package if it provides a lib others depend on.
17435            pkg = mPackages.get(packageName);
17436            if (pkg != null && pkg.staticSharedLibName != null) {
17437                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17438                        pkg.staticSharedLibVersion);
17439                if (libEntry != null) {
17440                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17441                            libEntry.info, 0, userId);
17442                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17443                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17444                                + " hosting lib " + libEntry.info.getName() + " version "
17445                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17446                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17447                    }
17448                }
17449            }
17450
17451            allUsers = sUserManager.getUserIds();
17452            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17453        }
17454
17455        final int freezeUser;
17456        if (isUpdatedSystemApp(uninstalledPs)
17457                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17458            // We're downgrading a system app, which will apply to all users, so
17459            // freeze them all during the downgrade
17460            freezeUser = UserHandle.USER_ALL;
17461        } else {
17462            freezeUser = removeUser;
17463        }
17464
17465        synchronized (mInstallLock) {
17466            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17467            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17468                    deleteFlags, "deletePackageX")) {
17469                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17470                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17471            }
17472            synchronized (mPackages) {
17473                if (res) {
17474                    if (pkg != null) {
17475                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17476                    }
17477                    updateSequenceNumberLP(packageName, info.removedUsers);
17478                }
17479            }
17480        }
17481
17482        if (res) {
17483            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17484            info.sendPackageRemovedBroadcasts(killApp);
17485            info.sendSystemPackageUpdatedBroadcasts();
17486            info.sendSystemPackageAppearedBroadcasts();
17487        }
17488        // Force a gc here.
17489        Runtime.getRuntime().gc();
17490        // Delete the resources here after sending the broadcast to let
17491        // other processes clean up before deleting resources.
17492        if (info.args != null) {
17493            synchronized (mInstallLock) {
17494                info.args.doPostDeleteLI(true);
17495            }
17496        }
17497
17498        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17499    }
17500
17501    class PackageRemovedInfo {
17502        String removedPackage;
17503        int uid = -1;
17504        int removedAppId = -1;
17505        int[] origUsers;
17506        int[] removedUsers = null;
17507        SparseArray<Integer> installReasons;
17508        boolean isRemovedPackageSystemUpdate = false;
17509        boolean isUpdate;
17510        boolean dataRemoved;
17511        boolean removedForAllUsers;
17512        boolean isStaticSharedLib;
17513        // Clean up resources deleted packages.
17514        InstallArgs args = null;
17515        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17516        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17517
17518        void sendPackageRemovedBroadcasts(boolean killApp) {
17519            sendPackageRemovedBroadcastInternal(killApp);
17520            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17521            for (int i = 0; i < childCount; i++) {
17522                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17523                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17524            }
17525        }
17526
17527        void sendSystemPackageUpdatedBroadcasts() {
17528            if (isRemovedPackageSystemUpdate) {
17529                sendSystemPackageUpdatedBroadcastsInternal();
17530                final int childCount = (removedChildPackages != null)
17531                        ? removedChildPackages.size() : 0;
17532                for (int i = 0; i < childCount; i++) {
17533                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17534                    if (childInfo.isRemovedPackageSystemUpdate) {
17535                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17536                    }
17537                }
17538            }
17539        }
17540
17541        void sendSystemPackageAppearedBroadcasts() {
17542            final int packageCount = (appearedChildPackages != null)
17543                    ? appearedChildPackages.size() : 0;
17544            for (int i = 0; i < packageCount; i++) {
17545                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17546                sendPackageAddedForNewUsers(installedInfo.name, true,
17547                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17548            }
17549        }
17550
17551        private void sendSystemPackageUpdatedBroadcastsInternal() {
17552            Bundle extras = new Bundle(2);
17553            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17554            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17555            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17556                    extras, 0, null, null, null);
17557            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17558                    extras, 0, null, null, null);
17559            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17560                    null, 0, removedPackage, null, null);
17561        }
17562
17563        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17564            // Don't send static shared library removal broadcasts as these
17565            // libs are visible only the the apps that depend on them an one
17566            // cannot remove the library if it has a dependency.
17567            if (isStaticSharedLib) {
17568                return;
17569            }
17570            Bundle extras = new Bundle(2);
17571            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17572            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17573            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17574            if (isUpdate || isRemovedPackageSystemUpdate) {
17575                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17576            }
17577            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17578            if (removedPackage != null) {
17579                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17580                        extras, 0, null, null, removedUsers);
17581                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17582                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17583                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17584                            null, null, removedUsers);
17585                }
17586            }
17587            if (removedAppId >= 0) {
17588                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17589                        removedUsers);
17590            }
17591        }
17592    }
17593
17594    /*
17595     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17596     * flag is not set, the data directory is removed as well.
17597     * make sure this flag is set for partially installed apps. If not its meaningless to
17598     * delete a partially installed application.
17599     */
17600    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17601            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17602        String packageName = ps.name;
17603        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17604        // Retrieve object to delete permissions for shared user later on
17605        final PackageParser.Package deletedPkg;
17606        final PackageSetting deletedPs;
17607        // reader
17608        synchronized (mPackages) {
17609            deletedPkg = mPackages.get(packageName);
17610            deletedPs = mSettings.mPackages.get(packageName);
17611            if (outInfo != null) {
17612                outInfo.removedPackage = packageName;
17613                outInfo.isStaticSharedLib = deletedPkg != null
17614                        && deletedPkg.staticSharedLibName != null;
17615                outInfo.removedUsers = deletedPs != null
17616                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17617                        : null;
17618            }
17619        }
17620
17621        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17622
17623        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17624            final PackageParser.Package resolvedPkg;
17625            if (deletedPkg != null) {
17626                resolvedPkg = deletedPkg;
17627            } else {
17628                // We don't have a parsed package when it lives on an ejected
17629                // adopted storage device, so fake something together
17630                resolvedPkg = new PackageParser.Package(ps.name);
17631                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17632            }
17633            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17634                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17635            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17636            if (outInfo != null) {
17637                outInfo.dataRemoved = true;
17638            }
17639            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17640        }
17641
17642        int removedAppId = -1;
17643
17644        // writer
17645        synchronized (mPackages) {
17646            boolean installedStateChanged = false;
17647            if (deletedPs != null) {
17648                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17649                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17650                    clearDefaultBrowserIfNeeded(packageName);
17651                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17652                    removedAppId = mSettings.removePackageLPw(packageName);
17653                    if (outInfo != null) {
17654                        outInfo.removedAppId = removedAppId;
17655                    }
17656                    updatePermissionsLPw(deletedPs.name, null, 0);
17657                    if (deletedPs.sharedUser != null) {
17658                        // Remove permissions associated with package. Since runtime
17659                        // permissions are per user we have to kill the removed package
17660                        // or packages running under the shared user of the removed
17661                        // package if revoking the permissions requested only by the removed
17662                        // package is successful and this causes a change in gids.
17663                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17664                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17665                                    userId);
17666                            if (userIdToKill == UserHandle.USER_ALL
17667                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17668                                // If gids changed for this user, kill all affected packages.
17669                                mHandler.post(new Runnable() {
17670                                    @Override
17671                                    public void run() {
17672                                        // This has to happen with no lock held.
17673                                        killApplication(deletedPs.name, deletedPs.appId,
17674                                                KILL_APP_REASON_GIDS_CHANGED);
17675                                    }
17676                                });
17677                                break;
17678                            }
17679                        }
17680                    }
17681                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17682                }
17683                // make sure to preserve per-user disabled state if this removal was just
17684                // a downgrade of a system app to the factory package
17685                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17686                    if (DEBUG_REMOVE) {
17687                        Slog.d(TAG, "Propagating install state across downgrade");
17688                    }
17689                    for (int userId : allUserHandles) {
17690                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17691                        if (DEBUG_REMOVE) {
17692                            Slog.d(TAG, "    user " + userId + " => " + installed);
17693                        }
17694                        if (installed != ps.getInstalled(userId)) {
17695                            installedStateChanged = true;
17696                        }
17697                        ps.setInstalled(installed, userId);
17698                    }
17699                }
17700            }
17701            // can downgrade to reader
17702            if (writeSettings) {
17703                // Save settings now
17704                mSettings.writeLPr();
17705            }
17706            if (installedStateChanged) {
17707                mSettings.writeKernelMappingLPr(ps);
17708            }
17709        }
17710        if (removedAppId != -1) {
17711            // A user ID was deleted here. Go through all users and remove it
17712            // from KeyStore.
17713            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17714        }
17715    }
17716
17717    static boolean locationIsPrivileged(File path) {
17718        try {
17719            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17720                    .getCanonicalPath();
17721            return path.getCanonicalPath().startsWith(privilegedAppDir);
17722        } catch (IOException e) {
17723            Slog.e(TAG, "Unable to access code path " + path);
17724        }
17725        return false;
17726    }
17727
17728    /*
17729     * Tries to delete system package.
17730     */
17731    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17732            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17733            boolean writeSettings) {
17734        if (deletedPs.parentPackageName != null) {
17735            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17736            return false;
17737        }
17738
17739        final boolean applyUserRestrictions
17740                = (allUserHandles != null) && (outInfo.origUsers != null);
17741        final PackageSetting disabledPs;
17742        // Confirm if the system package has been updated
17743        // An updated system app can be deleted. This will also have to restore
17744        // the system pkg from system partition
17745        // reader
17746        synchronized (mPackages) {
17747            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17748        }
17749
17750        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17751                + " disabledPs=" + disabledPs);
17752
17753        if (disabledPs == null) {
17754            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17755            return false;
17756        } else if (DEBUG_REMOVE) {
17757            Slog.d(TAG, "Deleting system pkg from data partition");
17758        }
17759
17760        if (DEBUG_REMOVE) {
17761            if (applyUserRestrictions) {
17762                Slog.d(TAG, "Remembering install states:");
17763                for (int userId : allUserHandles) {
17764                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17765                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17766                }
17767            }
17768        }
17769
17770        // Delete the updated package
17771        outInfo.isRemovedPackageSystemUpdate = true;
17772        if (outInfo.removedChildPackages != null) {
17773            final int childCount = (deletedPs.childPackageNames != null)
17774                    ? deletedPs.childPackageNames.size() : 0;
17775            for (int i = 0; i < childCount; i++) {
17776                String childPackageName = deletedPs.childPackageNames.get(i);
17777                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17778                        .contains(childPackageName)) {
17779                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17780                            childPackageName);
17781                    if (childInfo != null) {
17782                        childInfo.isRemovedPackageSystemUpdate = true;
17783                    }
17784                }
17785            }
17786        }
17787
17788        if (disabledPs.versionCode < deletedPs.versionCode) {
17789            // Delete data for downgrades
17790            flags &= ~PackageManager.DELETE_KEEP_DATA;
17791        } else {
17792            // Preserve data by setting flag
17793            flags |= PackageManager.DELETE_KEEP_DATA;
17794        }
17795
17796        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17797                outInfo, writeSettings, disabledPs.pkg);
17798        if (!ret) {
17799            return false;
17800        }
17801
17802        // writer
17803        synchronized (mPackages) {
17804            // Reinstate the old system package
17805            enableSystemPackageLPw(disabledPs.pkg);
17806            // Remove any native libraries from the upgraded package.
17807            removeNativeBinariesLI(deletedPs);
17808        }
17809
17810        // Install the system package
17811        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17812        int parseFlags = mDefParseFlags
17813                | PackageParser.PARSE_MUST_BE_APK
17814                | PackageParser.PARSE_IS_SYSTEM
17815                | PackageParser.PARSE_IS_SYSTEM_DIR;
17816        if (locationIsPrivileged(disabledPs.codePath)) {
17817            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17818        }
17819
17820        final PackageParser.Package newPkg;
17821        try {
17822            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17823                0 /* currentTime */, null);
17824        } catch (PackageManagerException e) {
17825            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17826                    + e.getMessage());
17827            return false;
17828        }
17829
17830        try {
17831            // update shared libraries for the newly re-installed system package
17832            updateSharedLibrariesLPr(newPkg, null);
17833        } catch (PackageManagerException e) {
17834            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17835        }
17836
17837        prepareAppDataAfterInstallLIF(newPkg);
17838
17839        // writer
17840        synchronized (mPackages) {
17841            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17842
17843            // Propagate the permissions state as we do not want to drop on the floor
17844            // runtime permissions. The update permissions method below will take
17845            // care of removing obsolete permissions and grant install permissions.
17846            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17847            updatePermissionsLPw(newPkg.packageName, newPkg,
17848                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17849
17850            if (applyUserRestrictions) {
17851                boolean installedStateChanged = false;
17852                if (DEBUG_REMOVE) {
17853                    Slog.d(TAG, "Propagating install state across reinstall");
17854                }
17855                for (int userId : allUserHandles) {
17856                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17857                    if (DEBUG_REMOVE) {
17858                        Slog.d(TAG, "    user " + userId + " => " + installed);
17859                    }
17860                    if (installed != ps.getInstalled(userId)) {
17861                        installedStateChanged = true;
17862                    }
17863                    ps.setInstalled(installed, userId);
17864
17865                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17866                }
17867                // Regardless of writeSettings we need to ensure that this restriction
17868                // state propagation is persisted
17869                mSettings.writeAllUsersPackageRestrictionsLPr();
17870                if (installedStateChanged) {
17871                    mSettings.writeKernelMappingLPr(ps);
17872                }
17873            }
17874            // can downgrade to reader here
17875            if (writeSettings) {
17876                mSettings.writeLPr();
17877            }
17878        }
17879        return true;
17880    }
17881
17882    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17883            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17884            PackageRemovedInfo outInfo, boolean writeSettings,
17885            PackageParser.Package replacingPackage) {
17886        synchronized (mPackages) {
17887            if (outInfo != null) {
17888                outInfo.uid = ps.appId;
17889            }
17890
17891            if (outInfo != null && outInfo.removedChildPackages != null) {
17892                final int childCount = (ps.childPackageNames != null)
17893                        ? ps.childPackageNames.size() : 0;
17894                for (int i = 0; i < childCount; i++) {
17895                    String childPackageName = ps.childPackageNames.get(i);
17896                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17897                    if (childPs == null) {
17898                        return false;
17899                    }
17900                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17901                            childPackageName);
17902                    if (childInfo != null) {
17903                        childInfo.uid = childPs.appId;
17904                    }
17905                }
17906            }
17907        }
17908
17909        // Delete package data from internal structures and also remove data if flag is set
17910        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17911
17912        // Delete the child packages data
17913        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17914        for (int i = 0; i < childCount; i++) {
17915            PackageSetting childPs;
17916            synchronized (mPackages) {
17917                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17918            }
17919            if (childPs != null) {
17920                PackageRemovedInfo childOutInfo = (outInfo != null
17921                        && outInfo.removedChildPackages != null)
17922                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17923                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17924                        && (replacingPackage != null
17925                        && !replacingPackage.hasChildPackage(childPs.name))
17926                        ? flags & ~DELETE_KEEP_DATA : flags;
17927                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17928                        deleteFlags, writeSettings);
17929            }
17930        }
17931
17932        // Delete application code and resources only for parent packages
17933        if (ps.parentPackageName == null) {
17934            if (deleteCodeAndResources && (outInfo != null)) {
17935                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17936                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17937                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17938            }
17939        }
17940
17941        return true;
17942    }
17943
17944    @Override
17945    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17946            int userId) {
17947        mContext.enforceCallingOrSelfPermission(
17948                android.Manifest.permission.DELETE_PACKAGES, null);
17949        synchronized (mPackages) {
17950            PackageSetting ps = mSettings.mPackages.get(packageName);
17951            if (ps == null) {
17952                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17953                return false;
17954            }
17955            // Cannot block uninstall of static shared libs as they are
17956            // considered a part of the using app (emulating static linking).
17957            // Also static libs are installed always on internal storage.
17958            PackageParser.Package pkg = mPackages.get(packageName);
17959            if (pkg != null && pkg.staticSharedLibName != null) {
17960                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17961                        + " providing static shared library: " + pkg.staticSharedLibName);
17962                return false;
17963            }
17964            if (!ps.getInstalled(userId)) {
17965                // Can't block uninstall for an app that is not installed or enabled.
17966                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17967                return false;
17968            }
17969            ps.setBlockUninstall(blockUninstall, userId);
17970            mSettings.writePackageRestrictionsLPr(userId);
17971        }
17972        return true;
17973    }
17974
17975    @Override
17976    public boolean getBlockUninstallForUser(String packageName, int userId) {
17977        synchronized (mPackages) {
17978            PackageSetting ps = mSettings.mPackages.get(packageName);
17979            if (ps == null) {
17980                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17981                return false;
17982            }
17983            return ps.getBlockUninstall(userId);
17984        }
17985    }
17986
17987    @Override
17988    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17989        int callingUid = Binder.getCallingUid();
17990        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17991            throw new SecurityException(
17992                    "setRequiredForSystemUser can only be run by the system or root");
17993        }
17994        synchronized (mPackages) {
17995            PackageSetting ps = mSettings.mPackages.get(packageName);
17996            if (ps == null) {
17997                Log.w(TAG, "Package doesn't exist: " + packageName);
17998                return false;
17999            }
18000            if (systemUserApp) {
18001                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18002            } else {
18003                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18004            }
18005            mSettings.writeLPr();
18006        }
18007        return true;
18008    }
18009
18010    /*
18011     * This method handles package deletion in general
18012     */
18013    private boolean deletePackageLIF(String packageName, UserHandle user,
18014            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18015            PackageRemovedInfo outInfo, boolean writeSettings,
18016            PackageParser.Package replacingPackage) {
18017        if (packageName == null) {
18018            Slog.w(TAG, "Attempt to delete null packageName.");
18019            return false;
18020        }
18021
18022        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18023
18024        PackageSetting ps;
18025        synchronized (mPackages) {
18026            ps = mSettings.mPackages.get(packageName);
18027            if (ps == null) {
18028                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18029                return false;
18030            }
18031
18032            if (ps.parentPackageName != null && (!isSystemApp(ps)
18033                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18034                if (DEBUG_REMOVE) {
18035                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18036                            + ((user == null) ? UserHandle.USER_ALL : user));
18037                }
18038                final int removedUserId = (user != null) ? user.getIdentifier()
18039                        : UserHandle.USER_ALL;
18040                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18041                    return false;
18042                }
18043                markPackageUninstalledForUserLPw(ps, user);
18044                scheduleWritePackageRestrictionsLocked(user);
18045                return true;
18046            }
18047        }
18048
18049        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18050                && user.getIdentifier() != UserHandle.USER_ALL)) {
18051            // The caller is asking that the package only be deleted for a single
18052            // user.  To do this, we just mark its uninstalled state and delete
18053            // its data. If this is a system app, we only allow this to happen if
18054            // they have set the special DELETE_SYSTEM_APP which requests different
18055            // semantics than normal for uninstalling system apps.
18056            markPackageUninstalledForUserLPw(ps, user);
18057
18058            if (!isSystemApp(ps)) {
18059                // Do not uninstall the APK if an app should be cached
18060                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18061                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18062                    // Other user still have this package installed, so all
18063                    // we need to do is clear this user's data and save that
18064                    // it is uninstalled.
18065                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18066                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18067                        return false;
18068                    }
18069                    scheduleWritePackageRestrictionsLocked(user);
18070                    return true;
18071                } else {
18072                    // We need to set it back to 'installed' so the uninstall
18073                    // broadcasts will be sent correctly.
18074                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18075                    ps.setInstalled(true, user.getIdentifier());
18076                    mSettings.writeKernelMappingLPr(ps);
18077                }
18078            } else {
18079                // This is a system app, so we assume that the
18080                // other users still have this package installed, so all
18081                // we need to do is clear this user's data and save that
18082                // it is uninstalled.
18083                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18084                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18085                    return false;
18086                }
18087                scheduleWritePackageRestrictionsLocked(user);
18088                return true;
18089            }
18090        }
18091
18092        // If we are deleting a composite package for all users, keep track
18093        // of result for each child.
18094        if (ps.childPackageNames != null && outInfo != null) {
18095            synchronized (mPackages) {
18096                final int childCount = ps.childPackageNames.size();
18097                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18098                for (int i = 0; i < childCount; i++) {
18099                    String childPackageName = ps.childPackageNames.get(i);
18100                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18101                    childInfo.removedPackage = childPackageName;
18102                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18103                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18104                    if (childPs != null) {
18105                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18106                    }
18107                }
18108            }
18109        }
18110
18111        boolean ret = false;
18112        if (isSystemApp(ps)) {
18113            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18114            // When an updated system application is deleted we delete the existing resources
18115            // as well and fall back to existing code in system partition
18116            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18117        } else {
18118            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18119            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18120                    outInfo, writeSettings, replacingPackage);
18121        }
18122
18123        // Take a note whether we deleted the package for all users
18124        if (outInfo != null) {
18125            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18126            if (outInfo.removedChildPackages != null) {
18127                synchronized (mPackages) {
18128                    final int childCount = outInfo.removedChildPackages.size();
18129                    for (int i = 0; i < childCount; i++) {
18130                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18131                        if (childInfo != null) {
18132                            childInfo.removedForAllUsers = mPackages.get(
18133                                    childInfo.removedPackage) == null;
18134                        }
18135                    }
18136                }
18137            }
18138            // If we uninstalled an update to a system app there may be some
18139            // child packages that appeared as they are declared in the system
18140            // app but were not declared in the update.
18141            if (isSystemApp(ps)) {
18142                synchronized (mPackages) {
18143                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18144                    final int childCount = (updatedPs.childPackageNames != null)
18145                            ? updatedPs.childPackageNames.size() : 0;
18146                    for (int i = 0; i < childCount; i++) {
18147                        String childPackageName = updatedPs.childPackageNames.get(i);
18148                        if (outInfo.removedChildPackages == null
18149                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18150                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18151                            if (childPs == null) {
18152                                continue;
18153                            }
18154                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18155                            installRes.name = childPackageName;
18156                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18157                            installRes.pkg = mPackages.get(childPackageName);
18158                            installRes.uid = childPs.pkg.applicationInfo.uid;
18159                            if (outInfo.appearedChildPackages == null) {
18160                                outInfo.appearedChildPackages = new ArrayMap<>();
18161                            }
18162                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18163                        }
18164                    }
18165                }
18166            }
18167        }
18168
18169        return ret;
18170    }
18171
18172    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18173        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18174                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18175        for (int nextUserId : userIds) {
18176            if (DEBUG_REMOVE) {
18177                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18178            }
18179            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18180                    false /*installed*/,
18181                    true /*stopped*/,
18182                    true /*notLaunched*/,
18183                    false /*hidden*/,
18184                    false /*suspended*/,
18185                    false /*instantApp*/,
18186                    null /*lastDisableAppCaller*/,
18187                    null /*enabledComponents*/,
18188                    null /*disabledComponents*/,
18189                    false /*blockUninstall*/,
18190                    ps.readUserState(nextUserId).domainVerificationStatus,
18191                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18192        }
18193        mSettings.writeKernelMappingLPr(ps);
18194    }
18195
18196    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18197            PackageRemovedInfo outInfo) {
18198        final PackageParser.Package pkg;
18199        synchronized (mPackages) {
18200            pkg = mPackages.get(ps.name);
18201        }
18202
18203        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18204                : new int[] {userId};
18205        for (int nextUserId : userIds) {
18206            if (DEBUG_REMOVE) {
18207                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18208                        + nextUserId);
18209            }
18210
18211            destroyAppDataLIF(pkg, userId,
18212                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18213            destroyAppProfilesLIF(pkg, userId);
18214            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18215            schedulePackageCleaning(ps.name, nextUserId, false);
18216            synchronized (mPackages) {
18217                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18218                    scheduleWritePackageRestrictionsLocked(nextUserId);
18219                }
18220                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18221            }
18222        }
18223
18224        if (outInfo != null) {
18225            outInfo.removedPackage = ps.name;
18226            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18227            outInfo.removedAppId = ps.appId;
18228            outInfo.removedUsers = userIds;
18229        }
18230
18231        return true;
18232    }
18233
18234    private final class ClearStorageConnection implements ServiceConnection {
18235        IMediaContainerService mContainerService;
18236
18237        @Override
18238        public void onServiceConnected(ComponentName name, IBinder service) {
18239            synchronized (this) {
18240                mContainerService = IMediaContainerService.Stub
18241                        .asInterface(Binder.allowBlocking(service));
18242                notifyAll();
18243            }
18244        }
18245
18246        @Override
18247        public void onServiceDisconnected(ComponentName name) {
18248        }
18249    }
18250
18251    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18252        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18253
18254        final boolean mounted;
18255        if (Environment.isExternalStorageEmulated()) {
18256            mounted = true;
18257        } else {
18258            final String status = Environment.getExternalStorageState();
18259
18260            mounted = status.equals(Environment.MEDIA_MOUNTED)
18261                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18262        }
18263
18264        if (!mounted) {
18265            return;
18266        }
18267
18268        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18269        int[] users;
18270        if (userId == UserHandle.USER_ALL) {
18271            users = sUserManager.getUserIds();
18272        } else {
18273            users = new int[] { userId };
18274        }
18275        final ClearStorageConnection conn = new ClearStorageConnection();
18276        if (mContext.bindServiceAsUser(
18277                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18278            try {
18279                for (int curUser : users) {
18280                    long timeout = SystemClock.uptimeMillis() + 5000;
18281                    synchronized (conn) {
18282                        long now;
18283                        while (conn.mContainerService == null &&
18284                                (now = SystemClock.uptimeMillis()) < timeout) {
18285                            try {
18286                                conn.wait(timeout - now);
18287                            } catch (InterruptedException e) {
18288                            }
18289                        }
18290                    }
18291                    if (conn.mContainerService == null) {
18292                        return;
18293                    }
18294
18295                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18296                    clearDirectory(conn.mContainerService,
18297                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18298                    if (allData) {
18299                        clearDirectory(conn.mContainerService,
18300                                userEnv.buildExternalStorageAppDataDirs(packageName));
18301                        clearDirectory(conn.mContainerService,
18302                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18303                    }
18304                }
18305            } finally {
18306                mContext.unbindService(conn);
18307            }
18308        }
18309    }
18310
18311    @Override
18312    public void clearApplicationProfileData(String packageName) {
18313        enforceSystemOrRoot("Only the system can clear all profile data");
18314
18315        final PackageParser.Package pkg;
18316        synchronized (mPackages) {
18317            pkg = mPackages.get(packageName);
18318        }
18319
18320        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18321            synchronized (mInstallLock) {
18322                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18323            }
18324        }
18325    }
18326
18327    @Override
18328    public void clearApplicationUserData(final String packageName,
18329            final IPackageDataObserver observer, final int userId) {
18330        mContext.enforceCallingOrSelfPermission(
18331                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18332
18333        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18334                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18335
18336        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18337            throw new SecurityException("Cannot clear data for a protected package: "
18338                    + packageName);
18339        }
18340        // Queue up an async operation since the package deletion may take a little while.
18341        mHandler.post(new Runnable() {
18342            public void run() {
18343                mHandler.removeCallbacks(this);
18344                final boolean succeeded;
18345                try (PackageFreezer freezer = freezePackage(packageName,
18346                        "clearApplicationUserData")) {
18347                    synchronized (mInstallLock) {
18348                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18349                    }
18350                    clearExternalStorageDataSync(packageName, userId, true);
18351                    synchronized (mPackages) {
18352                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18353                                packageName, userId);
18354                    }
18355                }
18356                if (succeeded) {
18357                    // invoke DeviceStorageMonitor's update method to clear any notifications
18358                    DeviceStorageMonitorInternal dsm = LocalServices
18359                            .getService(DeviceStorageMonitorInternal.class);
18360                    if (dsm != null) {
18361                        dsm.checkMemory();
18362                    }
18363                }
18364                if(observer != null) {
18365                    try {
18366                        observer.onRemoveCompleted(packageName, succeeded);
18367                    } catch (RemoteException e) {
18368                        Log.i(TAG, "Observer no longer exists.");
18369                    }
18370                } //end if observer
18371            } //end run
18372        });
18373    }
18374
18375    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18376        if (packageName == null) {
18377            Slog.w(TAG, "Attempt to delete null packageName.");
18378            return false;
18379        }
18380
18381        // Try finding details about the requested package
18382        PackageParser.Package pkg;
18383        synchronized (mPackages) {
18384            pkg = mPackages.get(packageName);
18385            if (pkg == null) {
18386                final PackageSetting ps = mSettings.mPackages.get(packageName);
18387                if (ps != null) {
18388                    pkg = ps.pkg;
18389                }
18390            }
18391
18392            if (pkg == null) {
18393                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18394                return false;
18395            }
18396
18397            PackageSetting ps = (PackageSetting) pkg.mExtras;
18398            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18399        }
18400
18401        clearAppDataLIF(pkg, userId,
18402                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18403
18404        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18405        removeKeystoreDataIfNeeded(userId, appId);
18406
18407        UserManagerInternal umInternal = getUserManagerInternal();
18408        final int flags;
18409        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18410            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18411        } else if (umInternal.isUserRunning(userId)) {
18412            flags = StorageManager.FLAG_STORAGE_DE;
18413        } else {
18414            flags = 0;
18415        }
18416        prepareAppDataContentsLIF(pkg, userId, flags);
18417
18418        return true;
18419    }
18420
18421    /**
18422     * Reverts user permission state changes (permissions and flags) in
18423     * all packages for a given user.
18424     *
18425     * @param userId The device user for which to do a reset.
18426     */
18427    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18428        final int packageCount = mPackages.size();
18429        for (int i = 0; i < packageCount; i++) {
18430            PackageParser.Package pkg = mPackages.valueAt(i);
18431            PackageSetting ps = (PackageSetting) pkg.mExtras;
18432            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18433        }
18434    }
18435
18436    private void resetNetworkPolicies(int userId) {
18437        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18438    }
18439
18440    /**
18441     * Reverts user permission state changes (permissions and flags).
18442     *
18443     * @param ps The package for which to reset.
18444     * @param userId The device user for which to do a reset.
18445     */
18446    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18447            final PackageSetting ps, final int userId) {
18448        if (ps.pkg == null) {
18449            return;
18450        }
18451
18452        // These are flags that can change base on user actions.
18453        final int userSettableMask = FLAG_PERMISSION_USER_SET
18454                | FLAG_PERMISSION_USER_FIXED
18455                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18456                | FLAG_PERMISSION_REVIEW_REQUIRED;
18457
18458        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18459                | FLAG_PERMISSION_POLICY_FIXED;
18460
18461        boolean writeInstallPermissions = false;
18462        boolean writeRuntimePermissions = false;
18463
18464        final int permissionCount = ps.pkg.requestedPermissions.size();
18465        for (int i = 0; i < permissionCount; i++) {
18466            String permission = ps.pkg.requestedPermissions.get(i);
18467
18468            BasePermission bp = mSettings.mPermissions.get(permission);
18469            if (bp == null) {
18470                continue;
18471            }
18472
18473            // If shared user we just reset the state to which only this app contributed.
18474            if (ps.sharedUser != null) {
18475                boolean used = false;
18476                final int packageCount = ps.sharedUser.packages.size();
18477                for (int j = 0; j < packageCount; j++) {
18478                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18479                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18480                            && pkg.pkg.requestedPermissions.contains(permission)) {
18481                        used = true;
18482                        break;
18483                    }
18484                }
18485                if (used) {
18486                    continue;
18487                }
18488            }
18489
18490            PermissionsState permissionsState = ps.getPermissionsState();
18491
18492            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18493
18494            // Always clear the user settable flags.
18495            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18496                    bp.name) != null;
18497            // If permission review is enabled and this is a legacy app, mark the
18498            // permission as requiring a review as this is the initial state.
18499            int flags = 0;
18500            if (mPermissionReviewRequired
18501                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18502                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18503            }
18504            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18505                if (hasInstallState) {
18506                    writeInstallPermissions = true;
18507                } else {
18508                    writeRuntimePermissions = true;
18509                }
18510            }
18511
18512            // Below is only runtime permission handling.
18513            if (!bp.isRuntime()) {
18514                continue;
18515            }
18516
18517            // Never clobber system or policy.
18518            if ((oldFlags & policyOrSystemFlags) != 0) {
18519                continue;
18520            }
18521
18522            // If this permission was granted by default, make sure it is.
18523            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18524                if (permissionsState.grantRuntimePermission(bp, userId)
18525                        != PERMISSION_OPERATION_FAILURE) {
18526                    writeRuntimePermissions = true;
18527                }
18528            // If permission review is enabled the permissions for a legacy apps
18529            // are represented as constantly granted runtime ones, so don't revoke.
18530            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18531                // Otherwise, reset the permission.
18532                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18533                switch (revokeResult) {
18534                    case PERMISSION_OPERATION_SUCCESS:
18535                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18536                        writeRuntimePermissions = true;
18537                        final int appId = ps.appId;
18538                        mHandler.post(new Runnable() {
18539                            @Override
18540                            public void run() {
18541                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18542                            }
18543                        });
18544                    } break;
18545                }
18546            }
18547        }
18548
18549        // Synchronously write as we are taking permissions away.
18550        if (writeRuntimePermissions) {
18551            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18552        }
18553
18554        // Synchronously write as we are taking permissions away.
18555        if (writeInstallPermissions) {
18556            mSettings.writeLPr();
18557        }
18558    }
18559
18560    /**
18561     * Remove entries from the keystore daemon. Will only remove it if the
18562     * {@code appId} is valid.
18563     */
18564    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18565        if (appId < 0) {
18566            return;
18567        }
18568
18569        final KeyStore keyStore = KeyStore.getInstance();
18570        if (keyStore != null) {
18571            if (userId == UserHandle.USER_ALL) {
18572                for (final int individual : sUserManager.getUserIds()) {
18573                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18574                }
18575            } else {
18576                keyStore.clearUid(UserHandle.getUid(userId, appId));
18577            }
18578        } else {
18579            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18580        }
18581    }
18582
18583    @Override
18584    public void deleteApplicationCacheFiles(final String packageName,
18585            final IPackageDataObserver observer) {
18586        final int userId = UserHandle.getCallingUserId();
18587        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18588    }
18589
18590    @Override
18591    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18592            final IPackageDataObserver observer) {
18593        mContext.enforceCallingOrSelfPermission(
18594                android.Manifest.permission.DELETE_CACHE_FILES, null);
18595        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18596                /* requireFullPermission= */ true, /* checkShell= */ false,
18597                "delete application cache files");
18598
18599        final PackageParser.Package pkg;
18600        synchronized (mPackages) {
18601            pkg = mPackages.get(packageName);
18602        }
18603
18604        // Queue up an async operation since the package deletion may take a little while.
18605        mHandler.post(new Runnable() {
18606            public void run() {
18607                synchronized (mInstallLock) {
18608                    final int flags = StorageManager.FLAG_STORAGE_DE
18609                            | StorageManager.FLAG_STORAGE_CE;
18610                    // We're only clearing cache files, so we don't care if the
18611                    // app is unfrozen and still able to run
18612                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18613                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18614                }
18615                clearExternalStorageDataSync(packageName, userId, false);
18616                if (observer != null) {
18617                    try {
18618                        observer.onRemoveCompleted(packageName, true);
18619                    } catch (RemoteException e) {
18620                        Log.i(TAG, "Observer no longer exists.");
18621                    }
18622                }
18623            }
18624        });
18625    }
18626
18627    @Override
18628    public void getPackageSizeInfo(final String packageName, int userHandle,
18629            final IPackageStatsObserver observer) {
18630        throw new UnsupportedOperationException(
18631                "Shame on you for calling a hidden API. Shame!");
18632    }
18633
18634    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18635        final PackageSetting ps;
18636        synchronized (mPackages) {
18637            ps = mSettings.mPackages.get(packageName);
18638            if (ps == null) {
18639                Slog.w(TAG, "Failed to find settings for " + packageName);
18640                return false;
18641            }
18642        }
18643
18644        final String[] packageNames = { packageName };
18645        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18646        final String[] codePaths = { ps.codePathString };
18647
18648        try {
18649            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18650                    ps.appId, ceDataInodes, codePaths, stats);
18651
18652            // For now, ignore code size of packages on system partition
18653            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18654                stats.codeSize = 0;
18655            }
18656
18657            // External clients expect these to be tracked separately
18658            stats.dataSize -= stats.cacheSize;
18659
18660        } catch (InstallerException e) {
18661            Slog.w(TAG, String.valueOf(e));
18662            return false;
18663        }
18664
18665        return true;
18666    }
18667
18668    private int getUidTargetSdkVersionLockedLPr(int uid) {
18669        Object obj = mSettings.getUserIdLPr(uid);
18670        if (obj instanceof SharedUserSetting) {
18671            final SharedUserSetting sus = (SharedUserSetting) obj;
18672            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18673            final Iterator<PackageSetting> it = sus.packages.iterator();
18674            while (it.hasNext()) {
18675                final PackageSetting ps = it.next();
18676                if (ps.pkg != null) {
18677                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18678                    if (v < vers) vers = v;
18679                }
18680            }
18681            return vers;
18682        } else if (obj instanceof PackageSetting) {
18683            final PackageSetting ps = (PackageSetting) obj;
18684            if (ps.pkg != null) {
18685                return ps.pkg.applicationInfo.targetSdkVersion;
18686            }
18687        }
18688        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18689    }
18690
18691    @Override
18692    public void addPreferredActivity(IntentFilter filter, int match,
18693            ComponentName[] set, ComponentName activity, int userId) {
18694        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18695                "Adding preferred");
18696    }
18697
18698    private void addPreferredActivityInternal(IntentFilter filter, int match,
18699            ComponentName[] set, ComponentName activity, boolean always, int userId,
18700            String opname) {
18701        // writer
18702        int callingUid = Binder.getCallingUid();
18703        enforceCrossUserPermission(callingUid, userId,
18704                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18705        if (filter.countActions() == 0) {
18706            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18707            return;
18708        }
18709        synchronized (mPackages) {
18710            if (mContext.checkCallingOrSelfPermission(
18711                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18712                    != PackageManager.PERMISSION_GRANTED) {
18713                if (getUidTargetSdkVersionLockedLPr(callingUid)
18714                        < Build.VERSION_CODES.FROYO) {
18715                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18716                            + callingUid);
18717                    return;
18718                }
18719                mContext.enforceCallingOrSelfPermission(
18720                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18721            }
18722
18723            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18724            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18725                    + userId + ":");
18726            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18727            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18728            scheduleWritePackageRestrictionsLocked(userId);
18729            postPreferredActivityChangedBroadcast(userId);
18730        }
18731    }
18732
18733    private void postPreferredActivityChangedBroadcast(int userId) {
18734        mHandler.post(() -> {
18735            final IActivityManager am = ActivityManager.getService();
18736            if (am == null) {
18737                return;
18738            }
18739
18740            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18741            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18742            try {
18743                am.broadcastIntent(null, intent, null, null,
18744                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18745                        null, false, false, userId);
18746            } catch (RemoteException e) {
18747            }
18748        });
18749    }
18750
18751    @Override
18752    public void replacePreferredActivity(IntentFilter filter, int match,
18753            ComponentName[] set, ComponentName activity, int userId) {
18754        if (filter.countActions() != 1) {
18755            throw new IllegalArgumentException(
18756                    "replacePreferredActivity expects filter to have only 1 action.");
18757        }
18758        if (filter.countDataAuthorities() != 0
18759                || filter.countDataPaths() != 0
18760                || filter.countDataSchemes() > 1
18761                || filter.countDataTypes() != 0) {
18762            throw new IllegalArgumentException(
18763                    "replacePreferredActivity expects filter to have no data authorities, " +
18764                    "paths, or types; and at most one scheme.");
18765        }
18766
18767        final int callingUid = Binder.getCallingUid();
18768        enforceCrossUserPermission(callingUid, userId,
18769                true /* requireFullPermission */, false /* checkShell */,
18770                "replace preferred activity");
18771        synchronized (mPackages) {
18772            if (mContext.checkCallingOrSelfPermission(
18773                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18774                    != PackageManager.PERMISSION_GRANTED) {
18775                if (getUidTargetSdkVersionLockedLPr(callingUid)
18776                        < Build.VERSION_CODES.FROYO) {
18777                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18778                            + Binder.getCallingUid());
18779                    return;
18780                }
18781                mContext.enforceCallingOrSelfPermission(
18782                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18783            }
18784
18785            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18786            if (pir != null) {
18787                // Get all of the existing entries that exactly match this filter.
18788                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18789                if (existing != null && existing.size() == 1) {
18790                    PreferredActivity cur = existing.get(0);
18791                    if (DEBUG_PREFERRED) {
18792                        Slog.i(TAG, "Checking replace of preferred:");
18793                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18794                        if (!cur.mPref.mAlways) {
18795                            Slog.i(TAG, "  -- CUR; not mAlways!");
18796                        } else {
18797                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18798                            Slog.i(TAG, "  -- CUR: mSet="
18799                                    + Arrays.toString(cur.mPref.mSetComponents));
18800                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18801                            Slog.i(TAG, "  -- NEW: mMatch="
18802                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18803                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18804                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18805                        }
18806                    }
18807                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18808                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18809                            && cur.mPref.sameSet(set)) {
18810                        // Setting the preferred activity to what it happens to be already
18811                        if (DEBUG_PREFERRED) {
18812                            Slog.i(TAG, "Replacing with same preferred activity "
18813                                    + cur.mPref.mShortComponent + " for user "
18814                                    + userId + ":");
18815                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18816                        }
18817                        return;
18818                    }
18819                }
18820
18821                if (existing != null) {
18822                    if (DEBUG_PREFERRED) {
18823                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18824                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18825                    }
18826                    for (int i = 0; i < existing.size(); i++) {
18827                        PreferredActivity pa = existing.get(i);
18828                        if (DEBUG_PREFERRED) {
18829                            Slog.i(TAG, "Removing existing preferred activity "
18830                                    + pa.mPref.mComponent + ":");
18831                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18832                        }
18833                        pir.removeFilter(pa);
18834                    }
18835                }
18836            }
18837            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18838                    "Replacing preferred");
18839        }
18840    }
18841
18842    @Override
18843    public void clearPackagePreferredActivities(String packageName) {
18844        final int uid = Binder.getCallingUid();
18845        // writer
18846        synchronized (mPackages) {
18847            PackageParser.Package pkg = mPackages.get(packageName);
18848            if (pkg == null || pkg.applicationInfo.uid != uid) {
18849                if (mContext.checkCallingOrSelfPermission(
18850                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18851                        != PackageManager.PERMISSION_GRANTED) {
18852                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18853                            < Build.VERSION_CODES.FROYO) {
18854                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18855                                + Binder.getCallingUid());
18856                        return;
18857                    }
18858                    mContext.enforceCallingOrSelfPermission(
18859                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18860                }
18861            }
18862
18863            int user = UserHandle.getCallingUserId();
18864            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18865                scheduleWritePackageRestrictionsLocked(user);
18866            }
18867        }
18868    }
18869
18870    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18871    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18872        ArrayList<PreferredActivity> removed = null;
18873        boolean changed = false;
18874        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18875            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18876            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18877            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18878                continue;
18879            }
18880            Iterator<PreferredActivity> it = pir.filterIterator();
18881            while (it.hasNext()) {
18882                PreferredActivity pa = it.next();
18883                // Mark entry for removal only if it matches the package name
18884                // and the entry is of type "always".
18885                if (packageName == null ||
18886                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18887                                && pa.mPref.mAlways)) {
18888                    if (removed == null) {
18889                        removed = new ArrayList<PreferredActivity>();
18890                    }
18891                    removed.add(pa);
18892                }
18893            }
18894            if (removed != null) {
18895                for (int j=0; j<removed.size(); j++) {
18896                    PreferredActivity pa = removed.get(j);
18897                    pir.removeFilter(pa);
18898                }
18899                changed = true;
18900            }
18901        }
18902        if (changed) {
18903            postPreferredActivityChangedBroadcast(userId);
18904        }
18905        return changed;
18906    }
18907
18908    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18909    private void clearIntentFilterVerificationsLPw(int userId) {
18910        final int packageCount = mPackages.size();
18911        for (int i = 0; i < packageCount; i++) {
18912            PackageParser.Package pkg = mPackages.valueAt(i);
18913            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18914        }
18915    }
18916
18917    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18918    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18919        if (userId == UserHandle.USER_ALL) {
18920            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18921                    sUserManager.getUserIds())) {
18922                for (int oneUserId : sUserManager.getUserIds()) {
18923                    scheduleWritePackageRestrictionsLocked(oneUserId);
18924                }
18925            }
18926        } else {
18927            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18928                scheduleWritePackageRestrictionsLocked(userId);
18929            }
18930        }
18931    }
18932
18933    void clearDefaultBrowserIfNeeded(String packageName) {
18934        for (int oneUserId : sUserManager.getUserIds()) {
18935            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18936            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18937            if (packageName.equals(defaultBrowserPackageName)) {
18938                setDefaultBrowserPackageName(null, oneUserId);
18939            }
18940        }
18941    }
18942
18943    @Override
18944    public void resetApplicationPreferences(int userId) {
18945        mContext.enforceCallingOrSelfPermission(
18946                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18947        final long identity = Binder.clearCallingIdentity();
18948        // writer
18949        try {
18950            synchronized (mPackages) {
18951                clearPackagePreferredActivitiesLPw(null, userId);
18952                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18953                // TODO: We have to reset the default SMS and Phone. This requires
18954                // significant refactoring to keep all default apps in the package
18955                // manager (cleaner but more work) or have the services provide
18956                // callbacks to the package manager to request a default app reset.
18957                applyFactoryDefaultBrowserLPw(userId);
18958                clearIntentFilterVerificationsLPw(userId);
18959                primeDomainVerificationsLPw(userId);
18960                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18961                scheduleWritePackageRestrictionsLocked(userId);
18962            }
18963            resetNetworkPolicies(userId);
18964        } finally {
18965            Binder.restoreCallingIdentity(identity);
18966        }
18967    }
18968
18969    @Override
18970    public int getPreferredActivities(List<IntentFilter> outFilters,
18971            List<ComponentName> outActivities, String packageName) {
18972
18973        int num = 0;
18974        final int userId = UserHandle.getCallingUserId();
18975        // reader
18976        synchronized (mPackages) {
18977            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18978            if (pir != null) {
18979                final Iterator<PreferredActivity> it = pir.filterIterator();
18980                while (it.hasNext()) {
18981                    final PreferredActivity pa = it.next();
18982                    if (packageName == null
18983                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18984                                    && pa.mPref.mAlways)) {
18985                        if (outFilters != null) {
18986                            outFilters.add(new IntentFilter(pa));
18987                        }
18988                        if (outActivities != null) {
18989                            outActivities.add(pa.mPref.mComponent);
18990                        }
18991                    }
18992                }
18993            }
18994        }
18995
18996        return num;
18997    }
18998
18999    @Override
19000    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19001            int userId) {
19002        int callingUid = Binder.getCallingUid();
19003        if (callingUid != Process.SYSTEM_UID) {
19004            throw new SecurityException(
19005                    "addPersistentPreferredActivity can only be run by the system");
19006        }
19007        if (filter.countActions() == 0) {
19008            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19009            return;
19010        }
19011        synchronized (mPackages) {
19012            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19013                    ":");
19014            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19015            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19016                    new PersistentPreferredActivity(filter, activity));
19017            scheduleWritePackageRestrictionsLocked(userId);
19018            postPreferredActivityChangedBroadcast(userId);
19019        }
19020    }
19021
19022    @Override
19023    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19024        int callingUid = Binder.getCallingUid();
19025        if (callingUid != Process.SYSTEM_UID) {
19026            throw new SecurityException(
19027                    "clearPackagePersistentPreferredActivities can only be run by the system");
19028        }
19029        ArrayList<PersistentPreferredActivity> removed = null;
19030        boolean changed = false;
19031        synchronized (mPackages) {
19032            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19033                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19034                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19035                        .valueAt(i);
19036                if (userId != thisUserId) {
19037                    continue;
19038                }
19039                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19040                while (it.hasNext()) {
19041                    PersistentPreferredActivity ppa = it.next();
19042                    // Mark entry for removal only if it matches the package name.
19043                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19044                        if (removed == null) {
19045                            removed = new ArrayList<PersistentPreferredActivity>();
19046                        }
19047                        removed.add(ppa);
19048                    }
19049                }
19050                if (removed != null) {
19051                    for (int j=0; j<removed.size(); j++) {
19052                        PersistentPreferredActivity ppa = removed.get(j);
19053                        ppir.removeFilter(ppa);
19054                    }
19055                    changed = true;
19056                }
19057            }
19058
19059            if (changed) {
19060                scheduleWritePackageRestrictionsLocked(userId);
19061                postPreferredActivityChangedBroadcast(userId);
19062            }
19063        }
19064    }
19065
19066    /**
19067     * Common machinery for picking apart a restored XML blob and passing
19068     * it to a caller-supplied functor to be applied to the running system.
19069     */
19070    private void restoreFromXml(XmlPullParser parser, int userId,
19071            String expectedStartTag, BlobXmlRestorer functor)
19072            throws IOException, XmlPullParserException {
19073        int type;
19074        while ((type = parser.next()) != XmlPullParser.START_TAG
19075                && type != XmlPullParser.END_DOCUMENT) {
19076        }
19077        if (type != XmlPullParser.START_TAG) {
19078            // oops didn't find a start tag?!
19079            if (DEBUG_BACKUP) {
19080                Slog.e(TAG, "Didn't find start tag during restore");
19081            }
19082            return;
19083        }
19084Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19085        // this is supposed to be TAG_PREFERRED_BACKUP
19086        if (!expectedStartTag.equals(parser.getName())) {
19087            if (DEBUG_BACKUP) {
19088                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19089            }
19090            return;
19091        }
19092
19093        // skip interfering stuff, then we're aligned with the backing implementation
19094        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19095Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19096        functor.apply(parser, userId);
19097    }
19098
19099    private interface BlobXmlRestorer {
19100        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19101    }
19102
19103    /**
19104     * Non-Binder method, support for the backup/restore mechanism: write the
19105     * full set of preferred activities in its canonical XML format.  Returns the
19106     * XML output as a byte array, or null if there is none.
19107     */
19108    @Override
19109    public byte[] getPreferredActivityBackup(int userId) {
19110        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19111            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19112        }
19113
19114        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19115        try {
19116            final XmlSerializer serializer = new FastXmlSerializer();
19117            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19118            serializer.startDocument(null, true);
19119            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19120
19121            synchronized (mPackages) {
19122                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19123            }
19124
19125            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19126            serializer.endDocument();
19127            serializer.flush();
19128        } catch (Exception e) {
19129            if (DEBUG_BACKUP) {
19130                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19131            }
19132            return null;
19133        }
19134
19135        return dataStream.toByteArray();
19136    }
19137
19138    @Override
19139    public void restorePreferredActivities(byte[] backup, int userId) {
19140        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19141            throw new SecurityException("Only the system may call restorePreferredActivities()");
19142        }
19143
19144        try {
19145            final XmlPullParser parser = Xml.newPullParser();
19146            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19147            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19148                    new BlobXmlRestorer() {
19149                        @Override
19150                        public void apply(XmlPullParser parser, int userId)
19151                                throws XmlPullParserException, IOException {
19152                            synchronized (mPackages) {
19153                                mSettings.readPreferredActivitiesLPw(parser, userId);
19154                            }
19155                        }
19156                    } );
19157        } catch (Exception e) {
19158            if (DEBUG_BACKUP) {
19159                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19160            }
19161        }
19162    }
19163
19164    /**
19165     * Non-Binder method, support for the backup/restore mechanism: write the
19166     * default browser (etc) settings in its canonical XML format.  Returns the default
19167     * browser XML representation as a byte array, or null if there is none.
19168     */
19169    @Override
19170    public byte[] getDefaultAppsBackup(int userId) {
19171        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19172            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19173        }
19174
19175        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19176        try {
19177            final XmlSerializer serializer = new FastXmlSerializer();
19178            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19179            serializer.startDocument(null, true);
19180            serializer.startTag(null, TAG_DEFAULT_APPS);
19181
19182            synchronized (mPackages) {
19183                mSettings.writeDefaultAppsLPr(serializer, userId);
19184            }
19185
19186            serializer.endTag(null, TAG_DEFAULT_APPS);
19187            serializer.endDocument();
19188            serializer.flush();
19189        } catch (Exception e) {
19190            if (DEBUG_BACKUP) {
19191                Slog.e(TAG, "Unable to write default apps for backup", e);
19192            }
19193            return null;
19194        }
19195
19196        return dataStream.toByteArray();
19197    }
19198
19199    @Override
19200    public void restoreDefaultApps(byte[] backup, int userId) {
19201        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19202            throw new SecurityException("Only the system may call restoreDefaultApps()");
19203        }
19204
19205        try {
19206            final XmlPullParser parser = Xml.newPullParser();
19207            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19208            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19209                    new BlobXmlRestorer() {
19210                        @Override
19211                        public void apply(XmlPullParser parser, int userId)
19212                                throws XmlPullParserException, IOException {
19213                            synchronized (mPackages) {
19214                                mSettings.readDefaultAppsLPw(parser, userId);
19215                            }
19216                        }
19217                    } );
19218        } catch (Exception e) {
19219            if (DEBUG_BACKUP) {
19220                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19221            }
19222        }
19223    }
19224
19225    @Override
19226    public byte[] getIntentFilterVerificationBackup(int userId) {
19227        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19228            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19229        }
19230
19231        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19232        try {
19233            final XmlSerializer serializer = new FastXmlSerializer();
19234            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19235            serializer.startDocument(null, true);
19236            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19237
19238            synchronized (mPackages) {
19239                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19240            }
19241
19242            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19243            serializer.endDocument();
19244            serializer.flush();
19245        } catch (Exception e) {
19246            if (DEBUG_BACKUP) {
19247                Slog.e(TAG, "Unable to write default apps for backup", e);
19248            }
19249            return null;
19250        }
19251
19252        return dataStream.toByteArray();
19253    }
19254
19255    @Override
19256    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19257        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19258            throw new SecurityException("Only the system may call restorePreferredActivities()");
19259        }
19260
19261        try {
19262            final XmlPullParser parser = Xml.newPullParser();
19263            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19264            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19265                    new BlobXmlRestorer() {
19266                        @Override
19267                        public void apply(XmlPullParser parser, int userId)
19268                                throws XmlPullParserException, IOException {
19269                            synchronized (mPackages) {
19270                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19271                                mSettings.writeLPr();
19272                            }
19273                        }
19274                    } );
19275        } catch (Exception e) {
19276            if (DEBUG_BACKUP) {
19277                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19278            }
19279        }
19280    }
19281
19282    @Override
19283    public byte[] getPermissionGrantBackup(int userId) {
19284        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19285            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19286        }
19287
19288        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19289        try {
19290            final XmlSerializer serializer = new FastXmlSerializer();
19291            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19292            serializer.startDocument(null, true);
19293            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19294
19295            synchronized (mPackages) {
19296                serializeRuntimePermissionGrantsLPr(serializer, userId);
19297            }
19298
19299            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19300            serializer.endDocument();
19301            serializer.flush();
19302        } catch (Exception e) {
19303            if (DEBUG_BACKUP) {
19304                Slog.e(TAG, "Unable to write default apps for backup", e);
19305            }
19306            return null;
19307        }
19308
19309        return dataStream.toByteArray();
19310    }
19311
19312    @Override
19313    public void restorePermissionGrants(byte[] backup, int userId) {
19314        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19315            throw new SecurityException("Only the system may call restorePermissionGrants()");
19316        }
19317
19318        try {
19319            final XmlPullParser parser = Xml.newPullParser();
19320            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19321            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19322                    new BlobXmlRestorer() {
19323                        @Override
19324                        public void apply(XmlPullParser parser, int userId)
19325                                throws XmlPullParserException, IOException {
19326                            synchronized (mPackages) {
19327                                processRestoredPermissionGrantsLPr(parser, userId);
19328                            }
19329                        }
19330                    } );
19331        } catch (Exception e) {
19332            if (DEBUG_BACKUP) {
19333                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19334            }
19335        }
19336    }
19337
19338    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19339            throws IOException {
19340        serializer.startTag(null, TAG_ALL_GRANTS);
19341
19342        final int N = mSettings.mPackages.size();
19343        for (int i = 0; i < N; i++) {
19344            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19345            boolean pkgGrantsKnown = false;
19346
19347            PermissionsState packagePerms = ps.getPermissionsState();
19348
19349            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19350                final int grantFlags = state.getFlags();
19351                // only look at grants that are not system/policy fixed
19352                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19353                    final boolean isGranted = state.isGranted();
19354                    // And only back up the user-twiddled state bits
19355                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19356                        final String packageName = mSettings.mPackages.keyAt(i);
19357                        if (!pkgGrantsKnown) {
19358                            serializer.startTag(null, TAG_GRANT);
19359                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19360                            pkgGrantsKnown = true;
19361                        }
19362
19363                        final boolean userSet =
19364                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19365                        final boolean userFixed =
19366                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19367                        final boolean revoke =
19368                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19369
19370                        serializer.startTag(null, TAG_PERMISSION);
19371                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19372                        if (isGranted) {
19373                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19374                        }
19375                        if (userSet) {
19376                            serializer.attribute(null, ATTR_USER_SET, "true");
19377                        }
19378                        if (userFixed) {
19379                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19380                        }
19381                        if (revoke) {
19382                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19383                        }
19384                        serializer.endTag(null, TAG_PERMISSION);
19385                    }
19386                }
19387            }
19388
19389            if (pkgGrantsKnown) {
19390                serializer.endTag(null, TAG_GRANT);
19391            }
19392        }
19393
19394        serializer.endTag(null, TAG_ALL_GRANTS);
19395    }
19396
19397    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19398            throws XmlPullParserException, IOException {
19399        String pkgName = null;
19400        int outerDepth = parser.getDepth();
19401        int type;
19402        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19403                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19404            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19405                continue;
19406            }
19407
19408            final String tagName = parser.getName();
19409            if (tagName.equals(TAG_GRANT)) {
19410                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19411                if (DEBUG_BACKUP) {
19412                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19413                }
19414            } else if (tagName.equals(TAG_PERMISSION)) {
19415
19416                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19417                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19418
19419                int newFlagSet = 0;
19420                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19421                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19422                }
19423                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19424                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19425                }
19426                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19427                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19428                }
19429                if (DEBUG_BACKUP) {
19430                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19431                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19432                }
19433                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19434                if (ps != null) {
19435                    // Already installed so we apply the grant immediately
19436                    if (DEBUG_BACKUP) {
19437                        Slog.v(TAG, "        + already installed; applying");
19438                    }
19439                    PermissionsState perms = ps.getPermissionsState();
19440                    BasePermission bp = mSettings.mPermissions.get(permName);
19441                    if (bp != null) {
19442                        if (isGranted) {
19443                            perms.grantRuntimePermission(bp, userId);
19444                        }
19445                        if (newFlagSet != 0) {
19446                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19447                        }
19448                    }
19449                } else {
19450                    // Need to wait for post-restore install to apply the grant
19451                    if (DEBUG_BACKUP) {
19452                        Slog.v(TAG, "        - not yet installed; saving for later");
19453                    }
19454                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19455                            isGranted, newFlagSet, userId);
19456                }
19457            } else {
19458                PackageManagerService.reportSettingsProblem(Log.WARN,
19459                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19460                XmlUtils.skipCurrentTag(parser);
19461            }
19462        }
19463
19464        scheduleWriteSettingsLocked();
19465        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19466    }
19467
19468    @Override
19469    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19470            int sourceUserId, int targetUserId, int flags) {
19471        mContext.enforceCallingOrSelfPermission(
19472                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19473        int callingUid = Binder.getCallingUid();
19474        enforceOwnerRights(ownerPackage, callingUid);
19475        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19476        if (intentFilter.countActions() == 0) {
19477            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19478            return;
19479        }
19480        synchronized (mPackages) {
19481            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19482                    ownerPackage, targetUserId, flags);
19483            CrossProfileIntentResolver resolver =
19484                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19485            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19486            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19487            if (existing != null) {
19488                int size = existing.size();
19489                for (int i = 0; i < size; i++) {
19490                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19491                        return;
19492                    }
19493                }
19494            }
19495            resolver.addFilter(newFilter);
19496            scheduleWritePackageRestrictionsLocked(sourceUserId);
19497        }
19498    }
19499
19500    @Override
19501    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19502        mContext.enforceCallingOrSelfPermission(
19503                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19504        int callingUid = Binder.getCallingUid();
19505        enforceOwnerRights(ownerPackage, callingUid);
19506        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19507        synchronized (mPackages) {
19508            CrossProfileIntentResolver resolver =
19509                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19510            ArraySet<CrossProfileIntentFilter> set =
19511                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19512            for (CrossProfileIntentFilter filter : set) {
19513                if (filter.getOwnerPackage().equals(ownerPackage)) {
19514                    resolver.removeFilter(filter);
19515                }
19516            }
19517            scheduleWritePackageRestrictionsLocked(sourceUserId);
19518        }
19519    }
19520
19521    // Enforcing that callingUid is owning pkg on userId
19522    private void enforceOwnerRights(String pkg, int callingUid) {
19523        // The system owns everything.
19524        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19525            return;
19526        }
19527        int callingUserId = UserHandle.getUserId(callingUid);
19528        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19529        if (pi == null) {
19530            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19531                    + callingUserId);
19532        }
19533        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19534            throw new SecurityException("Calling uid " + callingUid
19535                    + " does not own package " + pkg);
19536        }
19537    }
19538
19539    @Override
19540    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19541        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19542    }
19543
19544    /**
19545     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19546     * then reports the most likely home activity or null if there are more than one.
19547     */
19548    public ComponentName getDefaultHomeActivity(int userId) {
19549        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19550        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19551        if (cn != null) {
19552            return cn;
19553        }
19554
19555        // Find the launcher with the highest priority and return that component if there are no
19556        // other home activity with the same priority.
19557        int lastPriority = Integer.MIN_VALUE;
19558        ComponentName lastComponent = null;
19559        final int size = allHomeCandidates.size();
19560        for (int i = 0; i < size; i++) {
19561            final ResolveInfo ri = allHomeCandidates.get(i);
19562            if (ri.priority > lastPriority) {
19563                lastComponent = ri.activityInfo.getComponentName();
19564                lastPriority = ri.priority;
19565            } else if (ri.priority == lastPriority) {
19566                // Two components found with same priority.
19567                lastComponent = null;
19568            }
19569        }
19570        return lastComponent;
19571    }
19572
19573    private Intent getHomeIntent() {
19574        Intent intent = new Intent(Intent.ACTION_MAIN);
19575        intent.addCategory(Intent.CATEGORY_HOME);
19576        intent.addCategory(Intent.CATEGORY_DEFAULT);
19577        return intent;
19578    }
19579
19580    private IntentFilter getHomeFilter() {
19581        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19582        filter.addCategory(Intent.CATEGORY_HOME);
19583        filter.addCategory(Intent.CATEGORY_DEFAULT);
19584        return filter;
19585    }
19586
19587    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19588            int userId) {
19589        Intent intent  = getHomeIntent();
19590        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19591                PackageManager.GET_META_DATA, userId);
19592        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19593                true, false, false, userId);
19594
19595        allHomeCandidates.clear();
19596        if (list != null) {
19597            for (ResolveInfo ri : list) {
19598                allHomeCandidates.add(ri);
19599            }
19600        }
19601        return (preferred == null || preferred.activityInfo == null)
19602                ? null
19603                : new ComponentName(preferred.activityInfo.packageName,
19604                        preferred.activityInfo.name);
19605    }
19606
19607    @Override
19608    public void setHomeActivity(ComponentName comp, int userId) {
19609        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19610        getHomeActivitiesAsUser(homeActivities, userId);
19611
19612        boolean found = false;
19613
19614        final int size = homeActivities.size();
19615        final ComponentName[] set = new ComponentName[size];
19616        for (int i = 0; i < size; i++) {
19617            final ResolveInfo candidate = homeActivities.get(i);
19618            final ActivityInfo info = candidate.activityInfo;
19619            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19620            set[i] = activityName;
19621            if (!found && activityName.equals(comp)) {
19622                found = true;
19623            }
19624        }
19625        if (!found) {
19626            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19627                    + userId);
19628        }
19629        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19630                set, comp, userId);
19631    }
19632
19633    private @Nullable String getSetupWizardPackageName() {
19634        final Intent intent = new Intent(Intent.ACTION_MAIN);
19635        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19636
19637        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19638                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19639                        | MATCH_DISABLED_COMPONENTS,
19640                UserHandle.myUserId());
19641        if (matches.size() == 1) {
19642            return matches.get(0).getComponentInfo().packageName;
19643        } else {
19644            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19645                    + ": matches=" + matches);
19646            return null;
19647        }
19648    }
19649
19650    private @Nullable String getStorageManagerPackageName() {
19651        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19652
19653        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19654                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19655                        | MATCH_DISABLED_COMPONENTS,
19656                UserHandle.myUserId());
19657        if (matches.size() == 1) {
19658            return matches.get(0).getComponentInfo().packageName;
19659        } else {
19660            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19661                    + matches.size() + ": matches=" + matches);
19662            return null;
19663        }
19664    }
19665
19666    @Override
19667    public void setApplicationEnabledSetting(String appPackageName,
19668            int newState, int flags, int userId, String callingPackage) {
19669        if (!sUserManager.exists(userId)) return;
19670        if (callingPackage == null) {
19671            callingPackage = Integer.toString(Binder.getCallingUid());
19672        }
19673        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19674    }
19675
19676    @Override
19677    public void setComponentEnabledSetting(ComponentName componentName,
19678            int newState, int flags, int userId) {
19679        if (!sUserManager.exists(userId)) return;
19680        setEnabledSetting(componentName.getPackageName(),
19681                componentName.getClassName(), newState, flags, userId, null);
19682    }
19683
19684    private void setEnabledSetting(final String packageName, String className, int newState,
19685            final int flags, int userId, String callingPackage) {
19686        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19687              || newState == COMPONENT_ENABLED_STATE_ENABLED
19688              || newState == COMPONENT_ENABLED_STATE_DISABLED
19689              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19690              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19691            throw new IllegalArgumentException("Invalid new component state: "
19692                    + newState);
19693        }
19694        PackageSetting pkgSetting;
19695        final int uid = Binder.getCallingUid();
19696        final int permission;
19697        if (uid == Process.SYSTEM_UID) {
19698            permission = PackageManager.PERMISSION_GRANTED;
19699        } else {
19700            permission = mContext.checkCallingOrSelfPermission(
19701                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19702        }
19703        enforceCrossUserPermission(uid, userId,
19704                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19705        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19706        boolean sendNow = false;
19707        boolean isApp = (className == null);
19708        String componentName = isApp ? packageName : className;
19709        int packageUid = -1;
19710        ArrayList<String> components;
19711
19712        // writer
19713        synchronized (mPackages) {
19714            pkgSetting = mSettings.mPackages.get(packageName);
19715            if (pkgSetting == null) {
19716                if (className == null) {
19717                    throw new IllegalArgumentException("Unknown package: " + packageName);
19718                }
19719                throw new IllegalArgumentException(
19720                        "Unknown component: " + packageName + "/" + className);
19721            }
19722        }
19723
19724        // Limit who can change which apps
19725        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19726            // Don't allow apps that don't have permission to modify other apps
19727            if (!allowedByPermission) {
19728                throw new SecurityException(
19729                        "Permission Denial: attempt to change component state from pid="
19730                        + Binder.getCallingPid()
19731                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19732            }
19733            // Don't allow changing protected packages.
19734            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19735                throw new SecurityException("Cannot disable a protected package: " + packageName);
19736            }
19737        }
19738
19739        synchronized (mPackages) {
19740            if (uid == Process.SHELL_UID
19741                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19742                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19743                // unless it is a test package.
19744                int oldState = pkgSetting.getEnabled(userId);
19745                if (className == null
19746                    &&
19747                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19748                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19749                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19750                    &&
19751                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19752                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19753                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19754                    // ok
19755                } else {
19756                    throw new SecurityException(
19757                            "Shell cannot change component state for " + packageName + "/"
19758                            + className + " to " + newState);
19759                }
19760            }
19761            if (className == null) {
19762                // We're dealing with an application/package level state change
19763                if (pkgSetting.getEnabled(userId) == newState) {
19764                    // Nothing to do
19765                    return;
19766                }
19767                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19768                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19769                    // Don't care about who enables an app.
19770                    callingPackage = null;
19771                }
19772                pkgSetting.setEnabled(newState, userId, callingPackage);
19773                // pkgSetting.pkg.mSetEnabled = newState;
19774            } else {
19775                // We're dealing with a component level state change
19776                // First, verify that this is a valid class name.
19777                PackageParser.Package pkg = pkgSetting.pkg;
19778                if (pkg == null || !pkg.hasComponentClassName(className)) {
19779                    if (pkg != null &&
19780                            pkg.applicationInfo.targetSdkVersion >=
19781                                    Build.VERSION_CODES.JELLY_BEAN) {
19782                        throw new IllegalArgumentException("Component class " + className
19783                                + " does not exist in " + packageName);
19784                    } else {
19785                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19786                                + className + " does not exist in " + packageName);
19787                    }
19788                }
19789                switch (newState) {
19790                case COMPONENT_ENABLED_STATE_ENABLED:
19791                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19792                        return;
19793                    }
19794                    break;
19795                case COMPONENT_ENABLED_STATE_DISABLED:
19796                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19797                        return;
19798                    }
19799                    break;
19800                case COMPONENT_ENABLED_STATE_DEFAULT:
19801                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19802                        return;
19803                    }
19804                    break;
19805                default:
19806                    Slog.e(TAG, "Invalid new component state: " + newState);
19807                    return;
19808                }
19809            }
19810            scheduleWritePackageRestrictionsLocked(userId);
19811            updateSequenceNumberLP(packageName, new int[] { userId });
19812            components = mPendingBroadcasts.get(userId, packageName);
19813            final boolean newPackage = components == null;
19814            if (newPackage) {
19815                components = new ArrayList<String>();
19816            }
19817            if (!components.contains(componentName)) {
19818                components.add(componentName);
19819            }
19820            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19821                sendNow = true;
19822                // Purge entry from pending broadcast list if another one exists already
19823                // since we are sending one right away.
19824                mPendingBroadcasts.remove(userId, packageName);
19825            } else {
19826                if (newPackage) {
19827                    mPendingBroadcasts.put(userId, packageName, components);
19828                }
19829                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19830                    // Schedule a message
19831                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19832                }
19833            }
19834        }
19835
19836        long callingId = Binder.clearCallingIdentity();
19837        try {
19838            if (sendNow) {
19839                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19840                sendPackageChangedBroadcast(packageName,
19841                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19842            }
19843        } finally {
19844            Binder.restoreCallingIdentity(callingId);
19845        }
19846    }
19847
19848    @Override
19849    public void flushPackageRestrictionsAsUser(int userId) {
19850        if (!sUserManager.exists(userId)) {
19851            return;
19852        }
19853        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19854                false /* checkShell */, "flushPackageRestrictions");
19855        synchronized (mPackages) {
19856            mSettings.writePackageRestrictionsLPr(userId);
19857            mDirtyUsers.remove(userId);
19858            if (mDirtyUsers.isEmpty()) {
19859                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19860            }
19861        }
19862    }
19863
19864    private void sendPackageChangedBroadcast(String packageName,
19865            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19866        if (DEBUG_INSTALL)
19867            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19868                    + componentNames);
19869        Bundle extras = new Bundle(4);
19870        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19871        String nameList[] = new String[componentNames.size()];
19872        componentNames.toArray(nameList);
19873        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19874        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19875        extras.putInt(Intent.EXTRA_UID, packageUid);
19876        // If this is not reporting a change of the overall package, then only send it
19877        // to registered receivers.  We don't want to launch a swath of apps for every
19878        // little component state change.
19879        final int flags = !componentNames.contains(packageName)
19880                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19881        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19882                new int[] {UserHandle.getUserId(packageUid)});
19883    }
19884
19885    @Override
19886    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19887        if (!sUserManager.exists(userId)) return;
19888        final int uid = Binder.getCallingUid();
19889        final int permission = mContext.checkCallingOrSelfPermission(
19890                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19891        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19892        enforceCrossUserPermission(uid, userId,
19893                true /* requireFullPermission */, true /* checkShell */, "stop package");
19894        // writer
19895        synchronized (mPackages) {
19896            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19897                    allowedByPermission, uid, userId)) {
19898                scheduleWritePackageRestrictionsLocked(userId);
19899            }
19900        }
19901    }
19902
19903    @Override
19904    public String getInstallerPackageName(String packageName) {
19905        // reader
19906        synchronized (mPackages) {
19907            return mSettings.getInstallerPackageNameLPr(packageName);
19908        }
19909    }
19910
19911    public boolean isOrphaned(String packageName) {
19912        // reader
19913        synchronized (mPackages) {
19914            return mSettings.isOrphaned(packageName);
19915        }
19916    }
19917
19918    @Override
19919    public int getApplicationEnabledSetting(String packageName, int userId) {
19920        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19921        int uid = Binder.getCallingUid();
19922        enforceCrossUserPermission(uid, userId,
19923                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19924        // reader
19925        synchronized (mPackages) {
19926            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19927        }
19928    }
19929
19930    @Override
19931    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19932        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19933        int uid = Binder.getCallingUid();
19934        enforceCrossUserPermission(uid, userId,
19935                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19936        // reader
19937        synchronized (mPackages) {
19938            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19939        }
19940    }
19941
19942    @Override
19943    public void enterSafeMode() {
19944        enforceSystemOrRoot("Only the system can request entering safe mode");
19945
19946        if (!mSystemReady) {
19947            mSafeMode = true;
19948        }
19949    }
19950
19951    @Override
19952    public void systemReady() {
19953        mSystemReady = true;
19954
19955        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19956        // disabled after already being started.
19957        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19958                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19959
19960        // Read the compatibilty setting when the system is ready.
19961        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19962                mContext.getContentResolver(),
19963                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19964        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19965        if (DEBUG_SETTINGS) {
19966            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19967        }
19968
19969        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19970
19971        synchronized (mPackages) {
19972            // Verify that all of the preferred activity components actually
19973            // exist.  It is possible for applications to be updated and at
19974            // that point remove a previously declared activity component that
19975            // had been set as a preferred activity.  We try to clean this up
19976            // the next time we encounter that preferred activity, but it is
19977            // possible for the user flow to never be able to return to that
19978            // situation so here we do a sanity check to make sure we haven't
19979            // left any junk around.
19980            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19981            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19982                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19983                removed.clear();
19984                for (PreferredActivity pa : pir.filterSet()) {
19985                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19986                        removed.add(pa);
19987                    }
19988                }
19989                if (removed.size() > 0) {
19990                    for (int r=0; r<removed.size(); r++) {
19991                        PreferredActivity pa = removed.get(r);
19992                        Slog.w(TAG, "Removing dangling preferred activity: "
19993                                + pa.mPref.mComponent);
19994                        pir.removeFilter(pa);
19995                    }
19996                    mSettings.writePackageRestrictionsLPr(
19997                            mSettings.mPreferredActivities.keyAt(i));
19998                }
19999            }
20000
20001            for (int userId : UserManagerService.getInstance().getUserIds()) {
20002                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20003                    grantPermissionsUserIds = ArrayUtils.appendInt(
20004                            grantPermissionsUserIds, userId);
20005                }
20006            }
20007        }
20008        sUserManager.systemReady();
20009
20010        // If we upgraded grant all default permissions before kicking off.
20011        for (int userId : grantPermissionsUserIds) {
20012            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20013        }
20014
20015        // If we did not grant default permissions, we preload from this the
20016        // default permission exceptions lazily to ensure we don't hit the
20017        // disk on a new user creation.
20018        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20019            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20020        }
20021
20022        // Kick off any messages waiting for system ready
20023        if (mPostSystemReadyMessages != null) {
20024            for (Message msg : mPostSystemReadyMessages) {
20025                msg.sendToTarget();
20026            }
20027            mPostSystemReadyMessages = null;
20028        }
20029
20030        // Watch for external volumes that come and go over time
20031        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20032        storage.registerListener(mStorageListener);
20033
20034        mInstallerService.systemReady();
20035        mPackageDexOptimizer.systemReady();
20036
20037        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20038                StorageManagerInternal.class);
20039        StorageManagerInternal.addExternalStoragePolicy(
20040                new StorageManagerInternal.ExternalStorageMountPolicy() {
20041            @Override
20042            public int getMountMode(int uid, String packageName) {
20043                if (Process.isIsolated(uid)) {
20044                    return Zygote.MOUNT_EXTERNAL_NONE;
20045                }
20046                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20047                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20048                }
20049                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20050                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20051                }
20052                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20053                    return Zygote.MOUNT_EXTERNAL_READ;
20054                }
20055                return Zygote.MOUNT_EXTERNAL_WRITE;
20056            }
20057
20058            @Override
20059            public boolean hasExternalStorage(int uid, String packageName) {
20060                return true;
20061            }
20062        });
20063
20064        // Now that we're mostly running, clean up stale users and apps
20065        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20066        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20067
20068        if (mPrivappPermissionsViolations != null) {
20069            Slog.wtf(TAG,"Signature|privileged permissions not in "
20070                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20071            mPrivappPermissionsViolations = null;
20072        }
20073    }
20074
20075    public void waitForAppDataPrepared() {
20076        if (mPrepareAppDataFuture == null) {
20077            return;
20078        }
20079        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20080        mPrepareAppDataFuture = null;
20081    }
20082
20083    @Override
20084    public boolean isSafeMode() {
20085        return mSafeMode;
20086    }
20087
20088    @Override
20089    public boolean hasSystemUidErrors() {
20090        return mHasSystemUidErrors;
20091    }
20092
20093    static String arrayToString(int[] array) {
20094        StringBuffer buf = new StringBuffer(128);
20095        buf.append('[');
20096        if (array != null) {
20097            for (int i=0; i<array.length; i++) {
20098                if (i > 0) buf.append(", ");
20099                buf.append(array[i]);
20100            }
20101        }
20102        buf.append(']');
20103        return buf.toString();
20104    }
20105
20106    static class DumpState {
20107        public static final int DUMP_LIBS = 1 << 0;
20108        public static final int DUMP_FEATURES = 1 << 1;
20109        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20110        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20111        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20112        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20113        public static final int DUMP_PERMISSIONS = 1 << 6;
20114        public static final int DUMP_PACKAGES = 1 << 7;
20115        public static final int DUMP_SHARED_USERS = 1 << 8;
20116        public static final int DUMP_MESSAGES = 1 << 9;
20117        public static final int DUMP_PROVIDERS = 1 << 10;
20118        public static final int DUMP_VERIFIERS = 1 << 11;
20119        public static final int DUMP_PREFERRED = 1 << 12;
20120        public static final int DUMP_PREFERRED_XML = 1 << 13;
20121        public static final int DUMP_KEYSETS = 1 << 14;
20122        public static final int DUMP_VERSION = 1 << 15;
20123        public static final int DUMP_INSTALLS = 1 << 16;
20124        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20125        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20126        public static final int DUMP_FROZEN = 1 << 19;
20127        public static final int DUMP_DEXOPT = 1 << 20;
20128        public static final int DUMP_COMPILER_STATS = 1 << 21;
20129        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20130
20131        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20132
20133        private int mTypes;
20134
20135        private int mOptions;
20136
20137        private boolean mTitlePrinted;
20138
20139        private SharedUserSetting mSharedUser;
20140
20141        public boolean isDumping(int type) {
20142            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20143                return true;
20144            }
20145
20146            return (mTypes & type) != 0;
20147        }
20148
20149        public void setDump(int type) {
20150            mTypes |= type;
20151        }
20152
20153        public boolean isOptionEnabled(int option) {
20154            return (mOptions & option) != 0;
20155        }
20156
20157        public void setOptionEnabled(int option) {
20158            mOptions |= option;
20159        }
20160
20161        public boolean onTitlePrinted() {
20162            final boolean printed = mTitlePrinted;
20163            mTitlePrinted = true;
20164            return printed;
20165        }
20166
20167        public boolean getTitlePrinted() {
20168            return mTitlePrinted;
20169        }
20170
20171        public void setTitlePrinted(boolean enabled) {
20172            mTitlePrinted = enabled;
20173        }
20174
20175        public SharedUserSetting getSharedUser() {
20176            return mSharedUser;
20177        }
20178
20179        public void setSharedUser(SharedUserSetting user) {
20180            mSharedUser = user;
20181        }
20182    }
20183
20184    @Override
20185    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20186            FileDescriptor err, String[] args, ShellCallback callback,
20187            ResultReceiver resultReceiver) {
20188        (new PackageManagerShellCommand(this)).exec(
20189                this, in, out, err, args, callback, resultReceiver);
20190    }
20191
20192    @Override
20193    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20194        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20195                != PackageManager.PERMISSION_GRANTED) {
20196            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20197                    + Binder.getCallingPid()
20198                    + ", uid=" + Binder.getCallingUid()
20199                    + " without permission "
20200                    + android.Manifest.permission.DUMP);
20201            return;
20202        }
20203
20204        DumpState dumpState = new DumpState();
20205        boolean fullPreferred = false;
20206        boolean checkin = false;
20207
20208        String packageName = null;
20209        ArraySet<String> permissionNames = null;
20210
20211        int opti = 0;
20212        while (opti < args.length) {
20213            String opt = args[opti];
20214            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20215                break;
20216            }
20217            opti++;
20218
20219            if ("-a".equals(opt)) {
20220                // Right now we only know how to print all.
20221            } else if ("-h".equals(opt)) {
20222                pw.println("Package manager dump options:");
20223                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20224                pw.println("    --checkin: dump for a checkin");
20225                pw.println("    -f: print details of intent filters");
20226                pw.println("    -h: print this help");
20227                pw.println("  cmd may be one of:");
20228                pw.println("    l[ibraries]: list known shared libraries");
20229                pw.println("    f[eatures]: list device features");
20230                pw.println("    k[eysets]: print known keysets");
20231                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20232                pw.println("    perm[issions]: dump permissions");
20233                pw.println("    permission [name ...]: dump declaration and use of given permission");
20234                pw.println("    pref[erred]: print preferred package settings");
20235                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20236                pw.println("    prov[iders]: dump content providers");
20237                pw.println("    p[ackages]: dump installed packages");
20238                pw.println("    s[hared-users]: dump shared user IDs");
20239                pw.println("    m[essages]: print collected runtime messages");
20240                pw.println("    v[erifiers]: print package verifier info");
20241                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20242                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20243                pw.println("    version: print database version info");
20244                pw.println("    write: write current settings now");
20245                pw.println("    installs: details about install sessions");
20246                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20247                pw.println("    dexopt: dump dexopt state");
20248                pw.println("    compiler-stats: dump compiler statistics");
20249                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20250                pw.println("    <package.name>: info about given package");
20251                return;
20252            } else if ("--checkin".equals(opt)) {
20253                checkin = true;
20254            } else if ("-f".equals(opt)) {
20255                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20256            } else if ("--proto".equals(opt)) {
20257                dumpProto(fd);
20258                return;
20259            } else {
20260                pw.println("Unknown argument: " + opt + "; use -h for help");
20261            }
20262        }
20263
20264        // Is the caller requesting to dump a particular piece of data?
20265        if (opti < args.length) {
20266            String cmd = args[opti];
20267            opti++;
20268            // Is this a package name?
20269            if ("android".equals(cmd) || cmd.contains(".")) {
20270                packageName = cmd;
20271                // When dumping a single package, we always dump all of its
20272                // filter information since the amount of data will be reasonable.
20273                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20274            } else if ("check-permission".equals(cmd)) {
20275                if (opti >= args.length) {
20276                    pw.println("Error: check-permission missing permission argument");
20277                    return;
20278                }
20279                String perm = args[opti];
20280                opti++;
20281                if (opti >= args.length) {
20282                    pw.println("Error: check-permission missing package argument");
20283                    return;
20284                }
20285
20286                String pkg = args[opti];
20287                opti++;
20288                int user = UserHandle.getUserId(Binder.getCallingUid());
20289                if (opti < args.length) {
20290                    try {
20291                        user = Integer.parseInt(args[opti]);
20292                    } catch (NumberFormatException e) {
20293                        pw.println("Error: check-permission user argument is not a number: "
20294                                + args[opti]);
20295                        return;
20296                    }
20297                }
20298
20299                // Normalize package name to handle renamed packages and static libs
20300                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20301
20302                pw.println(checkPermission(perm, pkg, user));
20303                return;
20304            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20305                dumpState.setDump(DumpState.DUMP_LIBS);
20306            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20307                dumpState.setDump(DumpState.DUMP_FEATURES);
20308            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20309                if (opti >= args.length) {
20310                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20311                            | DumpState.DUMP_SERVICE_RESOLVERS
20312                            | DumpState.DUMP_RECEIVER_RESOLVERS
20313                            | DumpState.DUMP_CONTENT_RESOLVERS);
20314                } else {
20315                    while (opti < args.length) {
20316                        String name = args[opti];
20317                        if ("a".equals(name) || "activity".equals(name)) {
20318                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20319                        } else if ("s".equals(name) || "service".equals(name)) {
20320                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20321                        } else if ("r".equals(name) || "receiver".equals(name)) {
20322                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20323                        } else if ("c".equals(name) || "content".equals(name)) {
20324                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20325                        } else {
20326                            pw.println("Error: unknown resolver table type: " + name);
20327                            return;
20328                        }
20329                        opti++;
20330                    }
20331                }
20332            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20333                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20334            } else if ("permission".equals(cmd)) {
20335                if (opti >= args.length) {
20336                    pw.println("Error: permission requires permission name");
20337                    return;
20338                }
20339                permissionNames = new ArraySet<>();
20340                while (opti < args.length) {
20341                    permissionNames.add(args[opti]);
20342                    opti++;
20343                }
20344                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20345                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20346            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20347                dumpState.setDump(DumpState.DUMP_PREFERRED);
20348            } else if ("preferred-xml".equals(cmd)) {
20349                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20350                if (opti < args.length && "--full".equals(args[opti])) {
20351                    fullPreferred = true;
20352                    opti++;
20353                }
20354            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20355                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20356            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20357                dumpState.setDump(DumpState.DUMP_PACKAGES);
20358            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20359                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20360            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20361                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20362            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20363                dumpState.setDump(DumpState.DUMP_MESSAGES);
20364            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20365                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20366            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20367                    || "intent-filter-verifiers".equals(cmd)) {
20368                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20369            } else if ("version".equals(cmd)) {
20370                dumpState.setDump(DumpState.DUMP_VERSION);
20371            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20372                dumpState.setDump(DumpState.DUMP_KEYSETS);
20373            } else if ("installs".equals(cmd)) {
20374                dumpState.setDump(DumpState.DUMP_INSTALLS);
20375            } else if ("frozen".equals(cmd)) {
20376                dumpState.setDump(DumpState.DUMP_FROZEN);
20377            } else if ("dexopt".equals(cmd)) {
20378                dumpState.setDump(DumpState.DUMP_DEXOPT);
20379            } else if ("compiler-stats".equals(cmd)) {
20380                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20381            } else if ("enabled-overlays".equals(cmd)) {
20382                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20383            } else if ("write".equals(cmd)) {
20384                synchronized (mPackages) {
20385                    mSettings.writeLPr();
20386                    pw.println("Settings written.");
20387                    return;
20388                }
20389            }
20390        }
20391
20392        if (checkin) {
20393            pw.println("vers,1");
20394        }
20395
20396        // reader
20397        synchronized (mPackages) {
20398            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20399                if (!checkin) {
20400                    if (dumpState.onTitlePrinted())
20401                        pw.println();
20402                    pw.println("Database versions:");
20403                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20404                }
20405            }
20406
20407            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20408                if (!checkin) {
20409                    if (dumpState.onTitlePrinted())
20410                        pw.println();
20411                    pw.println("Verifiers:");
20412                    pw.print("  Required: ");
20413                    pw.print(mRequiredVerifierPackage);
20414                    pw.print(" (uid=");
20415                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20416                            UserHandle.USER_SYSTEM));
20417                    pw.println(")");
20418                } else if (mRequiredVerifierPackage != null) {
20419                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20420                    pw.print(",");
20421                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20422                            UserHandle.USER_SYSTEM));
20423                }
20424            }
20425
20426            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20427                    packageName == null) {
20428                if (mIntentFilterVerifierComponent != null) {
20429                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20430                    if (!checkin) {
20431                        if (dumpState.onTitlePrinted())
20432                            pw.println();
20433                        pw.println("Intent Filter Verifier:");
20434                        pw.print("  Using: ");
20435                        pw.print(verifierPackageName);
20436                        pw.print(" (uid=");
20437                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20438                                UserHandle.USER_SYSTEM));
20439                        pw.println(")");
20440                    } else if (verifierPackageName != null) {
20441                        pw.print("ifv,"); pw.print(verifierPackageName);
20442                        pw.print(",");
20443                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20444                                UserHandle.USER_SYSTEM));
20445                    }
20446                } else {
20447                    pw.println();
20448                    pw.println("No Intent Filter Verifier available!");
20449                }
20450            }
20451
20452            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20453                boolean printedHeader = false;
20454                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20455                while (it.hasNext()) {
20456                    String libName = it.next();
20457                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20458                    if (versionedLib == null) {
20459                        continue;
20460                    }
20461                    final int versionCount = versionedLib.size();
20462                    for (int i = 0; i < versionCount; i++) {
20463                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20464                        if (!checkin) {
20465                            if (!printedHeader) {
20466                                if (dumpState.onTitlePrinted())
20467                                    pw.println();
20468                                pw.println("Libraries:");
20469                                printedHeader = true;
20470                            }
20471                            pw.print("  ");
20472                        } else {
20473                            pw.print("lib,");
20474                        }
20475                        pw.print(libEntry.info.getName());
20476                        if (libEntry.info.isStatic()) {
20477                            pw.print(" version=" + libEntry.info.getVersion());
20478                        }
20479                        if (!checkin) {
20480                            pw.print(" -> ");
20481                        }
20482                        if (libEntry.path != null) {
20483                            pw.print(" (jar) ");
20484                            pw.print(libEntry.path);
20485                        } else {
20486                            pw.print(" (apk) ");
20487                            pw.print(libEntry.apk);
20488                        }
20489                        pw.println();
20490                    }
20491                }
20492            }
20493
20494            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20495                if (dumpState.onTitlePrinted())
20496                    pw.println();
20497                if (!checkin) {
20498                    pw.println("Features:");
20499                }
20500
20501                synchronized (mAvailableFeatures) {
20502                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20503                        if (checkin) {
20504                            pw.print("feat,");
20505                            pw.print(feat.name);
20506                            pw.print(",");
20507                            pw.println(feat.version);
20508                        } else {
20509                            pw.print("  ");
20510                            pw.print(feat.name);
20511                            if (feat.version > 0) {
20512                                pw.print(" version=");
20513                                pw.print(feat.version);
20514                            }
20515                            pw.println();
20516                        }
20517                    }
20518                }
20519            }
20520
20521            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20522                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20523                        : "Activity Resolver Table:", "  ", packageName,
20524                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20525                    dumpState.setTitlePrinted(true);
20526                }
20527            }
20528            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20529                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20530                        : "Receiver Resolver Table:", "  ", packageName,
20531                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20532                    dumpState.setTitlePrinted(true);
20533                }
20534            }
20535            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20536                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20537                        : "Service Resolver Table:", "  ", packageName,
20538                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20539                    dumpState.setTitlePrinted(true);
20540                }
20541            }
20542            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20543                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20544                        : "Provider Resolver Table:", "  ", packageName,
20545                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20546                    dumpState.setTitlePrinted(true);
20547                }
20548            }
20549
20550            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20551                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20552                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20553                    int user = mSettings.mPreferredActivities.keyAt(i);
20554                    if (pir.dump(pw,
20555                            dumpState.getTitlePrinted()
20556                                ? "\nPreferred Activities User " + user + ":"
20557                                : "Preferred Activities User " + user + ":", "  ",
20558                            packageName, true, false)) {
20559                        dumpState.setTitlePrinted(true);
20560                    }
20561                }
20562            }
20563
20564            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20565                pw.flush();
20566                FileOutputStream fout = new FileOutputStream(fd);
20567                BufferedOutputStream str = new BufferedOutputStream(fout);
20568                XmlSerializer serializer = new FastXmlSerializer();
20569                try {
20570                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20571                    serializer.startDocument(null, true);
20572                    serializer.setFeature(
20573                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20574                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20575                    serializer.endDocument();
20576                    serializer.flush();
20577                } catch (IllegalArgumentException e) {
20578                    pw.println("Failed writing: " + e);
20579                } catch (IllegalStateException e) {
20580                    pw.println("Failed writing: " + e);
20581                } catch (IOException e) {
20582                    pw.println("Failed writing: " + e);
20583                }
20584            }
20585
20586            if (!checkin
20587                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20588                    && packageName == null) {
20589                pw.println();
20590                int count = mSettings.mPackages.size();
20591                if (count == 0) {
20592                    pw.println("No applications!");
20593                    pw.println();
20594                } else {
20595                    final String prefix = "  ";
20596                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20597                    if (allPackageSettings.size() == 0) {
20598                        pw.println("No domain preferred apps!");
20599                        pw.println();
20600                    } else {
20601                        pw.println("App verification status:");
20602                        pw.println();
20603                        count = 0;
20604                        for (PackageSetting ps : allPackageSettings) {
20605                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20606                            if (ivi == null || ivi.getPackageName() == null) continue;
20607                            pw.println(prefix + "Package: " + ivi.getPackageName());
20608                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20609                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20610                            pw.println();
20611                            count++;
20612                        }
20613                        if (count == 0) {
20614                            pw.println(prefix + "No app verification established.");
20615                            pw.println();
20616                        }
20617                        for (int userId : sUserManager.getUserIds()) {
20618                            pw.println("App linkages for user " + userId + ":");
20619                            pw.println();
20620                            count = 0;
20621                            for (PackageSetting ps : allPackageSettings) {
20622                                final long status = ps.getDomainVerificationStatusForUser(userId);
20623                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20624                                        && !DEBUG_DOMAIN_VERIFICATION) {
20625                                    continue;
20626                                }
20627                                pw.println(prefix + "Package: " + ps.name);
20628                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20629                                String statusStr = IntentFilterVerificationInfo.
20630                                        getStatusStringFromValue(status);
20631                                pw.println(prefix + "Status:  " + statusStr);
20632                                pw.println();
20633                                count++;
20634                            }
20635                            if (count == 0) {
20636                                pw.println(prefix + "No configured app linkages.");
20637                                pw.println();
20638                            }
20639                        }
20640                    }
20641                }
20642            }
20643
20644            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20645                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20646                if (packageName == null && permissionNames == null) {
20647                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20648                        if (iperm == 0) {
20649                            if (dumpState.onTitlePrinted())
20650                                pw.println();
20651                            pw.println("AppOp Permissions:");
20652                        }
20653                        pw.print("  AppOp Permission ");
20654                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20655                        pw.println(":");
20656                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20657                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20658                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20659                        }
20660                    }
20661                }
20662            }
20663
20664            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20665                boolean printedSomething = false;
20666                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20667                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20668                        continue;
20669                    }
20670                    if (!printedSomething) {
20671                        if (dumpState.onTitlePrinted())
20672                            pw.println();
20673                        pw.println("Registered ContentProviders:");
20674                        printedSomething = true;
20675                    }
20676                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20677                    pw.print("    "); pw.println(p.toString());
20678                }
20679                printedSomething = false;
20680                for (Map.Entry<String, PackageParser.Provider> entry :
20681                        mProvidersByAuthority.entrySet()) {
20682                    PackageParser.Provider p = entry.getValue();
20683                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20684                        continue;
20685                    }
20686                    if (!printedSomething) {
20687                        if (dumpState.onTitlePrinted())
20688                            pw.println();
20689                        pw.println("ContentProvider Authorities:");
20690                        printedSomething = true;
20691                    }
20692                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20693                    pw.print("    "); pw.println(p.toString());
20694                    if (p.info != null && p.info.applicationInfo != null) {
20695                        final String appInfo = p.info.applicationInfo.toString();
20696                        pw.print("      applicationInfo="); pw.println(appInfo);
20697                    }
20698                }
20699            }
20700
20701            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20702                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20703            }
20704
20705            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20706                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20707            }
20708
20709            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20710                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20711            }
20712
20713            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20714                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20715            }
20716
20717            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20718                // XXX should handle packageName != null by dumping only install data that
20719                // the given package is involved with.
20720                if (dumpState.onTitlePrinted()) pw.println();
20721                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20722            }
20723
20724            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20725                // XXX should handle packageName != null by dumping only install data that
20726                // the given package is involved with.
20727                if (dumpState.onTitlePrinted()) pw.println();
20728
20729                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20730                ipw.println();
20731                ipw.println("Frozen packages:");
20732                ipw.increaseIndent();
20733                if (mFrozenPackages.size() == 0) {
20734                    ipw.println("(none)");
20735                } else {
20736                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20737                        ipw.println(mFrozenPackages.valueAt(i));
20738                    }
20739                }
20740                ipw.decreaseIndent();
20741            }
20742
20743            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20744                if (dumpState.onTitlePrinted()) pw.println();
20745                dumpDexoptStateLPr(pw, packageName);
20746            }
20747
20748            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20749                if (dumpState.onTitlePrinted()) pw.println();
20750                dumpCompilerStatsLPr(pw, packageName);
20751            }
20752
20753            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20754                if (dumpState.onTitlePrinted()) pw.println();
20755                dumpEnabledOverlaysLPr(pw);
20756            }
20757
20758            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20759                if (dumpState.onTitlePrinted()) pw.println();
20760                mSettings.dumpReadMessagesLPr(pw, dumpState);
20761
20762                pw.println();
20763                pw.println("Package warning messages:");
20764                BufferedReader in = null;
20765                String line = null;
20766                try {
20767                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20768                    while ((line = in.readLine()) != null) {
20769                        if (line.contains("ignored: updated version")) continue;
20770                        pw.println(line);
20771                    }
20772                } catch (IOException ignored) {
20773                } finally {
20774                    IoUtils.closeQuietly(in);
20775                }
20776            }
20777
20778            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20779                BufferedReader in = null;
20780                String line = null;
20781                try {
20782                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20783                    while ((line = in.readLine()) != null) {
20784                        if (line.contains("ignored: updated version")) continue;
20785                        pw.print("msg,");
20786                        pw.println(line);
20787                    }
20788                } catch (IOException ignored) {
20789                } finally {
20790                    IoUtils.closeQuietly(in);
20791                }
20792            }
20793        }
20794    }
20795
20796    private void dumpProto(FileDescriptor fd) {
20797        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20798
20799        synchronized (mPackages) {
20800            final long requiredVerifierPackageToken =
20801                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20802            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20803            proto.write(
20804                    PackageServiceDumpProto.PackageShortProto.UID,
20805                    getPackageUid(
20806                            mRequiredVerifierPackage,
20807                            MATCH_DEBUG_TRIAGED_MISSING,
20808                            UserHandle.USER_SYSTEM));
20809            proto.end(requiredVerifierPackageToken);
20810
20811            if (mIntentFilterVerifierComponent != null) {
20812                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20813                final long verifierPackageToken =
20814                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20815                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20816                proto.write(
20817                        PackageServiceDumpProto.PackageShortProto.UID,
20818                        getPackageUid(
20819                                verifierPackageName,
20820                                MATCH_DEBUG_TRIAGED_MISSING,
20821                                UserHandle.USER_SYSTEM));
20822                proto.end(verifierPackageToken);
20823            }
20824
20825            dumpSharedLibrariesProto(proto);
20826            dumpFeaturesProto(proto);
20827            mSettings.dumpPackagesProto(proto);
20828            mSettings.dumpSharedUsersProto(proto);
20829            dumpMessagesProto(proto);
20830        }
20831        proto.flush();
20832    }
20833
20834    private void dumpMessagesProto(ProtoOutputStream proto) {
20835        BufferedReader in = null;
20836        String line = null;
20837        try {
20838            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20839            while ((line = in.readLine()) != null) {
20840                if (line.contains("ignored: updated version")) continue;
20841                proto.write(PackageServiceDumpProto.MESSAGES, line);
20842            }
20843        } catch (IOException ignored) {
20844        } finally {
20845            IoUtils.closeQuietly(in);
20846        }
20847    }
20848
20849    private void dumpFeaturesProto(ProtoOutputStream proto) {
20850        synchronized (mAvailableFeatures) {
20851            final int count = mAvailableFeatures.size();
20852            for (int i = 0; i < count; i++) {
20853                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20854                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20855                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20856                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20857                proto.end(featureToken);
20858            }
20859        }
20860    }
20861
20862    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20863        final int count = mSharedLibraries.size();
20864        for (int i = 0; i < count; i++) {
20865            final String libName = mSharedLibraries.keyAt(i);
20866            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20867            if (versionedLib == null) {
20868                continue;
20869            }
20870            final int versionCount = versionedLib.size();
20871            for (int j = 0; j < versionCount; j++) {
20872                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20873                final long sharedLibraryToken =
20874                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20875                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20876                final boolean isJar = (libEntry.path != null);
20877                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20878                if (isJar) {
20879                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20880                } else {
20881                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20882                }
20883                proto.end(sharedLibraryToken);
20884            }
20885        }
20886    }
20887
20888    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20889        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20890        ipw.println();
20891        ipw.println("Dexopt state:");
20892        ipw.increaseIndent();
20893        Collection<PackageParser.Package> packages = null;
20894        if (packageName != null) {
20895            PackageParser.Package targetPackage = mPackages.get(packageName);
20896            if (targetPackage != null) {
20897                packages = Collections.singletonList(targetPackage);
20898            } else {
20899                ipw.println("Unable to find package: " + packageName);
20900                return;
20901            }
20902        } else {
20903            packages = mPackages.values();
20904        }
20905
20906        for (PackageParser.Package pkg : packages) {
20907            ipw.println("[" + pkg.packageName + "]");
20908            ipw.increaseIndent();
20909            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20910            ipw.decreaseIndent();
20911        }
20912    }
20913
20914    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20915        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20916        ipw.println();
20917        ipw.println("Compiler stats:");
20918        ipw.increaseIndent();
20919        Collection<PackageParser.Package> packages = null;
20920        if (packageName != null) {
20921            PackageParser.Package targetPackage = mPackages.get(packageName);
20922            if (targetPackage != null) {
20923                packages = Collections.singletonList(targetPackage);
20924            } else {
20925                ipw.println("Unable to find package: " + packageName);
20926                return;
20927            }
20928        } else {
20929            packages = mPackages.values();
20930        }
20931
20932        for (PackageParser.Package pkg : packages) {
20933            ipw.println("[" + pkg.packageName + "]");
20934            ipw.increaseIndent();
20935
20936            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20937            if (stats == null) {
20938                ipw.println("(No recorded stats)");
20939            } else {
20940                stats.dump(ipw);
20941            }
20942            ipw.decreaseIndent();
20943        }
20944    }
20945
20946    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20947        pw.println("Enabled overlay paths:");
20948        final int N = mEnabledOverlayPaths.size();
20949        for (int i = 0; i < N; i++) {
20950            final int userId = mEnabledOverlayPaths.keyAt(i);
20951            pw.println(String.format("    User %d:", userId));
20952            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20953                mEnabledOverlayPaths.valueAt(i);
20954            final int M = userSpecificOverlays.size();
20955            for (int j = 0; j < M; j++) {
20956                final String targetPackageName = userSpecificOverlays.keyAt(j);
20957                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20958                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20959            }
20960        }
20961    }
20962
20963    private String dumpDomainString(String packageName) {
20964        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20965                .getList();
20966        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20967
20968        ArraySet<String> result = new ArraySet<>();
20969        if (iviList.size() > 0) {
20970            for (IntentFilterVerificationInfo ivi : iviList) {
20971                for (String host : ivi.getDomains()) {
20972                    result.add(host);
20973                }
20974            }
20975        }
20976        if (filters != null && filters.size() > 0) {
20977            for (IntentFilter filter : filters) {
20978                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20979                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20980                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20981                    result.addAll(filter.getHostsList());
20982                }
20983            }
20984        }
20985
20986        StringBuilder sb = new StringBuilder(result.size() * 16);
20987        for (String domain : result) {
20988            if (sb.length() > 0) sb.append(" ");
20989            sb.append(domain);
20990        }
20991        return sb.toString();
20992    }
20993
20994    // ------- apps on sdcard specific code -------
20995    static final boolean DEBUG_SD_INSTALL = false;
20996
20997    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20998
20999    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21000
21001    private boolean mMediaMounted = false;
21002
21003    static String getEncryptKey() {
21004        try {
21005            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21006                    SD_ENCRYPTION_KEYSTORE_NAME);
21007            if (sdEncKey == null) {
21008                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21009                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21010                if (sdEncKey == null) {
21011                    Slog.e(TAG, "Failed to create encryption keys");
21012                    return null;
21013                }
21014            }
21015            return sdEncKey;
21016        } catch (NoSuchAlgorithmException nsae) {
21017            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21018            return null;
21019        } catch (IOException ioe) {
21020            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21021            return null;
21022        }
21023    }
21024
21025    /*
21026     * Update media status on PackageManager.
21027     */
21028    @Override
21029    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21030        int callingUid = Binder.getCallingUid();
21031        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21032            throw new SecurityException("Media status can only be updated by the system");
21033        }
21034        // reader; this apparently protects mMediaMounted, but should probably
21035        // be a different lock in that case.
21036        synchronized (mPackages) {
21037            Log.i(TAG, "Updating external media status from "
21038                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21039                    + (mediaStatus ? "mounted" : "unmounted"));
21040            if (DEBUG_SD_INSTALL)
21041                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21042                        + ", mMediaMounted=" + mMediaMounted);
21043            if (mediaStatus == mMediaMounted) {
21044                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21045                        : 0, -1);
21046                mHandler.sendMessage(msg);
21047                return;
21048            }
21049            mMediaMounted = mediaStatus;
21050        }
21051        // Queue up an async operation since the package installation may take a
21052        // little while.
21053        mHandler.post(new Runnable() {
21054            public void run() {
21055                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21056            }
21057        });
21058    }
21059
21060    /**
21061     * Called by StorageManagerService when the initial ASECs to scan are available.
21062     * Should block until all the ASEC containers are finished being scanned.
21063     */
21064    public void scanAvailableAsecs() {
21065        updateExternalMediaStatusInner(true, false, false);
21066    }
21067
21068    /*
21069     * Collect information of applications on external media, map them against
21070     * existing containers and update information based on current mount status.
21071     * Please note that we always have to report status if reportStatus has been
21072     * set to true especially when unloading packages.
21073     */
21074    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21075            boolean externalStorage) {
21076        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21077        int[] uidArr = EmptyArray.INT;
21078
21079        final String[] list = PackageHelper.getSecureContainerList();
21080        if (ArrayUtils.isEmpty(list)) {
21081            Log.i(TAG, "No secure containers found");
21082        } else {
21083            // Process list of secure containers and categorize them
21084            // as active or stale based on their package internal state.
21085
21086            // reader
21087            synchronized (mPackages) {
21088                for (String cid : list) {
21089                    // Leave stages untouched for now; installer service owns them
21090                    if (PackageInstallerService.isStageName(cid)) continue;
21091
21092                    if (DEBUG_SD_INSTALL)
21093                        Log.i(TAG, "Processing container " + cid);
21094                    String pkgName = getAsecPackageName(cid);
21095                    if (pkgName == null) {
21096                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21097                        continue;
21098                    }
21099                    if (DEBUG_SD_INSTALL)
21100                        Log.i(TAG, "Looking for pkg : " + pkgName);
21101
21102                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21103                    if (ps == null) {
21104                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21105                        continue;
21106                    }
21107
21108                    /*
21109                     * Skip packages that are not external if we're unmounting
21110                     * external storage.
21111                     */
21112                    if (externalStorage && !isMounted && !isExternal(ps)) {
21113                        continue;
21114                    }
21115
21116                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21117                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21118                    // The package status is changed only if the code path
21119                    // matches between settings and the container id.
21120                    if (ps.codePathString != null
21121                            && ps.codePathString.startsWith(args.getCodePath())) {
21122                        if (DEBUG_SD_INSTALL) {
21123                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21124                                    + " at code path: " + ps.codePathString);
21125                        }
21126
21127                        // We do have a valid package installed on sdcard
21128                        processCids.put(args, ps.codePathString);
21129                        final int uid = ps.appId;
21130                        if (uid != -1) {
21131                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21132                        }
21133                    } else {
21134                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21135                                + ps.codePathString);
21136                    }
21137                }
21138            }
21139
21140            Arrays.sort(uidArr);
21141        }
21142
21143        // Process packages with valid entries.
21144        if (isMounted) {
21145            if (DEBUG_SD_INSTALL)
21146                Log.i(TAG, "Loading packages");
21147            loadMediaPackages(processCids, uidArr, externalStorage);
21148            startCleaningPackages();
21149            mInstallerService.onSecureContainersAvailable();
21150        } else {
21151            if (DEBUG_SD_INSTALL)
21152                Log.i(TAG, "Unloading packages");
21153            unloadMediaPackages(processCids, uidArr, reportStatus);
21154        }
21155    }
21156
21157    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21158            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21159        final int size = infos.size();
21160        final String[] packageNames = new String[size];
21161        final int[] packageUids = new int[size];
21162        for (int i = 0; i < size; i++) {
21163            final ApplicationInfo info = infos.get(i);
21164            packageNames[i] = info.packageName;
21165            packageUids[i] = info.uid;
21166        }
21167        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21168                finishedReceiver);
21169    }
21170
21171    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21172            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21173        sendResourcesChangedBroadcast(mediaStatus, replacing,
21174                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21175    }
21176
21177    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21178            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21179        int size = pkgList.length;
21180        if (size > 0) {
21181            // Send broadcasts here
21182            Bundle extras = new Bundle();
21183            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21184            if (uidArr != null) {
21185                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21186            }
21187            if (replacing) {
21188                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21189            }
21190            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21191                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21192            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21193        }
21194    }
21195
21196   /*
21197     * Look at potentially valid container ids from processCids If package
21198     * information doesn't match the one on record or package scanning fails,
21199     * the cid is added to list of removeCids. We currently don't delete stale
21200     * containers.
21201     */
21202    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21203            boolean externalStorage) {
21204        ArrayList<String> pkgList = new ArrayList<String>();
21205        Set<AsecInstallArgs> keys = processCids.keySet();
21206
21207        for (AsecInstallArgs args : keys) {
21208            String codePath = processCids.get(args);
21209            if (DEBUG_SD_INSTALL)
21210                Log.i(TAG, "Loading container : " + args.cid);
21211            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21212            try {
21213                // Make sure there are no container errors first.
21214                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21215                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21216                            + " when installing from sdcard");
21217                    continue;
21218                }
21219                // Check code path here.
21220                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21221                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21222                            + " does not match one in settings " + codePath);
21223                    continue;
21224                }
21225                // Parse package
21226                int parseFlags = mDefParseFlags;
21227                if (args.isExternalAsec()) {
21228                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21229                }
21230                if (args.isFwdLocked()) {
21231                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21232                }
21233
21234                synchronized (mInstallLock) {
21235                    PackageParser.Package pkg = null;
21236                    try {
21237                        // Sadly we don't know the package name yet to freeze it
21238                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21239                                SCAN_IGNORE_FROZEN, 0, null);
21240                    } catch (PackageManagerException e) {
21241                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21242                    }
21243                    // Scan the package
21244                    if (pkg != null) {
21245                        /*
21246                         * TODO why is the lock being held? doPostInstall is
21247                         * called in other places without the lock. This needs
21248                         * to be straightened out.
21249                         */
21250                        // writer
21251                        synchronized (mPackages) {
21252                            retCode = PackageManager.INSTALL_SUCCEEDED;
21253                            pkgList.add(pkg.packageName);
21254                            // Post process args
21255                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21256                                    pkg.applicationInfo.uid);
21257                        }
21258                    } else {
21259                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21260                    }
21261                }
21262
21263            } finally {
21264                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21265                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21266                }
21267            }
21268        }
21269        // writer
21270        synchronized (mPackages) {
21271            // If the platform SDK has changed since the last time we booted,
21272            // we need to re-grant app permission to catch any new ones that
21273            // appear. This is really a hack, and means that apps can in some
21274            // cases get permissions that the user didn't initially explicitly
21275            // allow... it would be nice to have some better way to handle
21276            // this situation.
21277            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21278                    : mSettings.getInternalVersion();
21279            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21280                    : StorageManager.UUID_PRIVATE_INTERNAL;
21281
21282            int updateFlags = UPDATE_PERMISSIONS_ALL;
21283            if (ver.sdkVersion != mSdkVersion) {
21284                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21285                        + mSdkVersion + "; regranting permissions for external");
21286                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21287            }
21288            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21289
21290            // Yay, everything is now upgraded
21291            ver.forceCurrent();
21292
21293            // can downgrade to reader
21294            // Persist settings
21295            mSettings.writeLPr();
21296        }
21297        // Send a broadcast to let everyone know we are done processing
21298        if (pkgList.size() > 0) {
21299            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21300        }
21301    }
21302
21303   /*
21304     * Utility method to unload a list of specified containers
21305     */
21306    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21307        // Just unmount all valid containers.
21308        for (AsecInstallArgs arg : cidArgs) {
21309            synchronized (mInstallLock) {
21310                arg.doPostDeleteLI(false);
21311           }
21312       }
21313   }
21314
21315    /*
21316     * Unload packages mounted on external media. This involves deleting package
21317     * data from internal structures, sending broadcasts about disabled packages,
21318     * gc'ing to free up references, unmounting all secure containers
21319     * corresponding to packages on external media, and posting a
21320     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21321     * that we always have to post this message if status has been requested no
21322     * matter what.
21323     */
21324    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21325            final boolean reportStatus) {
21326        if (DEBUG_SD_INSTALL)
21327            Log.i(TAG, "unloading media packages");
21328        ArrayList<String> pkgList = new ArrayList<String>();
21329        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21330        final Set<AsecInstallArgs> keys = processCids.keySet();
21331        for (AsecInstallArgs args : keys) {
21332            String pkgName = args.getPackageName();
21333            if (DEBUG_SD_INSTALL)
21334                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21335            // Delete package internally
21336            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21337            synchronized (mInstallLock) {
21338                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21339                final boolean res;
21340                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21341                        "unloadMediaPackages")) {
21342                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21343                            null);
21344                }
21345                if (res) {
21346                    pkgList.add(pkgName);
21347                } else {
21348                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21349                    failedList.add(args);
21350                }
21351            }
21352        }
21353
21354        // reader
21355        synchronized (mPackages) {
21356            // We didn't update the settings after removing each package;
21357            // write them now for all packages.
21358            mSettings.writeLPr();
21359        }
21360
21361        // We have to absolutely send UPDATED_MEDIA_STATUS only
21362        // after confirming that all the receivers processed the ordered
21363        // broadcast when packages get disabled, force a gc to clean things up.
21364        // and unload all the containers.
21365        if (pkgList.size() > 0) {
21366            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21367                    new IIntentReceiver.Stub() {
21368                public void performReceive(Intent intent, int resultCode, String data,
21369                        Bundle extras, boolean ordered, boolean sticky,
21370                        int sendingUser) throws RemoteException {
21371                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21372                            reportStatus ? 1 : 0, 1, keys);
21373                    mHandler.sendMessage(msg);
21374                }
21375            });
21376        } else {
21377            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21378                    keys);
21379            mHandler.sendMessage(msg);
21380        }
21381    }
21382
21383    private void loadPrivatePackages(final VolumeInfo vol) {
21384        mHandler.post(new Runnable() {
21385            @Override
21386            public void run() {
21387                loadPrivatePackagesInner(vol);
21388            }
21389        });
21390    }
21391
21392    private void loadPrivatePackagesInner(VolumeInfo vol) {
21393        final String volumeUuid = vol.fsUuid;
21394        if (TextUtils.isEmpty(volumeUuid)) {
21395            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21396            return;
21397        }
21398
21399        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21400        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21401        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21402
21403        final VersionInfo ver;
21404        final List<PackageSetting> packages;
21405        synchronized (mPackages) {
21406            ver = mSettings.findOrCreateVersion(volumeUuid);
21407            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21408        }
21409
21410        for (PackageSetting ps : packages) {
21411            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21412            synchronized (mInstallLock) {
21413                final PackageParser.Package pkg;
21414                try {
21415                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21416                    loaded.add(pkg.applicationInfo);
21417
21418                } catch (PackageManagerException e) {
21419                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21420                }
21421
21422                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21423                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21424                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21425                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21426                }
21427            }
21428        }
21429
21430        // Reconcile app data for all started/unlocked users
21431        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21432        final UserManager um = mContext.getSystemService(UserManager.class);
21433        UserManagerInternal umInternal = getUserManagerInternal();
21434        for (UserInfo user : um.getUsers()) {
21435            final int flags;
21436            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21437                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21438            } else if (umInternal.isUserRunning(user.id)) {
21439                flags = StorageManager.FLAG_STORAGE_DE;
21440            } else {
21441                continue;
21442            }
21443
21444            try {
21445                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21446                synchronized (mInstallLock) {
21447                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21448                }
21449            } catch (IllegalStateException e) {
21450                // Device was probably ejected, and we'll process that event momentarily
21451                Slog.w(TAG, "Failed to prepare storage: " + e);
21452            }
21453        }
21454
21455        synchronized (mPackages) {
21456            int updateFlags = UPDATE_PERMISSIONS_ALL;
21457            if (ver.sdkVersion != mSdkVersion) {
21458                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21459                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21460                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21461            }
21462            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21463
21464            // Yay, everything is now upgraded
21465            ver.forceCurrent();
21466
21467            mSettings.writeLPr();
21468        }
21469
21470        for (PackageFreezer freezer : freezers) {
21471            freezer.close();
21472        }
21473
21474        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21475        sendResourcesChangedBroadcast(true, false, loaded, null);
21476    }
21477
21478    private void unloadPrivatePackages(final VolumeInfo vol) {
21479        mHandler.post(new Runnable() {
21480            @Override
21481            public void run() {
21482                unloadPrivatePackagesInner(vol);
21483            }
21484        });
21485    }
21486
21487    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21488        final String volumeUuid = vol.fsUuid;
21489        if (TextUtils.isEmpty(volumeUuid)) {
21490            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21491            return;
21492        }
21493
21494        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21495        synchronized (mInstallLock) {
21496        synchronized (mPackages) {
21497            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21498            for (PackageSetting ps : packages) {
21499                if (ps.pkg == null) continue;
21500
21501                final ApplicationInfo info = ps.pkg.applicationInfo;
21502                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21503                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21504
21505                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21506                        "unloadPrivatePackagesInner")) {
21507                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21508                            false, null)) {
21509                        unloaded.add(info);
21510                    } else {
21511                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21512                    }
21513                }
21514
21515                // Try very hard to release any references to this package
21516                // so we don't risk the system server being killed due to
21517                // open FDs
21518                AttributeCache.instance().removePackage(ps.name);
21519            }
21520
21521            mSettings.writeLPr();
21522        }
21523        }
21524
21525        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21526        sendResourcesChangedBroadcast(false, false, unloaded, null);
21527
21528        // Try very hard to release any references to this path so we don't risk
21529        // the system server being killed due to open FDs
21530        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21531
21532        for (int i = 0; i < 3; i++) {
21533            System.gc();
21534            System.runFinalization();
21535        }
21536    }
21537
21538    private void assertPackageKnown(String volumeUuid, String packageName)
21539            throws PackageManagerException {
21540        synchronized (mPackages) {
21541            // Normalize package name to handle renamed packages
21542            packageName = normalizePackageNameLPr(packageName);
21543
21544            final PackageSetting ps = mSettings.mPackages.get(packageName);
21545            if (ps == null) {
21546                throw new PackageManagerException("Package " + packageName + " is unknown");
21547            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21548                throw new PackageManagerException(
21549                        "Package " + packageName + " found on unknown volume " + volumeUuid
21550                                + "; expected volume " + ps.volumeUuid);
21551            }
21552        }
21553    }
21554
21555    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21556            throws PackageManagerException {
21557        synchronized (mPackages) {
21558            // Normalize package name to handle renamed packages
21559            packageName = normalizePackageNameLPr(packageName);
21560
21561            final PackageSetting ps = mSettings.mPackages.get(packageName);
21562            if (ps == null) {
21563                throw new PackageManagerException("Package " + packageName + " is unknown");
21564            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21565                throw new PackageManagerException(
21566                        "Package " + packageName + " found on unknown volume " + volumeUuid
21567                                + "; expected volume " + ps.volumeUuid);
21568            } else if (!ps.getInstalled(userId)) {
21569                throw new PackageManagerException(
21570                        "Package " + packageName + " not installed for user " + userId);
21571            }
21572        }
21573    }
21574
21575    private List<String> collectAbsoluteCodePaths() {
21576        synchronized (mPackages) {
21577            List<String> codePaths = new ArrayList<>();
21578            final int packageCount = mSettings.mPackages.size();
21579            for (int i = 0; i < packageCount; i++) {
21580                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21581                codePaths.add(ps.codePath.getAbsolutePath());
21582            }
21583            return codePaths;
21584        }
21585    }
21586
21587    /**
21588     * Examine all apps present on given mounted volume, and destroy apps that
21589     * aren't expected, either due to uninstallation or reinstallation on
21590     * another volume.
21591     */
21592    private void reconcileApps(String volumeUuid) {
21593        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21594        List<File> filesToDelete = null;
21595
21596        final File[] files = FileUtils.listFilesOrEmpty(
21597                Environment.getDataAppDirectory(volumeUuid));
21598        for (File file : files) {
21599            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21600                    && !PackageInstallerService.isStageName(file.getName());
21601            if (!isPackage) {
21602                // Ignore entries which are not packages
21603                continue;
21604            }
21605
21606            String absolutePath = file.getAbsolutePath();
21607
21608            boolean pathValid = false;
21609            final int absoluteCodePathCount = absoluteCodePaths.size();
21610            for (int i = 0; i < absoluteCodePathCount; i++) {
21611                String absoluteCodePath = absoluteCodePaths.get(i);
21612                if (absolutePath.startsWith(absoluteCodePath)) {
21613                    pathValid = true;
21614                    break;
21615                }
21616            }
21617
21618            if (!pathValid) {
21619                if (filesToDelete == null) {
21620                    filesToDelete = new ArrayList<>();
21621                }
21622                filesToDelete.add(file);
21623            }
21624        }
21625
21626        if (filesToDelete != null) {
21627            final int fileToDeleteCount = filesToDelete.size();
21628            for (int i = 0; i < fileToDeleteCount; i++) {
21629                File fileToDelete = filesToDelete.get(i);
21630                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21631                synchronized (mInstallLock) {
21632                    removeCodePathLI(fileToDelete);
21633                }
21634            }
21635        }
21636    }
21637
21638    /**
21639     * Reconcile all app data for the given user.
21640     * <p>
21641     * Verifies that directories exist and that ownership and labeling is
21642     * correct for all installed apps on all mounted volumes.
21643     */
21644    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21645        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21646        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21647            final String volumeUuid = vol.getFsUuid();
21648            synchronized (mInstallLock) {
21649                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21650            }
21651        }
21652    }
21653
21654    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21655            boolean migrateAppData) {
21656        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21657    }
21658
21659    /**
21660     * Reconcile all app data on given mounted volume.
21661     * <p>
21662     * Destroys app data that isn't expected, either due to uninstallation or
21663     * reinstallation on another volume.
21664     * <p>
21665     * Verifies that directories exist and that ownership and labeling is
21666     * correct for all installed apps.
21667     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21668     */
21669    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21670            boolean migrateAppData, boolean onlyCoreApps) {
21671        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21672                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21673        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21674
21675        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21676        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21677
21678        // First look for stale data that doesn't belong, and check if things
21679        // have changed since we did our last restorecon
21680        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21681            if (StorageManager.isFileEncryptedNativeOrEmulated()
21682                    && !StorageManager.isUserKeyUnlocked(userId)) {
21683                throw new RuntimeException(
21684                        "Yikes, someone asked us to reconcile CE storage while " + userId
21685                                + " was still locked; this would have caused massive data loss!");
21686            }
21687
21688            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21689            for (File file : files) {
21690                final String packageName = file.getName();
21691                try {
21692                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21693                } catch (PackageManagerException e) {
21694                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21695                    try {
21696                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21697                                StorageManager.FLAG_STORAGE_CE, 0);
21698                    } catch (InstallerException e2) {
21699                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21700                    }
21701                }
21702            }
21703        }
21704        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21705            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21706            for (File file : files) {
21707                final String packageName = file.getName();
21708                try {
21709                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21710                } catch (PackageManagerException e) {
21711                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21712                    try {
21713                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21714                                StorageManager.FLAG_STORAGE_DE, 0);
21715                    } catch (InstallerException e2) {
21716                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21717                    }
21718                }
21719            }
21720        }
21721
21722        // Ensure that data directories are ready to roll for all packages
21723        // installed for this volume and user
21724        final List<PackageSetting> packages;
21725        synchronized (mPackages) {
21726            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21727        }
21728        int preparedCount = 0;
21729        for (PackageSetting ps : packages) {
21730            final String packageName = ps.name;
21731            if (ps.pkg == null) {
21732                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21733                // TODO: might be due to legacy ASEC apps; we should circle back
21734                // and reconcile again once they're scanned
21735                continue;
21736            }
21737            // Skip non-core apps if requested
21738            if (onlyCoreApps && !ps.pkg.coreApp) {
21739                result.add(packageName);
21740                continue;
21741            }
21742
21743            if (ps.getInstalled(userId)) {
21744                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21745                preparedCount++;
21746            }
21747        }
21748
21749        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21750        return result;
21751    }
21752
21753    /**
21754     * Prepare app data for the given app just after it was installed or
21755     * upgraded. This method carefully only touches users that it's installed
21756     * for, and it forces a restorecon to handle any seinfo changes.
21757     * <p>
21758     * Verifies that directories exist and that ownership and labeling is
21759     * correct for all installed apps. If there is an ownership mismatch, it
21760     * will try recovering system apps by wiping data; third-party app data is
21761     * left intact.
21762     * <p>
21763     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21764     */
21765    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21766        final PackageSetting ps;
21767        synchronized (mPackages) {
21768            ps = mSettings.mPackages.get(pkg.packageName);
21769            mSettings.writeKernelMappingLPr(ps);
21770        }
21771
21772        final UserManager um = mContext.getSystemService(UserManager.class);
21773        UserManagerInternal umInternal = getUserManagerInternal();
21774        for (UserInfo user : um.getUsers()) {
21775            final int flags;
21776            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21777                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21778            } else if (umInternal.isUserRunning(user.id)) {
21779                flags = StorageManager.FLAG_STORAGE_DE;
21780            } else {
21781                continue;
21782            }
21783
21784            if (ps.getInstalled(user.id)) {
21785                // TODO: when user data is locked, mark that we're still dirty
21786                prepareAppDataLIF(pkg, user.id, flags);
21787            }
21788        }
21789    }
21790
21791    /**
21792     * Prepare app data for the given app.
21793     * <p>
21794     * Verifies that directories exist and that ownership and labeling is
21795     * correct for all installed apps. If there is an ownership mismatch, this
21796     * will try recovering system apps by wiping data; third-party app data is
21797     * left intact.
21798     */
21799    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21800        if (pkg == null) {
21801            Slog.wtf(TAG, "Package was null!", new Throwable());
21802            return;
21803        }
21804        prepareAppDataLeafLIF(pkg, userId, flags);
21805        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21806        for (int i = 0; i < childCount; i++) {
21807            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21808        }
21809    }
21810
21811    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21812            boolean maybeMigrateAppData) {
21813        prepareAppDataLIF(pkg, userId, flags);
21814
21815        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21816            // We may have just shuffled around app data directories, so
21817            // prepare them one more time
21818            prepareAppDataLIF(pkg, userId, flags);
21819        }
21820    }
21821
21822    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21823        if (DEBUG_APP_DATA) {
21824            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21825                    + Integer.toHexString(flags));
21826        }
21827
21828        final String volumeUuid = pkg.volumeUuid;
21829        final String packageName = pkg.packageName;
21830        final ApplicationInfo app = pkg.applicationInfo;
21831        final int appId = UserHandle.getAppId(app.uid);
21832
21833        Preconditions.checkNotNull(app.seInfo);
21834
21835        long ceDataInode = -1;
21836        try {
21837            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21838                    appId, app.seInfo, app.targetSdkVersion);
21839        } catch (InstallerException e) {
21840            if (app.isSystemApp()) {
21841                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21842                        + ", but trying to recover: " + e);
21843                destroyAppDataLeafLIF(pkg, userId, flags);
21844                try {
21845                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21846                            appId, app.seInfo, app.targetSdkVersion);
21847                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21848                } catch (InstallerException e2) {
21849                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21850                }
21851            } else {
21852                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21853            }
21854        }
21855
21856        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21857            // TODO: mark this structure as dirty so we persist it!
21858            synchronized (mPackages) {
21859                final PackageSetting ps = mSettings.mPackages.get(packageName);
21860                if (ps != null) {
21861                    ps.setCeDataInode(ceDataInode, userId);
21862                }
21863            }
21864        }
21865
21866        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21867    }
21868
21869    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21870        if (pkg == null) {
21871            Slog.wtf(TAG, "Package was null!", new Throwable());
21872            return;
21873        }
21874        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21875        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21876        for (int i = 0; i < childCount; i++) {
21877            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21878        }
21879    }
21880
21881    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21882        final String volumeUuid = pkg.volumeUuid;
21883        final String packageName = pkg.packageName;
21884        final ApplicationInfo app = pkg.applicationInfo;
21885
21886        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21887            // Create a native library symlink only if we have native libraries
21888            // and if the native libraries are 32 bit libraries. We do not provide
21889            // this symlink for 64 bit libraries.
21890            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21891                final String nativeLibPath = app.nativeLibraryDir;
21892                try {
21893                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21894                            nativeLibPath, userId);
21895                } catch (InstallerException e) {
21896                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21897                }
21898            }
21899        }
21900    }
21901
21902    /**
21903     * For system apps on non-FBE devices, this method migrates any existing
21904     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21905     * requested by the app.
21906     */
21907    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21908        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21909                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21910            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21911                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21912            try {
21913                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21914                        storageTarget);
21915            } catch (InstallerException e) {
21916                logCriticalInfo(Log.WARN,
21917                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21918            }
21919            return true;
21920        } else {
21921            return false;
21922        }
21923    }
21924
21925    public PackageFreezer freezePackage(String packageName, String killReason) {
21926        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21927    }
21928
21929    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21930        return new PackageFreezer(packageName, userId, killReason);
21931    }
21932
21933    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21934            String killReason) {
21935        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21936    }
21937
21938    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21939            String killReason) {
21940        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21941            return new PackageFreezer();
21942        } else {
21943            return freezePackage(packageName, userId, killReason);
21944        }
21945    }
21946
21947    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21948            String killReason) {
21949        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21950    }
21951
21952    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21953            String killReason) {
21954        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21955            return new PackageFreezer();
21956        } else {
21957            return freezePackage(packageName, userId, killReason);
21958        }
21959    }
21960
21961    /**
21962     * Class that freezes and kills the given package upon creation, and
21963     * unfreezes it upon closing. This is typically used when doing surgery on
21964     * app code/data to prevent the app from running while you're working.
21965     */
21966    private class PackageFreezer implements AutoCloseable {
21967        private final String mPackageName;
21968        private final PackageFreezer[] mChildren;
21969
21970        private final boolean mWeFroze;
21971
21972        private final AtomicBoolean mClosed = new AtomicBoolean();
21973        private final CloseGuard mCloseGuard = CloseGuard.get();
21974
21975        /**
21976         * Create and return a stub freezer that doesn't actually do anything,
21977         * typically used when someone requested
21978         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21979         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21980         */
21981        public PackageFreezer() {
21982            mPackageName = null;
21983            mChildren = null;
21984            mWeFroze = false;
21985            mCloseGuard.open("close");
21986        }
21987
21988        public PackageFreezer(String packageName, int userId, String killReason) {
21989            synchronized (mPackages) {
21990                mPackageName = packageName;
21991                mWeFroze = mFrozenPackages.add(mPackageName);
21992
21993                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21994                if (ps != null) {
21995                    killApplication(ps.name, ps.appId, userId, killReason);
21996                }
21997
21998                final PackageParser.Package p = mPackages.get(packageName);
21999                if (p != null && p.childPackages != null) {
22000                    final int N = p.childPackages.size();
22001                    mChildren = new PackageFreezer[N];
22002                    for (int i = 0; i < N; i++) {
22003                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22004                                userId, killReason);
22005                    }
22006                } else {
22007                    mChildren = null;
22008                }
22009            }
22010            mCloseGuard.open("close");
22011        }
22012
22013        @Override
22014        protected void finalize() throws Throwable {
22015            try {
22016                mCloseGuard.warnIfOpen();
22017                close();
22018            } finally {
22019                super.finalize();
22020            }
22021        }
22022
22023        @Override
22024        public void close() {
22025            mCloseGuard.close();
22026            if (mClosed.compareAndSet(false, true)) {
22027                synchronized (mPackages) {
22028                    if (mWeFroze) {
22029                        mFrozenPackages.remove(mPackageName);
22030                    }
22031
22032                    if (mChildren != null) {
22033                        for (PackageFreezer freezer : mChildren) {
22034                            freezer.close();
22035                        }
22036                    }
22037                }
22038            }
22039        }
22040    }
22041
22042    /**
22043     * Verify that given package is currently frozen.
22044     */
22045    private void checkPackageFrozen(String packageName) {
22046        synchronized (mPackages) {
22047            if (!mFrozenPackages.contains(packageName)) {
22048                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22049            }
22050        }
22051    }
22052
22053    @Override
22054    public int movePackage(final String packageName, final String volumeUuid) {
22055        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22056
22057        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22058        final int moveId = mNextMoveId.getAndIncrement();
22059        mHandler.post(new Runnable() {
22060            @Override
22061            public void run() {
22062                try {
22063                    movePackageInternal(packageName, volumeUuid, moveId, user);
22064                } catch (PackageManagerException e) {
22065                    Slog.w(TAG, "Failed to move " + packageName, e);
22066                    mMoveCallbacks.notifyStatusChanged(moveId,
22067                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22068                }
22069            }
22070        });
22071        return moveId;
22072    }
22073
22074    private void movePackageInternal(final String packageName, final String volumeUuid,
22075            final int moveId, UserHandle user) throws PackageManagerException {
22076        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22077        final PackageManager pm = mContext.getPackageManager();
22078
22079        final boolean currentAsec;
22080        final String currentVolumeUuid;
22081        final File codeFile;
22082        final String installerPackageName;
22083        final String packageAbiOverride;
22084        final int appId;
22085        final String seinfo;
22086        final String label;
22087        final int targetSdkVersion;
22088        final PackageFreezer freezer;
22089        final int[] installedUserIds;
22090
22091        // reader
22092        synchronized (mPackages) {
22093            final PackageParser.Package pkg = mPackages.get(packageName);
22094            final PackageSetting ps = mSettings.mPackages.get(packageName);
22095            if (pkg == null || ps == null) {
22096                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22097            }
22098
22099            if (pkg.applicationInfo.isSystemApp()) {
22100                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22101                        "Cannot move system application");
22102            }
22103
22104            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22105            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22106                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22107            if (isInternalStorage && !allow3rdPartyOnInternal) {
22108                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22109                        "3rd party apps are not allowed on internal storage");
22110            }
22111
22112            if (pkg.applicationInfo.isExternalAsec()) {
22113                currentAsec = true;
22114                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22115            } else if (pkg.applicationInfo.isForwardLocked()) {
22116                currentAsec = true;
22117                currentVolumeUuid = "forward_locked";
22118            } else {
22119                currentAsec = false;
22120                currentVolumeUuid = ps.volumeUuid;
22121
22122                final File probe = new File(pkg.codePath);
22123                final File probeOat = new File(probe, "oat");
22124                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22125                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22126                            "Move only supported for modern cluster style installs");
22127                }
22128            }
22129
22130            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22131                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22132                        "Package already moved to " + volumeUuid);
22133            }
22134            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22135                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22136                        "Device admin cannot be moved");
22137            }
22138
22139            if (mFrozenPackages.contains(packageName)) {
22140                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22141                        "Failed to move already frozen package");
22142            }
22143
22144            codeFile = new File(pkg.codePath);
22145            installerPackageName = ps.installerPackageName;
22146            packageAbiOverride = ps.cpuAbiOverrideString;
22147            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22148            seinfo = pkg.applicationInfo.seInfo;
22149            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22150            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22151            freezer = freezePackage(packageName, "movePackageInternal");
22152            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22153        }
22154
22155        final Bundle extras = new Bundle();
22156        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22157        extras.putString(Intent.EXTRA_TITLE, label);
22158        mMoveCallbacks.notifyCreated(moveId, extras);
22159
22160        int installFlags;
22161        final boolean moveCompleteApp;
22162        final File measurePath;
22163
22164        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22165            installFlags = INSTALL_INTERNAL;
22166            moveCompleteApp = !currentAsec;
22167            measurePath = Environment.getDataAppDirectory(volumeUuid);
22168        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22169            installFlags = INSTALL_EXTERNAL;
22170            moveCompleteApp = false;
22171            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22172        } else {
22173            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22174            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22175                    || !volume.isMountedWritable()) {
22176                freezer.close();
22177                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22178                        "Move location not mounted private volume");
22179            }
22180
22181            Preconditions.checkState(!currentAsec);
22182
22183            installFlags = INSTALL_INTERNAL;
22184            moveCompleteApp = true;
22185            measurePath = Environment.getDataAppDirectory(volumeUuid);
22186        }
22187
22188        final PackageStats stats = new PackageStats(null, -1);
22189        synchronized (mInstaller) {
22190            for (int userId : installedUserIds) {
22191                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22192                    freezer.close();
22193                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22194                            "Failed to measure package size");
22195                }
22196            }
22197        }
22198
22199        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22200                + stats.dataSize);
22201
22202        final long startFreeBytes = measurePath.getFreeSpace();
22203        final long sizeBytes;
22204        if (moveCompleteApp) {
22205            sizeBytes = stats.codeSize + stats.dataSize;
22206        } else {
22207            sizeBytes = stats.codeSize;
22208        }
22209
22210        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22211            freezer.close();
22212            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22213                    "Not enough free space to move");
22214        }
22215
22216        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22217
22218        final CountDownLatch installedLatch = new CountDownLatch(1);
22219        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22220            @Override
22221            public void onUserActionRequired(Intent intent) throws RemoteException {
22222                throw new IllegalStateException();
22223            }
22224
22225            @Override
22226            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22227                    Bundle extras) throws RemoteException {
22228                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22229                        + PackageManager.installStatusToString(returnCode, msg));
22230
22231                installedLatch.countDown();
22232                freezer.close();
22233
22234                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22235                switch (status) {
22236                    case PackageInstaller.STATUS_SUCCESS:
22237                        mMoveCallbacks.notifyStatusChanged(moveId,
22238                                PackageManager.MOVE_SUCCEEDED);
22239                        break;
22240                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22241                        mMoveCallbacks.notifyStatusChanged(moveId,
22242                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22243                        break;
22244                    default:
22245                        mMoveCallbacks.notifyStatusChanged(moveId,
22246                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22247                        break;
22248                }
22249            }
22250        };
22251
22252        final MoveInfo move;
22253        if (moveCompleteApp) {
22254            // Kick off a thread to report progress estimates
22255            new Thread() {
22256                @Override
22257                public void run() {
22258                    while (true) {
22259                        try {
22260                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22261                                break;
22262                            }
22263                        } catch (InterruptedException ignored) {
22264                        }
22265
22266                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22267                        final int progress = 10 + (int) MathUtils.constrain(
22268                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22269                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22270                    }
22271                }
22272            }.start();
22273
22274            final String dataAppName = codeFile.getName();
22275            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22276                    dataAppName, appId, seinfo, targetSdkVersion);
22277        } else {
22278            move = null;
22279        }
22280
22281        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22282
22283        final Message msg = mHandler.obtainMessage(INIT_COPY);
22284        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22285        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22286                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22287                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22288                PackageManager.INSTALL_REASON_UNKNOWN);
22289        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22290        msg.obj = params;
22291
22292        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22293                System.identityHashCode(msg.obj));
22294        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22295                System.identityHashCode(msg.obj));
22296
22297        mHandler.sendMessage(msg);
22298    }
22299
22300    @Override
22301    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22302        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22303
22304        final int realMoveId = mNextMoveId.getAndIncrement();
22305        final Bundle extras = new Bundle();
22306        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22307        mMoveCallbacks.notifyCreated(realMoveId, extras);
22308
22309        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22310            @Override
22311            public void onCreated(int moveId, Bundle extras) {
22312                // Ignored
22313            }
22314
22315            @Override
22316            public void onStatusChanged(int moveId, int status, long estMillis) {
22317                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22318            }
22319        };
22320
22321        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22322        storage.setPrimaryStorageUuid(volumeUuid, callback);
22323        return realMoveId;
22324    }
22325
22326    @Override
22327    public int getMoveStatus(int moveId) {
22328        mContext.enforceCallingOrSelfPermission(
22329                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22330        return mMoveCallbacks.mLastStatus.get(moveId);
22331    }
22332
22333    @Override
22334    public void registerMoveCallback(IPackageMoveObserver callback) {
22335        mContext.enforceCallingOrSelfPermission(
22336                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22337        mMoveCallbacks.register(callback);
22338    }
22339
22340    @Override
22341    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22342        mContext.enforceCallingOrSelfPermission(
22343                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22344        mMoveCallbacks.unregister(callback);
22345    }
22346
22347    @Override
22348    public boolean setInstallLocation(int loc) {
22349        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22350                null);
22351        if (getInstallLocation() == loc) {
22352            return true;
22353        }
22354        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22355                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22356            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22357                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22358            return true;
22359        }
22360        return false;
22361   }
22362
22363    @Override
22364    public int getInstallLocation() {
22365        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22366                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22367                PackageHelper.APP_INSTALL_AUTO);
22368    }
22369
22370    /** Called by UserManagerService */
22371    void cleanUpUser(UserManagerService userManager, int userHandle) {
22372        synchronized (mPackages) {
22373            mDirtyUsers.remove(userHandle);
22374            mUserNeedsBadging.delete(userHandle);
22375            mSettings.removeUserLPw(userHandle);
22376            mPendingBroadcasts.remove(userHandle);
22377            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22378            removeUnusedPackagesLPw(userManager, userHandle);
22379        }
22380    }
22381
22382    /**
22383     * We're removing userHandle and would like to remove any downloaded packages
22384     * that are no longer in use by any other user.
22385     * @param userHandle the user being removed
22386     */
22387    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22388        final boolean DEBUG_CLEAN_APKS = false;
22389        int [] users = userManager.getUserIds();
22390        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22391        while (psit.hasNext()) {
22392            PackageSetting ps = psit.next();
22393            if (ps.pkg == null) {
22394                continue;
22395            }
22396            final String packageName = ps.pkg.packageName;
22397            // Skip over if system app
22398            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22399                continue;
22400            }
22401            if (DEBUG_CLEAN_APKS) {
22402                Slog.i(TAG, "Checking package " + packageName);
22403            }
22404            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22405            if (keep) {
22406                if (DEBUG_CLEAN_APKS) {
22407                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22408                }
22409            } else {
22410                for (int i = 0; i < users.length; i++) {
22411                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22412                        keep = true;
22413                        if (DEBUG_CLEAN_APKS) {
22414                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22415                                    + users[i]);
22416                        }
22417                        break;
22418                    }
22419                }
22420            }
22421            if (!keep) {
22422                if (DEBUG_CLEAN_APKS) {
22423                    Slog.i(TAG, "  Removing package " + packageName);
22424                }
22425                mHandler.post(new Runnable() {
22426                    public void run() {
22427                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22428                                userHandle, 0);
22429                    } //end run
22430                });
22431            }
22432        }
22433    }
22434
22435    /** Called by UserManagerService */
22436    void createNewUser(int userId, String[] disallowedPackages) {
22437        synchronized (mInstallLock) {
22438            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22439        }
22440        synchronized (mPackages) {
22441            scheduleWritePackageRestrictionsLocked(userId);
22442            scheduleWritePackageListLocked(userId);
22443            applyFactoryDefaultBrowserLPw(userId);
22444            primeDomainVerificationsLPw(userId);
22445        }
22446    }
22447
22448    void onNewUserCreated(final int userId) {
22449        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22450        // If permission review for legacy apps is required, we represent
22451        // dagerous permissions for such apps as always granted runtime
22452        // permissions to keep per user flag state whether review is needed.
22453        // Hence, if a new user is added we have to propagate dangerous
22454        // permission grants for these legacy apps.
22455        if (mPermissionReviewRequired) {
22456            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22457                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22458        }
22459    }
22460
22461    @Override
22462    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22463        mContext.enforceCallingOrSelfPermission(
22464                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22465                "Only package verification agents can read the verifier device identity");
22466
22467        synchronized (mPackages) {
22468            return mSettings.getVerifierDeviceIdentityLPw();
22469        }
22470    }
22471
22472    @Override
22473    public void setPermissionEnforced(String permission, boolean enforced) {
22474        // TODO: Now that we no longer change GID for storage, this should to away.
22475        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22476                "setPermissionEnforced");
22477        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22478            synchronized (mPackages) {
22479                if (mSettings.mReadExternalStorageEnforced == null
22480                        || mSettings.mReadExternalStorageEnforced != enforced) {
22481                    mSettings.mReadExternalStorageEnforced = enforced;
22482                    mSettings.writeLPr();
22483                }
22484            }
22485            // kill any non-foreground processes so we restart them and
22486            // grant/revoke the GID.
22487            final IActivityManager am = ActivityManager.getService();
22488            if (am != null) {
22489                final long token = Binder.clearCallingIdentity();
22490                try {
22491                    am.killProcessesBelowForeground("setPermissionEnforcement");
22492                } catch (RemoteException e) {
22493                } finally {
22494                    Binder.restoreCallingIdentity(token);
22495                }
22496            }
22497        } else {
22498            throw new IllegalArgumentException("No selective enforcement for " + permission);
22499        }
22500    }
22501
22502    @Override
22503    @Deprecated
22504    public boolean isPermissionEnforced(String permission) {
22505        return true;
22506    }
22507
22508    @Override
22509    public boolean isStorageLow() {
22510        final long token = Binder.clearCallingIdentity();
22511        try {
22512            final DeviceStorageMonitorInternal
22513                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22514            if (dsm != null) {
22515                return dsm.isMemoryLow();
22516            } else {
22517                return false;
22518            }
22519        } finally {
22520            Binder.restoreCallingIdentity(token);
22521        }
22522    }
22523
22524    @Override
22525    public IPackageInstaller getPackageInstaller() {
22526        return mInstallerService;
22527    }
22528
22529    private boolean userNeedsBadging(int userId) {
22530        int index = mUserNeedsBadging.indexOfKey(userId);
22531        if (index < 0) {
22532            final UserInfo userInfo;
22533            final long token = Binder.clearCallingIdentity();
22534            try {
22535                userInfo = sUserManager.getUserInfo(userId);
22536            } finally {
22537                Binder.restoreCallingIdentity(token);
22538            }
22539            final boolean b;
22540            if (userInfo != null && userInfo.isManagedProfile()) {
22541                b = true;
22542            } else {
22543                b = false;
22544            }
22545            mUserNeedsBadging.put(userId, b);
22546            return b;
22547        }
22548        return mUserNeedsBadging.valueAt(index);
22549    }
22550
22551    @Override
22552    public KeySet getKeySetByAlias(String packageName, String alias) {
22553        if (packageName == null || alias == null) {
22554            return null;
22555        }
22556        synchronized(mPackages) {
22557            final PackageParser.Package pkg = mPackages.get(packageName);
22558            if (pkg == null) {
22559                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22560                throw new IllegalArgumentException("Unknown package: " + packageName);
22561            }
22562            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22563            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22564        }
22565    }
22566
22567    @Override
22568    public KeySet getSigningKeySet(String packageName) {
22569        if (packageName == null) {
22570            return null;
22571        }
22572        synchronized(mPackages) {
22573            final PackageParser.Package pkg = mPackages.get(packageName);
22574            if (pkg == null) {
22575                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22576                throw new IllegalArgumentException("Unknown package: " + packageName);
22577            }
22578            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22579                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22580                throw new SecurityException("May not access signing KeySet of other apps.");
22581            }
22582            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22583            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22584        }
22585    }
22586
22587    @Override
22588    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22589        if (packageName == null || ks == null) {
22590            return false;
22591        }
22592        synchronized(mPackages) {
22593            final PackageParser.Package pkg = mPackages.get(packageName);
22594            if (pkg == null) {
22595                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22596                throw new IllegalArgumentException("Unknown package: " + packageName);
22597            }
22598            IBinder ksh = ks.getToken();
22599            if (ksh instanceof KeySetHandle) {
22600                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22601                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22602            }
22603            return false;
22604        }
22605    }
22606
22607    @Override
22608    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22609        if (packageName == null || ks == null) {
22610            return false;
22611        }
22612        synchronized(mPackages) {
22613            final PackageParser.Package pkg = mPackages.get(packageName);
22614            if (pkg == null) {
22615                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22616                throw new IllegalArgumentException("Unknown package: " + packageName);
22617            }
22618            IBinder ksh = ks.getToken();
22619            if (ksh instanceof KeySetHandle) {
22620                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22621                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22622            }
22623            return false;
22624        }
22625    }
22626
22627    private void deletePackageIfUnusedLPr(final String packageName) {
22628        PackageSetting ps = mSettings.mPackages.get(packageName);
22629        if (ps == null) {
22630            return;
22631        }
22632        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22633            // TODO Implement atomic delete if package is unused
22634            // It is currently possible that the package will be deleted even if it is installed
22635            // after this method returns.
22636            mHandler.post(new Runnable() {
22637                public void run() {
22638                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22639                            0, PackageManager.DELETE_ALL_USERS);
22640                }
22641            });
22642        }
22643    }
22644
22645    /**
22646     * Check and throw if the given before/after packages would be considered a
22647     * downgrade.
22648     */
22649    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22650            throws PackageManagerException {
22651        if (after.versionCode < before.mVersionCode) {
22652            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22653                    "Update version code " + after.versionCode + " is older than current "
22654                    + before.mVersionCode);
22655        } else if (after.versionCode == before.mVersionCode) {
22656            if (after.baseRevisionCode < before.baseRevisionCode) {
22657                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22658                        "Update base revision code " + after.baseRevisionCode
22659                        + " is older than current " + before.baseRevisionCode);
22660            }
22661
22662            if (!ArrayUtils.isEmpty(after.splitNames)) {
22663                for (int i = 0; i < after.splitNames.length; i++) {
22664                    final String splitName = after.splitNames[i];
22665                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22666                    if (j != -1) {
22667                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22668                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22669                                    "Update split " + splitName + " revision code "
22670                                    + after.splitRevisionCodes[i] + " is older than current "
22671                                    + before.splitRevisionCodes[j]);
22672                        }
22673                    }
22674                }
22675            }
22676        }
22677    }
22678
22679    private static class MoveCallbacks extends Handler {
22680        private static final int MSG_CREATED = 1;
22681        private static final int MSG_STATUS_CHANGED = 2;
22682
22683        private final RemoteCallbackList<IPackageMoveObserver>
22684                mCallbacks = new RemoteCallbackList<>();
22685
22686        private final SparseIntArray mLastStatus = new SparseIntArray();
22687
22688        public MoveCallbacks(Looper looper) {
22689            super(looper);
22690        }
22691
22692        public void register(IPackageMoveObserver callback) {
22693            mCallbacks.register(callback);
22694        }
22695
22696        public void unregister(IPackageMoveObserver callback) {
22697            mCallbacks.unregister(callback);
22698        }
22699
22700        @Override
22701        public void handleMessage(Message msg) {
22702            final SomeArgs args = (SomeArgs) msg.obj;
22703            final int n = mCallbacks.beginBroadcast();
22704            for (int i = 0; i < n; i++) {
22705                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22706                try {
22707                    invokeCallback(callback, msg.what, args);
22708                } catch (RemoteException ignored) {
22709                }
22710            }
22711            mCallbacks.finishBroadcast();
22712            args.recycle();
22713        }
22714
22715        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22716                throws RemoteException {
22717            switch (what) {
22718                case MSG_CREATED: {
22719                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22720                    break;
22721                }
22722                case MSG_STATUS_CHANGED: {
22723                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22724                    break;
22725                }
22726            }
22727        }
22728
22729        private void notifyCreated(int moveId, Bundle extras) {
22730            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22731
22732            final SomeArgs args = SomeArgs.obtain();
22733            args.argi1 = moveId;
22734            args.arg2 = extras;
22735            obtainMessage(MSG_CREATED, args).sendToTarget();
22736        }
22737
22738        private void notifyStatusChanged(int moveId, int status) {
22739            notifyStatusChanged(moveId, status, -1);
22740        }
22741
22742        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22743            Slog.v(TAG, "Move " + moveId + " status " + status);
22744
22745            final SomeArgs args = SomeArgs.obtain();
22746            args.argi1 = moveId;
22747            args.argi2 = status;
22748            args.arg3 = estMillis;
22749            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22750
22751            synchronized (mLastStatus) {
22752                mLastStatus.put(moveId, status);
22753            }
22754        }
22755    }
22756
22757    private final static class OnPermissionChangeListeners extends Handler {
22758        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22759
22760        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22761                new RemoteCallbackList<>();
22762
22763        public OnPermissionChangeListeners(Looper looper) {
22764            super(looper);
22765        }
22766
22767        @Override
22768        public void handleMessage(Message msg) {
22769            switch (msg.what) {
22770                case MSG_ON_PERMISSIONS_CHANGED: {
22771                    final int uid = msg.arg1;
22772                    handleOnPermissionsChanged(uid);
22773                } break;
22774            }
22775        }
22776
22777        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22778            mPermissionListeners.register(listener);
22779
22780        }
22781
22782        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22783            mPermissionListeners.unregister(listener);
22784        }
22785
22786        public void onPermissionsChanged(int uid) {
22787            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22788                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22789            }
22790        }
22791
22792        private void handleOnPermissionsChanged(int uid) {
22793            final int count = mPermissionListeners.beginBroadcast();
22794            try {
22795                for (int i = 0; i < count; i++) {
22796                    IOnPermissionsChangeListener callback = mPermissionListeners
22797                            .getBroadcastItem(i);
22798                    try {
22799                        callback.onPermissionsChanged(uid);
22800                    } catch (RemoteException e) {
22801                        Log.e(TAG, "Permission listener is dead", e);
22802                    }
22803                }
22804            } finally {
22805                mPermissionListeners.finishBroadcast();
22806            }
22807        }
22808    }
22809
22810    private class PackageManagerInternalImpl extends PackageManagerInternal {
22811        @Override
22812        public void setLocationPackagesProvider(PackagesProvider provider) {
22813            synchronized (mPackages) {
22814                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22815            }
22816        }
22817
22818        @Override
22819        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22820            synchronized (mPackages) {
22821                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22822            }
22823        }
22824
22825        @Override
22826        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22827            synchronized (mPackages) {
22828                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22829            }
22830        }
22831
22832        @Override
22833        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22834            synchronized (mPackages) {
22835                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22836            }
22837        }
22838
22839        @Override
22840        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22841            synchronized (mPackages) {
22842                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22843            }
22844        }
22845
22846        @Override
22847        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22848            synchronized (mPackages) {
22849                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22850            }
22851        }
22852
22853        @Override
22854        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22855            synchronized (mPackages) {
22856                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22857                        packageName, userId);
22858            }
22859        }
22860
22861        @Override
22862        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22863            synchronized (mPackages) {
22864                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22865                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22866                        packageName, userId);
22867            }
22868        }
22869
22870        @Override
22871        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22872            synchronized (mPackages) {
22873                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22874                        packageName, userId);
22875            }
22876        }
22877
22878        @Override
22879        public void setKeepUninstalledPackages(final List<String> packageList) {
22880            Preconditions.checkNotNull(packageList);
22881            List<String> removedFromList = null;
22882            synchronized (mPackages) {
22883                if (mKeepUninstalledPackages != null) {
22884                    final int packagesCount = mKeepUninstalledPackages.size();
22885                    for (int i = 0; i < packagesCount; i++) {
22886                        String oldPackage = mKeepUninstalledPackages.get(i);
22887                        if (packageList != null && packageList.contains(oldPackage)) {
22888                            continue;
22889                        }
22890                        if (removedFromList == null) {
22891                            removedFromList = new ArrayList<>();
22892                        }
22893                        removedFromList.add(oldPackage);
22894                    }
22895                }
22896                mKeepUninstalledPackages = new ArrayList<>(packageList);
22897                if (removedFromList != null) {
22898                    final int removedCount = removedFromList.size();
22899                    for (int i = 0; i < removedCount; i++) {
22900                        deletePackageIfUnusedLPr(removedFromList.get(i));
22901                    }
22902                }
22903            }
22904        }
22905
22906        @Override
22907        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22908            synchronized (mPackages) {
22909                // If we do not support permission review, done.
22910                if (!mPermissionReviewRequired) {
22911                    return false;
22912                }
22913
22914                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22915                if (packageSetting == null) {
22916                    return false;
22917                }
22918
22919                // Permission review applies only to apps not supporting the new permission model.
22920                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22921                    return false;
22922                }
22923
22924                // Legacy apps have the permission and get user consent on launch.
22925                PermissionsState permissionsState = packageSetting.getPermissionsState();
22926                return permissionsState.isPermissionReviewRequired(userId);
22927            }
22928        }
22929
22930        @Override
22931        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22932            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22933        }
22934
22935        @Override
22936        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22937                int userId) {
22938            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22939        }
22940
22941        @Override
22942        public void setDeviceAndProfileOwnerPackages(
22943                int deviceOwnerUserId, String deviceOwnerPackage,
22944                SparseArray<String> profileOwnerPackages) {
22945            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22946                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22947        }
22948
22949        @Override
22950        public boolean isPackageDataProtected(int userId, String packageName) {
22951            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22952        }
22953
22954        @Override
22955        public boolean isPackageEphemeral(int userId, String packageName) {
22956            synchronized (mPackages) {
22957                final PackageSetting ps = mSettings.mPackages.get(packageName);
22958                return ps != null ? ps.getInstantApp(userId) : false;
22959            }
22960        }
22961
22962        @Override
22963        public boolean wasPackageEverLaunched(String packageName, int userId) {
22964            synchronized (mPackages) {
22965                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22966            }
22967        }
22968
22969        @Override
22970        public void grantRuntimePermission(String packageName, String name, int userId,
22971                boolean overridePolicy) {
22972            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22973                    overridePolicy);
22974        }
22975
22976        @Override
22977        public void revokeRuntimePermission(String packageName, String name, int userId,
22978                boolean overridePolicy) {
22979            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22980                    overridePolicy);
22981        }
22982
22983        @Override
22984        public String getNameForUid(int uid) {
22985            return PackageManagerService.this.getNameForUid(uid);
22986        }
22987
22988        @Override
22989        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22990                Intent origIntent, String resolvedType, String callingPackage, int userId) {
22991            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22992                    responseObj, origIntent, resolvedType, callingPackage, userId);
22993        }
22994
22995        @Override
22996        public void grantEphemeralAccess(int userId, Intent intent,
22997                int targetAppId, int ephemeralAppId) {
22998            synchronized (mPackages) {
22999                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23000                        targetAppId, ephemeralAppId);
23001            }
23002        }
23003
23004        @Override
23005        public void pruneInstantApps() {
23006            synchronized (mPackages) {
23007                mInstantAppRegistry.pruneInstantAppsLPw();
23008            }
23009        }
23010
23011        @Override
23012        public String getSetupWizardPackageName() {
23013            return mSetupWizardPackage;
23014        }
23015
23016        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23017            if (policy != null) {
23018                mExternalSourcesPolicy = policy;
23019            }
23020        }
23021
23022        @Override
23023        public boolean isPackagePersistent(String packageName) {
23024            synchronized (mPackages) {
23025                PackageParser.Package pkg = mPackages.get(packageName);
23026                return pkg != null
23027                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23028                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23029                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23030                        : false;
23031            }
23032        }
23033
23034        @Override
23035        public List<PackageInfo> getOverlayPackages(int userId) {
23036            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23037            synchronized (mPackages) {
23038                for (PackageParser.Package p : mPackages.values()) {
23039                    if (p.mOverlayTarget != null) {
23040                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23041                        if (pkg != null) {
23042                            overlayPackages.add(pkg);
23043                        }
23044                    }
23045                }
23046            }
23047            return overlayPackages;
23048        }
23049
23050        @Override
23051        public List<String> getTargetPackageNames(int userId) {
23052            List<String> targetPackages = new ArrayList<>();
23053            synchronized (mPackages) {
23054                for (PackageParser.Package p : mPackages.values()) {
23055                    if (p.mOverlayTarget == null) {
23056                        targetPackages.add(p.packageName);
23057                    }
23058                }
23059            }
23060            return targetPackages;
23061        }
23062
23063        @Override
23064        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23065                @Nullable List<String> overlayPackageNames) {
23066            synchronized (mPackages) {
23067                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23068                    Slog.e(TAG, "failed to find package " + targetPackageName);
23069                    return false;
23070                }
23071
23072                ArrayList<String> paths = null;
23073                if (overlayPackageNames != null) {
23074                    final int N = overlayPackageNames.size();
23075                    paths = new ArrayList<>(N);
23076                    for (int i = 0; i < N; i++) {
23077                        final String packageName = overlayPackageNames.get(i);
23078                        final PackageParser.Package pkg = mPackages.get(packageName);
23079                        if (pkg == null) {
23080                            Slog.e(TAG, "failed to find package " + packageName);
23081                            return false;
23082                        }
23083                        paths.add(pkg.baseCodePath);
23084                    }
23085                }
23086
23087                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23088                    mEnabledOverlayPaths.get(userId);
23089                if (userSpecificOverlays == null) {
23090                    userSpecificOverlays = new ArrayMap<>();
23091                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23092                }
23093
23094                if (paths != null && paths.size() > 0) {
23095                    userSpecificOverlays.put(targetPackageName, paths);
23096                } else {
23097                    userSpecificOverlays.remove(targetPackageName);
23098                }
23099                return true;
23100            }
23101        }
23102
23103        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23104                int flags, int userId) {
23105            return resolveIntentInternal(
23106                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23107        }
23108    }
23109
23110    @Override
23111    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23112        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23113        synchronized (mPackages) {
23114            final long identity = Binder.clearCallingIdentity();
23115            try {
23116                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23117                        packageNames, userId);
23118            } finally {
23119                Binder.restoreCallingIdentity(identity);
23120            }
23121        }
23122    }
23123
23124    @Override
23125    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23126        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23127        synchronized (mPackages) {
23128            final long identity = Binder.clearCallingIdentity();
23129            try {
23130                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23131                        packageNames, userId);
23132            } finally {
23133                Binder.restoreCallingIdentity(identity);
23134            }
23135        }
23136    }
23137
23138    private static void enforceSystemOrPhoneCaller(String tag) {
23139        int callingUid = Binder.getCallingUid();
23140        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23141            throw new SecurityException(
23142                    "Cannot call " + tag + " from UID " + callingUid);
23143        }
23144    }
23145
23146    boolean isHistoricalPackageUsageAvailable() {
23147        return mPackageUsage.isHistoricalPackageUsageAvailable();
23148    }
23149
23150    /**
23151     * Return a <b>copy</b> of the collection of packages known to the package manager.
23152     * @return A copy of the values of mPackages.
23153     */
23154    Collection<PackageParser.Package> getPackages() {
23155        synchronized (mPackages) {
23156            return new ArrayList<>(mPackages.values());
23157        }
23158    }
23159
23160    /**
23161     * Logs process start information (including base APK hash) to the security log.
23162     * @hide
23163     */
23164    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23165            String apkFile, int pid) {
23166        if (!SecurityLog.isLoggingEnabled()) {
23167            return;
23168        }
23169        Bundle data = new Bundle();
23170        data.putLong("startTimestamp", System.currentTimeMillis());
23171        data.putString("processName", processName);
23172        data.putInt("uid", uid);
23173        data.putString("seinfo", seinfo);
23174        data.putString("apkFile", apkFile);
23175        data.putInt("pid", pid);
23176        Message msg = mProcessLoggingHandler.obtainMessage(
23177                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23178        msg.setData(data);
23179        mProcessLoggingHandler.sendMessage(msg);
23180    }
23181
23182    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23183        return mCompilerStats.getPackageStats(pkgName);
23184    }
23185
23186    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23187        return getOrCreateCompilerPackageStats(pkg.packageName);
23188    }
23189
23190    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23191        return mCompilerStats.getOrCreatePackageStats(pkgName);
23192    }
23193
23194    public void deleteCompilerPackageStats(String pkgName) {
23195        mCompilerStats.deletePackageStats(pkgName);
23196    }
23197
23198    @Override
23199    public int getInstallReason(String packageName, int userId) {
23200        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23201                true /* requireFullPermission */, false /* checkShell */,
23202                "get install reason");
23203        synchronized (mPackages) {
23204            final PackageSetting ps = mSettings.mPackages.get(packageName);
23205            if (ps != null) {
23206                return ps.getInstallReason(userId);
23207            }
23208        }
23209        return PackageManager.INSTALL_REASON_UNKNOWN;
23210    }
23211
23212    @Override
23213    public boolean canRequestPackageInstalls(String packageName, int userId) {
23214        int callingUid = Binder.getCallingUid();
23215        int uid = getPackageUid(packageName, 0, userId);
23216        if (callingUid != uid && callingUid != Process.ROOT_UID
23217                && callingUid != Process.SYSTEM_UID) {
23218            throw new SecurityException(
23219                    "Caller uid " + callingUid + " does not own package " + packageName);
23220        }
23221        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23222        if (info == null) {
23223            return false;
23224        }
23225        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23226            throw new UnsupportedOperationException(
23227                    "Operation only supported on apps targeting Android O or higher");
23228        }
23229        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23230        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23231        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23232            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23233        }
23234        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23235            return false;
23236        }
23237        if (mExternalSourcesPolicy != null) {
23238            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23239            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23240                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23241            }
23242        }
23243        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23244    }
23245}
23246