PackageManagerService.java revision 8e9bcec1e470ddeeb375b26bb273f4122057bd17
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
103
104import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
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.ServiceInfo;
168import android.content.pm.SharedLibraryInfo;
169import android.content.pm.Signature;
170import android.content.pm.UserInfo;
171import android.content.pm.VerifierDeviceIdentity;
172import android.content.pm.VerifierInfo;
173import android.content.pm.VersionedPackage;
174import android.content.res.Resources;
175import android.database.ContentObserver;
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.BootTimingsTraceLog;
225import android.util.DisplayMetrics;
226import android.util.EventLog;
227import android.util.ExceptionUtils;
228import android.util.Log;
229import android.util.LogPrinter;
230import android.util.MathUtils;
231import android.util.PackageUtils;
232import android.util.Pair;
233import android.util.PrintStreamPrinter;
234import android.util.Slog;
235import android.util.SparseArray;
236import android.util.SparseBooleanArray;
237import android.util.SparseIntArray;
238import android.util.Xml;
239import android.util.jar.StrictJarFile;
240import android.util.proto.ProtoOutputStream;
241import android.view.Display;
242
243import com.android.internal.R;
244import com.android.internal.annotations.GuardedBy;
245import com.android.internal.app.IMediaContainerService;
246import com.android.internal.app.ResolverActivity;
247import com.android.internal.content.NativeLibraryHelper;
248import com.android.internal.content.PackageHelper;
249import com.android.internal.logging.MetricsLogger;
250import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
251import com.android.internal.os.IParcelFileDescriptorFactory;
252import com.android.internal.os.RoSystemProperties;
253import com.android.internal.os.SomeArgs;
254import com.android.internal.os.Zygote;
255import com.android.internal.telephony.CarrierAppUtils;
256import com.android.internal.util.ArrayUtils;
257import com.android.internal.util.ConcurrentUtils;
258import com.android.internal.util.DumpUtils;
259import com.android.internal.util.FastPrintWriter;
260import com.android.internal.util.FastXmlSerializer;
261import com.android.internal.util.IndentingPrintWriter;
262import com.android.internal.util.Preconditions;
263import com.android.internal.util.XmlUtils;
264import com.android.server.AttributeCache;
265import com.android.server.DeviceIdleController;
266import com.android.server.EventLogTags;
267import com.android.server.FgThread;
268import com.android.server.IntentResolver;
269import com.android.server.LocalServices;
270import com.android.server.LockGuard;
271import com.android.server.ServiceThread;
272import com.android.server.SystemConfig;
273import com.android.server.SystemServerInitThreadPool;
274import com.android.server.Watchdog;
275import com.android.server.net.NetworkPolicyManagerInternal;
276import com.android.server.pm.Installer.InstallerException;
277import com.android.server.pm.PermissionsState.PermissionState;
278import com.android.server.pm.Settings.DatabaseVersion;
279import com.android.server.pm.Settings.VersionInfo;
280import com.android.server.pm.dex.DexManager;
281import com.android.server.storage.DeviceStorageMonitorInternal;
282
283import dalvik.system.CloseGuard;
284import dalvik.system.DexFile;
285import dalvik.system.VMRuntime;
286
287import libcore.io.IoUtils;
288import libcore.util.EmptyArray;
289
290import org.xmlpull.v1.XmlPullParser;
291import org.xmlpull.v1.XmlPullParserException;
292import org.xmlpull.v1.XmlSerializer;
293
294import java.io.BufferedOutputStream;
295import java.io.BufferedReader;
296import java.io.ByteArrayInputStream;
297import java.io.ByteArrayOutputStream;
298import java.io.File;
299import java.io.FileDescriptor;
300import java.io.FileInputStream;
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        implements PackageSender {
370    static final String TAG = "PackageManager";
371    static final boolean DEBUG_SETTINGS = false;
372    static final boolean DEBUG_PREFERRED = false;
373    static final boolean DEBUG_UPGRADE = false;
374    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
375    private static final boolean DEBUG_BACKUP = false;
376    private static final boolean DEBUG_INSTALL = false;
377    private static final boolean DEBUG_REMOVE = false;
378    private static final boolean DEBUG_BROADCASTS = false;
379    private static final boolean DEBUG_SHOW_INFO = false;
380    private static final boolean DEBUG_PACKAGE_INFO = false;
381    private static final boolean DEBUG_INTENT_MATCHING = false;
382    private static final boolean DEBUG_PACKAGE_SCANNING = false;
383    private static final boolean DEBUG_VERIFY = false;
384    private static final boolean DEBUG_FILTERS = false;
385    private static final boolean DEBUG_PERMISSIONS = false;
386    private static final boolean DEBUG_SHARED_LIBRARIES = false;
387
388    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
389    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
390    // user, but by default initialize to this.
391    public static final boolean DEBUG_DEXOPT = false;
392
393    private static final boolean DEBUG_ABI_SELECTION = false;
394    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
395    private static final boolean DEBUG_TRIAGED_MISSING = false;
396    private static final boolean DEBUG_APP_DATA = false;
397
398    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
399    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
400
401    private static final boolean HIDE_EPHEMERAL_APIS = false;
402
403    private static final boolean ENABLE_FREE_CACHE_V2 =
404            SystemProperties.getBoolean("fw.free_cache_v2", true);
405
406    private static final int RADIO_UID = Process.PHONE_UID;
407    private static final int LOG_UID = Process.LOG_UID;
408    private static final int NFC_UID = Process.NFC_UID;
409    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
410    private static final int SHELL_UID = Process.SHELL_UID;
411
412    // Cap the size of permission trees that 3rd party apps can define
413    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
414
415    // Suffix used during package installation when copying/moving
416    // package apks to install directory.
417    private static final String INSTALL_PACKAGE_SUFFIX = "-";
418
419    static final int SCAN_NO_DEX = 1<<1;
420    static final int SCAN_FORCE_DEX = 1<<2;
421    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
422    static final int SCAN_NEW_INSTALL = 1<<4;
423    static final int SCAN_UPDATE_TIME = 1<<5;
424    static final int SCAN_BOOTING = 1<<6;
425    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
426    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
427    static final int SCAN_REPLACING = 1<<9;
428    static final int SCAN_REQUIRE_KNOWN = 1<<10;
429    static final int SCAN_MOVE = 1<<11;
430    static final int SCAN_INITIAL = 1<<12;
431    static final int SCAN_CHECK_ONLY = 1<<13;
432    static final int SCAN_DONT_KILL_APP = 1<<14;
433    static final int SCAN_IGNORE_FROZEN = 1<<15;
434    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
435    static final int SCAN_AS_INSTANT_APP = 1<<17;
436    static final int SCAN_AS_FULL_APP = 1<<18;
437    /** Should not be with the scan flags */
438    static final int FLAGS_REMOVE_CHATTY = 1<<31;
439
440    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
441
442    private static final int[] EMPTY_INT_ARRAY = new int[0];
443
444    /**
445     * Timeout (in milliseconds) after which the watchdog should declare that
446     * our handler thread is wedged.  The usual default for such things is one
447     * minute but we sometimes do very lengthy I/O operations on this thread,
448     * such as installing multi-gigabyte applications, so ours needs to be longer.
449     */
450    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
451
452    /**
453     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
454     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
455     * settings entry if available, otherwise we use the hardcoded default.  If it's been
456     * more than this long since the last fstrim, we force one during the boot sequence.
457     *
458     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
459     * one gets run at the next available charging+idle time.  This final mandatory
460     * no-fstrim check kicks in only of the other scheduling criteria is never met.
461     */
462    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
463
464    /**
465     * Whether verification is enabled by default.
466     */
467    private static final boolean DEFAULT_VERIFY_ENABLE = true;
468
469    /**
470     * The default maximum time to wait for the verification agent to return in
471     * milliseconds.
472     */
473    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
474
475    /**
476     * The default response for package verification timeout.
477     *
478     * This can be either PackageManager.VERIFICATION_ALLOW or
479     * PackageManager.VERIFICATION_REJECT.
480     */
481    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
482
483    static final String PLATFORM_PACKAGE_NAME = "android";
484
485    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
486
487    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
488            DEFAULT_CONTAINER_PACKAGE,
489            "com.android.defcontainer.DefaultContainerService");
490
491    private static final String KILL_APP_REASON_GIDS_CHANGED =
492            "permission grant or revoke changed gids";
493
494    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
495            "permissions revoked";
496
497    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
498
499    private static final String PACKAGE_SCHEME = "package";
500
501    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
502
503    /** Permission grant: not grant the permission. */
504    private static final int GRANT_DENIED = 1;
505
506    /** Permission grant: grant the permission as an install permission. */
507    private static final int GRANT_INSTALL = 2;
508
509    /** Permission grant: grant the permission as a runtime one. */
510    private static final int GRANT_RUNTIME = 3;
511
512    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
513    private static final int GRANT_UPGRADE = 4;
514
515    /** Canonical intent used to identify what counts as a "web browser" app */
516    private static final Intent sBrowserIntent;
517    static {
518        sBrowserIntent = new Intent();
519        sBrowserIntent.setAction(Intent.ACTION_VIEW);
520        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
521        sBrowserIntent.setData(Uri.parse("http:"));
522    }
523
524    /**
525     * The set of all protected actions [i.e. those actions for which a high priority
526     * intent filter is disallowed].
527     */
528    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
529    static {
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
531        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
532        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
533        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
534    }
535
536    // Compilation reasons.
537    public static final int REASON_FIRST_BOOT = 0;
538    public static final int REASON_BOOT = 1;
539    public static final int REASON_INSTALL = 2;
540    public static final int REASON_BACKGROUND_DEXOPT = 3;
541    public static final int REASON_AB_OTA = 4;
542
543    public static final int REASON_LAST = REASON_AB_OTA;
544
545    /** All dangerous permission names in the same order as the events in MetricsEvent */
546    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
547            Manifest.permission.READ_CALENDAR,
548            Manifest.permission.WRITE_CALENDAR,
549            Manifest.permission.CAMERA,
550            Manifest.permission.READ_CONTACTS,
551            Manifest.permission.WRITE_CONTACTS,
552            Manifest.permission.GET_ACCOUNTS,
553            Manifest.permission.ACCESS_FINE_LOCATION,
554            Manifest.permission.ACCESS_COARSE_LOCATION,
555            Manifest.permission.RECORD_AUDIO,
556            Manifest.permission.READ_PHONE_STATE,
557            Manifest.permission.CALL_PHONE,
558            Manifest.permission.READ_CALL_LOG,
559            Manifest.permission.WRITE_CALL_LOG,
560            Manifest.permission.ADD_VOICEMAIL,
561            Manifest.permission.USE_SIP,
562            Manifest.permission.PROCESS_OUTGOING_CALLS,
563            Manifest.permission.READ_CELL_BROADCASTS,
564            Manifest.permission.BODY_SENSORS,
565            Manifest.permission.SEND_SMS,
566            Manifest.permission.RECEIVE_SMS,
567            Manifest.permission.READ_SMS,
568            Manifest.permission.RECEIVE_WAP_PUSH,
569            Manifest.permission.RECEIVE_MMS,
570            Manifest.permission.READ_EXTERNAL_STORAGE,
571            Manifest.permission.WRITE_EXTERNAL_STORAGE,
572            Manifest.permission.READ_PHONE_NUMBERS,
573            Manifest.permission.ANSWER_PHONE_CALLS);
574
575
576    /**
577     * Version number for the package parser cache. Increment this whenever the format or
578     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
579     */
580    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
581
582    /**
583     * Whether the package parser cache is enabled.
584     */
585    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
586
587    final ServiceThread mHandlerThread;
588
589    final PackageHandler mHandler;
590
591    private final ProcessLoggingHandler mProcessLoggingHandler;
592
593    /**
594     * Messages for {@link #mHandler} that need to wait for system ready before
595     * being dispatched.
596     */
597    private ArrayList<Message> mPostSystemReadyMessages;
598
599    final int mSdkVersion = Build.VERSION.SDK_INT;
600
601    final Context mContext;
602    final boolean mFactoryTest;
603    final boolean mOnlyCore;
604    final DisplayMetrics mMetrics;
605    final int mDefParseFlags;
606    final String[] mSeparateProcesses;
607    final boolean mIsUpgrade;
608    final boolean mIsPreNUpgrade;
609    final boolean mIsPreNMR1Upgrade;
610
611    // Have we told the Activity Manager to whitelist the default container service by uid yet?
612    @GuardedBy("mPackages")
613    boolean mDefaultContainerWhitelisted = false;
614
615    @GuardedBy("mPackages")
616    private boolean mDexOptDialogShown;
617
618    /** The location for ASEC container files on internal storage. */
619    final String mAsecInternalPath;
620
621    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
622    // LOCK HELD.  Can be called with mInstallLock held.
623    @GuardedBy("mInstallLock")
624    final Installer mInstaller;
625
626    /** Directory where installed third-party apps stored */
627    final File mAppInstallDir;
628
629    /**
630     * Directory to which applications installed internally have their
631     * 32 bit native libraries copied.
632     */
633    private File mAppLib32InstallDir;
634
635    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
636    // apps.
637    final File mDrmAppPrivateInstallDir;
638
639    // ----------------------------------------------------------------
640
641    // Lock for state used when installing and doing other long running
642    // operations.  Methods that must be called with this lock held have
643    // the suffix "LI".
644    final Object mInstallLock = new Object();
645
646    // ----------------------------------------------------------------
647
648    // Keys are String (package name), values are Package.  This also serves
649    // as the lock for the global state.  Methods that must be called with
650    // this lock held have the prefix "LP".
651    @GuardedBy("mPackages")
652    final ArrayMap<String, PackageParser.Package> mPackages =
653            new ArrayMap<String, PackageParser.Package>();
654
655    final ArrayMap<String, Set<String>> mKnownCodebase =
656            new ArrayMap<String, Set<String>>();
657
658    // Keys are isolated uids and values are the uid of the application
659    // that created the isolated proccess.
660    @GuardedBy("mPackages")
661    final SparseIntArray mIsolatedOwners = new SparseIntArray();
662
663    // List of APK paths to load for each user and package. This data is never
664    // persisted by the package manager. Instead, the overlay manager will
665    // ensure the data is up-to-date in runtime.
666    @GuardedBy("mPackages")
667    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
668        new SparseArray<ArrayMap<String, ArrayList<String>>>();
669
670    /**
671     * Tracks new system packages [received in an OTA] that we expect to
672     * find updated user-installed versions. Keys are package name, values
673     * are package location.
674     */
675    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
676    /**
677     * Tracks high priority intent filters for protected actions. During boot, certain
678     * filter actions are protected and should never be allowed to have a high priority
679     * intent filter for them. However, there is one, and only one exception -- the
680     * setup wizard. It must be able to define a high priority intent filter for these
681     * actions to ensure there are no escapes from the wizard. We need to delay processing
682     * of these during boot as we need to look at all of the system packages in order
683     * to know which component is the setup wizard.
684     */
685    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
686    /**
687     * Whether or not processing protected filters should be deferred.
688     */
689    private boolean mDeferProtectedFilters = true;
690
691    /**
692     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
693     */
694    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
695    /**
696     * Whether or not system app permissions should be promoted from install to runtime.
697     */
698    boolean mPromoteSystemApps;
699
700    @GuardedBy("mPackages")
701    final Settings mSettings;
702
703    /**
704     * Set of package names that are currently "frozen", which means active
705     * surgery is being done on the code/data for that package. The platform
706     * will refuse to launch frozen packages to avoid race conditions.
707     *
708     * @see PackageFreezer
709     */
710    @GuardedBy("mPackages")
711    final ArraySet<String> mFrozenPackages = new ArraySet<>();
712
713    final ProtectedPackages mProtectedPackages;
714
715    boolean mFirstBoot;
716
717    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
718
719    // System configuration read by SystemConfig.
720    final int[] mGlobalGids;
721    final SparseArray<ArraySet<String>> mSystemPermissions;
722    @GuardedBy("mAvailableFeatures")
723    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
724
725    // If mac_permissions.xml was found for seinfo labeling.
726    boolean mFoundPolicyFile;
727
728    private final InstantAppRegistry mInstantAppRegistry;
729
730    @GuardedBy("mPackages")
731    int mChangedPackagesSequenceNumber;
732    /**
733     * List of changed [installed, removed or updated] packages.
734     * mapping from user id -> sequence number -> package name
735     */
736    @GuardedBy("mPackages")
737    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
738    /**
739     * The sequence number of the last change to a package.
740     * mapping from user id -> package name -> sequence number
741     */
742    @GuardedBy("mPackages")
743    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
744
745    class PackageParserCallback implements PackageParser.Callback {
746        @Override public final boolean hasFeature(String feature) {
747            return PackageManagerService.this.hasSystemFeature(feature, 0);
748        }
749
750        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
751                Collection<PackageParser.Package> allPackages, String targetPackageName) {
752            List<PackageParser.Package> overlayPackages = null;
753            for (PackageParser.Package p : allPackages) {
754                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
755                    if (overlayPackages == null) {
756                        overlayPackages = new ArrayList<PackageParser.Package>();
757                    }
758                    overlayPackages.add(p);
759                }
760            }
761            if (overlayPackages != null) {
762                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
763                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
764                        return p1.mOverlayPriority - p2.mOverlayPriority;
765                    }
766                };
767                Collections.sort(overlayPackages, cmp);
768            }
769            return overlayPackages;
770        }
771
772        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
773                String targetPackageName, String targetPath) {
774            if ("android".equals(targetPackageName)) {
775                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
776                // native AssetManager.
777                return null;
778            }
779            List<PackageParser.Package> overlayPackages =
780                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
781            if (overlayPackages == null || overlayPackages.isEmpty()) {
782                return null;
783            }
784            List<String> overlayPathList = null;
785            for (PackageParser.Package overlayPackage : overlayPackages) {
786                if (targetPath == null) {
787                    if (overlayPathList == null) {
788                        overlayPathList = new ArrayList<String>();
789                    }
790                    overlayPathList.add(overlayPackage.baseCodePath);
791                    continue;
792                }
793
794                try {
795                    // Creates idmaps for system to parse correctly the Android manifest of the
796                    // target package.
797                    //
798                    // OverlayManagerService will update each of them with a correct gid from its
799                    // target package app id.
800                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
801                            UserHandle.getSharedAppGid(
802                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
803                    if (overlayPathList == null) {
804                        overlayPathList = new ArrayList<String>();
805                    }
806                    overlayPathList.add(overlayPackage.baseCodePath);
807                } catch (InstallerException e) {
808                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
809                            overlayPackage.baseCodePath);
810                }
811            }
812            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
813        }
814
815        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
816            synchronized (mPackages) {
817                return getStaticOverlayPathsLocked(
818                        mPackages.values(), targetPackageName, targetPath);
819            }
820        }
821
822        @Override public final String[] getOverlayApks(String targetPackageName) {
823            return getStaticOverlayPaths(targetPackageName, null);
824        }
825
826        @Override public final String[] getOverlayPaths(String targetPackageName,
827                String targetPath) {
828            return getStaticOverlayPaths(targetPackageName, targetPath);
829        }
830    };
831
832    class ParallelPackageParserCallback extends PackageParserCallback {
833        List<PackageParser.Package> mOverlayPackages = null;
834
835        void findStaticOverlayPackages() {
836            synchronized (mPackages) {
837                for (PackageParser.Package p : mPackages.values()) {
838                    if (p.mIsStaticOverlay) {
839                        if (mOverlayPackages == null) {
840                            mOverlayPackages = new ArrayList<PackageParser.Package>();
841                        }
842                        mOverlayPackages.add(p);
843                    }
844                }
845            }
846        }
847
848        @Override
849        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            // We can trust mOverlayPackages without holding mPackages because package uninstall
851            // can't happen while running parallel parsing.
852            // Moreover holding mPackages on each parsing thread causes dead-lock.
853            return mOverlayPackages == null ? null :
854                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
855        }
856    }
857
858    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
859    final ParallelPackageParserCallback mParallelPackageParserCallback =
860            new ParallelPackageParserCallback();
861
862    public static final class SharedLibraryEntry {
863        public final String path;
864        public final String apk;
865        public final SharedLibraryInfo info;
866
867        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
868                String declaringPackageName, int declaringPackageVersionCode) {
869            path = _path;
870            apk = _apk;
871            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
872                    declaringPackageName, declaringPackageVersionCode), null);
873        }
874    }
875
876    // Currently known shared libraries.
877    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
878    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
879            new ArrayMap<>();
880
881    // All available activities, for your resolving pleasure.
882    final ActivityIntentResolver mActivities =
883            new ActivityIntentResolver();
884
885    // All available receivers, for your resolving pleasure.
886    final ActivityIntentResolver mReceivers =
887            new ActivityIntentResolver();
888
889    // All available services, for your resolving pleasure.
890    final ServiceIntentResolver mServices = new ServiceIntentResolver();
891
892    // All available providers, for your resolving pleasure.
893    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
894
895    // Mapping from provider base names (first directory in content URI codePath)
896    // to the provider information.
897    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
898            new ArrayMap<String, PackageParser.Provider>();
899
900    // Mapping from instrumentation class names to info about them.
901    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
902            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
903
904    // Mapping from permission names to info about them.
905    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
906            new ArrayMap<String, PackageParser.PermissionGroup>();
907
908    // Packages whose data we have transfered into another package, thus
909    // should no longer exist.
910    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
911
912    // Broadcast actions that are only available to the system.
913    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
914
915    /** List of packages waiting for verification. */
916    final SparseArray<PackageVerificationState> mPendingVerification
917            = new SparseArray<PackageVerificationState>();
918
919    /** Set of packages associated with each app op permission. */
920    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
921
922    final PackageInstallerService mInstallerService;
923
924    private final PackageDexOptimizer mPackageDexOptimizer;
925    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
926    // is used by other apps).
927    private final DexManager mDexManager;
928
929    private AtomicInteger mNextMoveId = new AtomicInteger();
930    private final MoveCallbacks mMoveCallbacks;
931
932    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
933
934    // Cache of users who need badging.
935    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
936
937    /** Token for keys in mPendingVerification. */
938    private int mPendingVerificationToken = 0;
939
940    volatile boolean mSystemReady;
941    volatile boolean mSafeMode;
942    volatile boolean mHasSystemUidErrors;
943    private volatile boolean mEphemeralAppsDisabled;
944
945    ApplicationInfo mAndroidApplication;
946    final ActivityInfo mResolveActivity = new ActivityInfo();
947    final ResolveInfo mResolveInfo = new ResolveInfo();
948    ComponentName mResolveComponentName;
949    PackageParser.Package mPlatformPackage;
950    ComponentName mCustomResolverComponentName;
951
952    boolean mResolverReplaced = false;
953
954    private final @Nullable ComponentName mIntentFilterVerifierComponent;
955    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
956
957    private int mIntentFilterVerificationToken = 0;
958
959    /** The service connection to the ephemeral resolver */
960    final EphemeralResolverConnection mInstantAppResolverConnection;
961    /** Component used to show resolver settings for Instant Apps */
962    final ComponentName mInstantAppResolverSettingsComponent;
963
964    /** Activity used to install instant applications */
965    ActivityInfo mInstantAppInstallerActivity;
966    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
967
968    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
969            = new SparseArray<IntentFilterVerificationState>();
970
971    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
972
973    // List of packages names to keep cached, even if they are uninstalled for all users
974    private List<String> mKeepUninstalledPackages;
975
976    private UserManagerInternal mUserManagerInternal;
977
978    private DeviceIdleController.LocalService mDeviceIdleController;
979
980    private File mCacheDir;
981
982    private ArraySet<String> mPrivappPermissionsViolations;
983
984    private Future<?> mPrepareAppDataFuture;
985
986    private static class IFVerificationParams {
987        PackageParser.Package pkg;
988        boolean replacing;
989        int userId;
990        int verifierUid;
991
992        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
993                int _userId, int _verifierUid) {
994            pkg = _pkg;
995            replacing = _replacing;
996            userId = _userId;
997            replacing = _replacing;
998            verifierUid = _verifierUid;
999        }
1000    }
1001
1002    private interface IntentFilterVerifier<T extends IntentFilter> {
1003        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1004                                               T filter, String packageName);
1005        void startVerifications(int userId);
1006        void receiveVerificationResponse(int verificationId);
1007    }
1008
1009    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1010        private Context mContext;
1011        private ComponentName mIntentFilterVerifierComponent;
1012        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1013
1014        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1015            mContext = context;
1016            mIntentFilterVerifierComponent = verifierComponent;
1017        }
1018
1019        private String getDefaultScheme() {
1020            return IntentFilter.SCHEME_HTTPS;
1021        }
1022
1023        @Override
1024        public void startVerifications(int userId) {
1025            // Launch verifications requests
1026            int count = mCurrentIntentFilterVerifications.size();
1027            for (int n=0; n<count; n++) {
1028                int verificationId = mCurrentIntentFilterVerifications.get(n);
1029                final IntentFilterVerificationState ivs =
1030                        mIntentFilterVerificationStates.get(verificationId);
1031
1032                String packageName = ivs.getPackageName();
1033
1034                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1035                final int filterCount = filters.size();
1036                ArraySet<String> domainsSet = new ArraySet<>();
1037                for (int m=0; m<filterCount; m++) {
1038                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1039                    domainsSet.addAll(filter.getHostsList());
1040                }
1041                synchronized (mPackages) {
1042                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1043                            packageName, domainsSet) != null) {
1044                        scheduleWriteSettingsLocked();
1045                    }
1046                }
1047                sendVerificationRequest(userId, verificationId, ivs);
1048            }
1049            mCurrentIntentFilterVerifications.clear();
1050        }
1051
1052        private void sendVerificationRequest(int userId, int verificationId,
1053                IntentFilterVerificationState ivs) {
1054
1055            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1056            verificationIntent.putExtra(
1057                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1058                    verificationId);
1059            verificationIntent.putExtra(
1060                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1061                    getDefaultScheme());
1062            verificationIntent.putExtra(
1063                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1064                    ivs.getHostsString());
1065            verificationIntent.putExtra(
1066                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1067                    ivs.getPackageName());
1068            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1069            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1070
1071            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1072            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1073                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1074                    userId, false, "intent filter verifier");
1075
1076            UserHandle user = new UserHandle(userId);
1077            mContext.sendBroadcastAsUser(verificationIntent, user);
1078            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1079                    "Sending IntentFilter verification broadcast");
1080        }
1081
1082        public void receiveVerificationResponse(int verificationId) {
1083            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1084
1085            final boolean verified = ivs.isVerified();
1086
1087            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1088            final int count = filters.size();
1089            if (DEBUG_DOMAIN_VERIFICATION) {
1090                Slog.i(TAG, "Received verification response " + verificationId
1091                        + " for " + count + " filters, verified=" + verified);
1092            }
1093            for (int n=0; n<count; n++) {
1094                PackageParser.ActivityIntentInfo filter = filters.get(n);
1095                filter.setVerified(verified);
1096
1097                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1098                        + " verified with result:" + verified + " and hosts:"
1099                        + ivs.getHostsString());
1100            }
1101
1102            mIntentFilterVerificationStates.remove(verificationId);
1103
1104            final String packageName = ivs.getPackageName();
1105            IntentFilterVerificationInfo ivi = null;
1106
1107            synchronized (mPackages) {
1108                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1109            }
1110            if (ivi == null) {
1111                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1112                        + verificationId + " packageName:" + packageName);
1113                return;
1114            }
1115            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1116                    "Updating IntentFilterVerificationInfo for package " + packageName
1117                            +" verificationId:" + verificationId);
1118
1119            synchronized (mPackages) {
1120                if (verified) {
1121                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1122                } else {
1123                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1124                }
1125                scheduleWriteSettingsLocked();
1126
1127                final int userId = ivs.getUserId();
1128                if (userId != UserHandle.USER_ALL) {
1129                    final int userStatus =
1130                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1131
1132                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1133                    boolean needUpdate = false;
1134
1135                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1136                    // already been set by the User thru the Disambiguation dialog
1137                    switch (userStatus) {
1138                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1139                            if (verified) {
1140                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1141                            } else {
1142                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1143                            }
1144                            needUpdate = true;
1145                            break;
1146
1147                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1148                            if (verified) {
1149                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1150                                needUpdate = true;
1151                            }
1152                            break;
1153
1154                        default:
1155                            // Nothing to do
1156                    }
1157
1158                    if (needUpdate) {
1159                        mSettings.updateIntentFilterVerificationStatusLPw(
1160                                packageName, updatedStatus, userId);
1161                        scheduleWritePackageRestrictionsLocked(userId);
1162                    }
1163                }
1164            }
1165        }
1166
1167        @Override
1168        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1169                    ActivityIntentInfo filter, String packageName) {
1170            if (!hasValidDomains(filter)) {
1171                return false;
1172            }
1173            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1174            if (ivs == null) {
1175                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1176                        packageName);
1177            }
1178            if (DEBUG_DOMAIN_VERIFICATION) {
1179                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1180            }
1181            ivs.addFilter(filter);
1182            return true;
1183        }
1184
1185        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1186                int userId, int verificationId, String packageName) {
1187            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1188                    verifierUid, userId, packageName);
1189            ivs.setPendingState();
1190            synchronized (mPackages) {
1191                mIntentFilterVerificationStates.append(verificationId, ivs);
1192                mCurrentIntentFilterVerifications.add(verificationId);
1193            }
1194            return ivs;
1195        }
1196    }
1197
1198    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1199        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1200                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1201                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1202    }
1203
1204    // Set of pending broadcasts for aggregating enable/disable of components.
1205    static class PendingPackageBroadcasts {
1206        // for each user id, a map of <package name -> components within that package>
1207        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1208
1209        public PendingPackageBroadcasts() {
1210            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1211        }
1212
1213        public ArrayList<String> get(int userId, String packageName) {
1214            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1215            return packages.get(packageName);
1216        }
1217
1218        public void put(int userId, String packageName, ArrayList<String> components) {
1219            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1220            packages.put(packageName, components);
1221        }
1222
1223        public void remove(int userId, String packageName) {
1224            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1225            if (packages != null) {
1226                packages.remove(packageName);
1227            }
1228        }
1229
1230        public void remove(int userId) {
1231            mUidMap.remove(userId);
1232        }
1233
1234        public int userIdCount() {
1235            return mUidMap.size();
1236        }
1237
1238        public int userIdAt(int n) {
1239            return mUidMap.keyAt(n);
1240        }
1241
1242        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1243            return mUidMap.get(userId);
1244        }
1245
1246        public int size() {
1247            // total number of pending broadcast entries across all userIds
1248            int num = 0;
1249            for (int i = 0; i< mUidMap.size(); i++) {
1250                num += mUidMap.valueAt(i).size();
1251            }
1252            return num;
1253        }
1254
1255        public void clear() {
1256            mUidMap.clear();
1257        }
1258
1259        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1260            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1261            if (map == null) {
1262                map = new ArrayMap<String, ArrayList<String>>();
1263                mUidMap.put(userId, map);
1264            }
1265            return map;
1266        }
1267    }
1268    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1269
1270    // Service Connection to remote media container service to copy
1271    // package uri's from external media onto secure containers
1272    // or internal storage.
1273    private IMediaContainerService mContainerService = null;
1274
1275    static final int SEND_PENDING_BROADCAST = 1;
1276    static final int MCS_BOUND = 3;
1277    static final int END_COPY = 4;
1278    static final int INIT_COPY = 5;
1279    static final int MCS_UNBIND = 6;
1280    static final int START_CLEANING_PACKAGE = 7;
1281    static final int FIND_INSTALL_LOC = 8;
1282    static final int POST_INSTALL = 9;
1283    static final int MCS_RECONNECT = 10;
1284    static final int MCS_GIVE_UP = 11;
1285    static final int UPDATED_MEDIA_STATUS = 12;
1286    static final int WRITE_SETTINGS = 13;
1287    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1288    static final int PACKAGE_VERIFIED = 15;
1289    static final int CHECK_PENDING_VERIFICATION = 16;
1290    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1291    static final int INTENT_FILTER_VERIFIED = 18;
1292    static final int WRITE_PACKAGE_LIST = 19;
1293    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1294
1295    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1296
1297    // Delay time in millisecs
1298    static final int BROADCAST_DELAY = 10 * 1000;
1299
1300    static UserManagerService sUserManager;
1301
1302    // Stores a list of users whose package restrictions file needs to be updated
1303    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1304
1305    final private DefaultContainerConnection mDefContainerConn =
1306            new DefaultContainerConnection();
1307    class DefaultContainerConnection implements ServiceConnection {
1308        public void onServiceConnected(ComponentName name, IBinder service) {
1309            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1310            final IMediaContainerService imcs = IMediaContainerService.Stub
1311                    .asInterface(Binder.allowBlocking(service));
1312            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1313        }
1314
1315        public void onServiceDisconnected(ComponentName name) {
1316            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1317        }
1318    }
1319
1320    // Recordkeeping of restore-after-install operations that are currently in flight
1321    // between the Package Manager and the Backup Manager
1322    static class PostInstallData {
1323        public InstallArgs args;
1324        public PackageInstalledInfo res;
1325
1326        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1327            args = _a;
1328            res = _r;
1329        }
1330    }
1331
1332    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1333    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1334
1335    // XML tags for backup/restore of various bits of state
1336    private static final String TAG_PREFERRED_BACKUP = "pa";
1337    private static final String TAG_DEFAULT_APPS = "da";
1338    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1339
1340    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1341    private static final String TAG_ALL_GRANTS = "rt-grants";
1342    private static final String TAG_GRANT = "grant";
1343    private static final String ATTR_PACKAGE_NAME = "pkg";
1344
1345    private static final String TAG_PERMISSION = "perm";
1346    private static final String ATTR_PERMISSION_NAME = "name";
1347    private static final String ATTR_IS_GRANTED = "g";
1348    private static final String ATTR_USER_SET = "set";
1349    private static final String ATTR_USER_FIXED = "fixed";
1350    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1351
1352    // System/policy permission grants are not backed up
1353    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1354            FLAG_PERMISSION_POLICY_FIXED
1355            | FLAG_PERMISSION_SYSTEM_FIXED
1356            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1357
1358    // And we back up these user-adjusted states
1359    private static final int USER_RUNTIME_GRANT_MASK =
1360            FLAG_PERMISSION_USER_SET
1361            | FLAG_PERMISSION_USER_FIXED
1362            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1363
1364    final @Nullable String mRequiredVerifierPackage;
1365    final @NonNull String mRequiredInstallerPackage;
1366    final @NonNull String mRequiredUninstallerPackage;
1367    final @Nullable String mSetupWizardPackage;
1368    final @Nullable String mStorageManagerPackage;
1369    final @NonNull String mServicesSystemSharedLibraryPackageName;
1370    final @NonNull String mSharedSystemSharedLibraryPackageName;
1371
1372    final boolean mPermissionReviewRequired;
1373
1374    private final PackageUsage mPackageUsage = new PackageUsage();
1375    private final CompilerStats mCompilerStats = new CompilerStats();
1376
1377    class PackageHandler extends Handler {
1378        private boolean mBound = false;
1379        final ArrayList<HandlerParams> mPendingInstalls =
1380            new ArrayList<HandlerParams>();
1381
1382        private boolean connectToService() {
1383            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1384                    " DefaultContainerService");
1385            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1386            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1387            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1388                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1389                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1390                mBound = true;
1391                return true;
1392            }
1393            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1394            return false;
1395        }
1396
1397        private void disconnectService() {
1398            mContainerService = null;
1399            mBound = false;
1400            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401            mContext.unbindService(mDefContainerConn);
1402            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1403        }
1404
1405        PackageHandler(Looper looper) {
1406            super(looper);
1407        }
1408
1409        public void handleMessage(Message msg) {
1410            try {
1411                doHandleMessage(msg);
1412            } finally {
1413                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414            }
1415        }
1416
1417        void doHandleMessage(Message msg) {
1418            switch (msg.what) {
1419                case INIT_COPY: {
1420                    HandlerParams params = (HandlerParams) msg.obj;
1421                    int idx = mPendingInstalls.size();
1422                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1423                    // If a bind was already initiated we dont really
1424                    // need to do anything. The pending install
1425                    // will be processed later on.
1426                    if (!mBound) {
1427                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1428                                System.identityHashCode(mHandler));
1429                        // If this is the only one pending we might
1430                        // have to bind to the service again.
1431                        if (!connectToService()) {
1432                            Slog.e(TAG, "Failed to bind to media container service");
1433                            params.serviceError();
1434                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1435                                    System.identityHashCode(mHandler));
1436                            if (params.traceMethod != null) {
1437                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1438                                        params.traceCookie);
1439                            }
1440                            return;
1441                        } else {
1442                            // Once we bind to the service, the first
1443                            // pending request will be processed.
1444                            mPendingInstalls.add(idx, params);
1445                        }
1446                    } else {
1447                        mPendingInstalls.add(idx, params);
1448                        // Already bound to the service. Just make
1449                        // sure we trigger off processing the first request.
1450                        if (idx == 0) {
1451                            mHandler.sendEmptyMessage(MCS_BOUND);
1452                        }
1453                    }
1454                    break;
1455                }
1456                case MCS_BOUND: {
1457                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1458                    if (msg.obj != null) {
1459                        mContainerService = (IMediaContainerService) msg.obj;
1460                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1461                                System.identityHashCode(mHandler));
1462                    }
1463                    if (mContainerService == null) {
1464                        if (!mBound) {
1465                            // Something seriously wrong since we are not bound and we are not
1466                            // waiting for connection. Bail out.
1467                            Slog.e(TAG, "Cannot bind to media container service");
1468                            for (HandlerParams params : mPendingInstalls) {
1469                                // Indicate service bind error
1470                                params.serviceError();
1471                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1472                                        System.identityHashCode(params));
1473                                if (params.traceMethod != null) {
1474                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1475                                            params.traceMethod, params.traceCookie);
1476                                }
1477                                return;
1478                            }
1479                            mPendingInstalls.clear();
1480                        } else {
1481                            Slog.w(TAG, "Waiting to connect to media container service");
1482                        }
1483                    } else if (mPendingInstalls.size() > 0) {
1484                        HandlerParams params = mPendingInstalls.get(0);
1485                        if (params != null) {
1486                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1487                                    System.identityHashCode(params));
1488                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1489                            if (params.startCopy()) {
1490                                // We are done...  look for more work or to
1491                                // go idle.
1492                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1493                                        "Checking for more work or unbind...");
1494                                // Delete pending install
1495                                if (mPendingInstalls.size() > 0) {
1496                                    mPendingInstalls.remove(0);
1497                                }
1498                                if (mPendingInstalls.size() == 0) {
1499                                    if (mBound) {
1500                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1501                                                "Posting delayed MCS_UNBIND");
1502                                        removeMessages(MCS_UNBIND);
1503                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1504                                        // Unbind after a little delay, to avoid
1505                                        // continual thrashing.
1506                                        sendMessageDelayed(ubmsg, 10000);
1507                                    }
1508                                } else {
1509                                    // There are more pending requests in queue.
1510                                    // Just post MCS_BOUND message to trigger processing
1511                                    // of next pending install.
1512                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1513                                            "Posting MCS_BOUND for next work");
1514                                    mHandler.sendEmptyMessage(MCS_BOUND);
1515                                }
1516                            }
1517                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1518                        }
1519                    } else {
1520                        // Should never happen ideally.
1521                        Slog.w(TAG, "Empty queue");
1522                    }
1523                    break;
1524                }
1525                case MCS_RECONNECT: {
1526                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1527                    if (mPendingInstalls.size() > 0) {
1528                        if (mBound) {
1529                            disconnectService();
1530                        }
1531                        if (!connectToService()) {
1532                            Slog.e(TAG, "Failed to bind to media container service");
1533                            for (HandlerParams params : mPendingInstalls) {
1534                                // Indicate service bind error
1535                                params.serviceError();
1536                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1537                                        System.identityHashCode(params));
1538                            }
1539                            mPendingInstalls.clear();
1540                        }
1541                    }
1542                    break;
1543                }
1544                case MCS_UNBIND: {
1545                    // If there is no actual work left, then time to unbind.
1546                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1547
1548                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1549                        if (mBound) {
1550                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1551
1552                            disconnectService();
1553                        }
1554                    } else if (mPendingInstalls.size() > 0) {
1555                        // There are more pending requests in queue.
1556                        // Just post MCS_BOUND message to trigger processing
1557                        // of next pending install.
1558                        mHandler.sendEmptyMessage(MCS_BOUND);
1559                    }
1560
1561                    break;
1562                }
1563                case MCS_GIVE_UP: {
1564                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1565                    HandlerParams params = mPendingInstalls.remove(0);
1566                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1567                            System.identityHashCode(params));
1568                    break;
1569                }
1570                case SEND_PENDING_BROADCAST: {
1571                    String packages[];
1572                    ArrayList<String> components[];
1573                    int size = 0;
1574                    int uids[];
1575                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1576                    synchronized (mPackages) {
1577                        if (mPendingBroadcasts == null) {
1578                            return;
1579                        }
1580                        size = mPendingBroadcasts.size();
1581                        if (size <= 0) {
1582                            // Nothing to be done. Just return
1583                            return;
1584                        }
1585                        packages = new String[size];
1586                        components = new ArrayList[size];
1587                        uids = new int[size];
1588                        int i = 0;  // filling out the above arrays
1589
1590                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1591                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1592                            Iterator<Map.Entry<String, ArrayList<String>>> it
1593                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1594                                            .entrySet().iterator();
1595                            while (it.hasNext() && i < size) {
1596                                Map.Entry<String, ArrayList<String>> ent = it.next();
1597                                packages[i] = ent.getKey();
1598                                components[i] = ent.getValue();
1599                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1600                                uids[i] = (ps != null)
1601                                        ? UserHandle.getUid(packageUserId, ps.appId)
1602                                        : -1;
1603                                i++;
1604                            }
1605                        }
1606                        size = i;
1607                        mPendingBroadcasts.clear();
1608                    }
1609                    // Send broadcasts
1610                    for (int i = 0; i < size; i++) {
1611                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1612                    }
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1614                    break;
1615                }
1616                case START_CLEANING_PACKAGE: {
1617                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1618                    final String packageName = (String)msg.obj;
1619                    final int userId = msg.arg1;
1620                    final boolean andCode = msg.arg2 != 0;
1621                    synchronized (mPackages) {
1622                        if (userId == UserHandle.USER_ALL) {
1623                            int[] users = sUserManager.getUserIds();
1624                            for (int user : users) {
1625                                mSettings.addPackageToCleanLPw(
1626                                        new PackageCleanItem(user, packageName, andCode));
1627                            }
1628                        } else {
1629                            mSettings.addPackageToCleanLPw(
1630                                    new PackageCleanItem(userId, packageName, andCode));
1631                        }
1632                    }
1633                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1634                    startCleaningPackages();
1635                } break;
1636                case POST_INSTALL: {
1637                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1638
1639                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1640                    final boolean didRestore = (msg.arg2 != 0);
1641                    mRunningInstalls.delete(msg.arg1);
1642
1643                    if (data != null) {
1644                        InstallArgs args = data.args;
1645                        PackageInstalledInfo parentRes = data.res;
1646
1647                        final boolean grantPermissions = (args.installFlags
1648                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1649                        final boolean killApp = (args.installFlags
1650                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1651                        final String[] grantedPermissions = args.installGrantPermissions;
1652
1653                        // Handle the parent package
1654                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1655                                grantedPermissions, didRestore, args.installerPackageName,
1656                                args.observer);
1657
1658                        // Handle the child packages
1659                        final int childCount = (parentRes.addedChildPackages != null)
1660                                ? parentRes.addedChildPackages.size() : 0;
1661                        for (int i = 0; i < childCount; i++) {
1662                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1663                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1664                                    grantedPermissions, false, args.installerPackageName,
1665                                    args.observer);
1666                        }
1667
1668                        // Log tracing if needed
1669                        if (args.traceMethod != null) {
1670                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1671                                    args.traceCookie);
1672                        }
1673                    } else {
1674                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1675                    }
1676
1677                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1678                } break;
1679                case UPDATED_MEDIA_STATUS: {
1680                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1681                    boolean reportStatus = msg.arg1 == 1;
1682                    boolean doGc = msg.arg2 == 1;
1683                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1684                    if (doGc) {
1685                        // Force a gc to clear up stale containers.
1686                        Runtime.getRuntime().gc();
1687                    }
1688                    if (msg.obj != null) {
1689                        @SuppressWarnings("unchecked")
1690                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1691                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1692                        // Unload containers
1693                        unloadAllContainers(args);
1694                    }
1695                    if (reportStatus) {
1696                        try {
1697                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1698                                    "Invoking StorageManagerService call back");
1699                            PackageHelper.getStorageManager().finishMediaUpdate();
1700                        } catch (RemoteException e) {
1701                            Log.e(TAG, "StorageManagerService not running?");
1702                        }
1703                    }
1704                } break;
1705                case WRITE_SETTINGS: {
1706                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1707                    synchronized (mPackages) {
1708                        removeMessages(WRITE_SETTINGS);
1709                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1710                        mSettings.writeLPr();
1711                        mDirtyUsers.clear();
1712                    }
1713                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1714                } break;
1715                case WRITE_PACKAGE_RESTRICTIONS: {
1716                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1717                    synchronized (mPackages) {
1718                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1719                        for (int userId : mDirtyUsers) {
1720                            mSettings.writePackageRestrictionsLPr(userId);
1721                        }
1722                        mDirtyUsers.clear();
1723                    }
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1725                } break;
1726                case WRITE_PACKAGE_LIST: {
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1728                    synchronized (mPackages) {
1729                        removeMessages(WRITE_PACKAGE_LIST);
1730                        mSettings.writePackageListLPr(msg.arg1);
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case CHECK_PENDING_VERIFICATION: {
1735                    final int verificationId = msg.arg1;
1736                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1737
1738                    if ((state != null) && !state.timeoutExtended()) {
1739                        final InstallArgs args = state.getInstallArgs();
1740                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1741
1742                        Slog.i(TAG, "Verification timed out for " + originUri);
1743                        mPendingVerification.remove(verificationId);
1744
1745                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1746
1747                        final UserHandle user = args.getUser();
1748                        if (getDefaultVerificationResponse(user)
1749                                == PackageManager.VERIFICATION_ALLOW) {
1750                            Slog.i(TAG, "Continuing with installation of " + originUri);
1751                            state.setVerifierResponse(Binder.getCallingUid(),
1752                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1753                            broadcastPackageVerified(verificationId, originUri,
1754                                    PackageManager.VERIFICATION_ALLOW, user);
1755                            try {
1756                                ret = args.copyApk(mContainerService, true);
1757                            } catch (RemoteException e) {
1758                                Slog.e(TAG, "Could not contact the ContainerService");
1759                            }
1760                        } else {
1761                            broadcastPackageVerified(verificationId, originUri,
1762                                    PackageManager.VERIFICATION_REJECT, user);
1763                        }
1764
1765                        Trace.asyncTraceEnd(
1766                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1767
1768                        processPendingInstall(args, ret);
1769                        mHandler.sendEmptyMessage(MCS_UNBIND);
1770                    }
1771                    break;
1772                }
1773                case PACKAGE_VERIFIED: {
1774                    final int verificationId = msg.arg1;
1775
1776                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1777                    if (state == null) {
1778                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1779                        break;
1780                    }
1781
1782                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1783
1784                    state.setVerifierResponse(response.callerUid, response.code);
1785
1786                    if (state.isVerificationComplete()) {
1787                        mPendingVerification.remove(verificationId);
1788
1789                        final InstallArgs args = state.getInstallArgs();
1790                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1791
1792                        int ret;
1793                        if (state.isInstallAllowed()) {
1794                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1795                            broadcastPackageVerified(verificationId, originUri,
1796                                    response.code, state.getInstallArgs().getUser());
1797                            try {
1798                                ret = args.copyApk(mContainerService, true);
1799                            } catch (RemoteException e) {
1800                                Slog.e(TAG, "Could not contact the ContainerService");
1801                            }
1802                        } else {
1803                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1804                        }
1805
1806                        Trace.asyncTraceEnd(
1807                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1808
1809                        processPendingInstall(args, ret);
1810                        mHandler.sendEmptyMessage(MCS_UNBIND);
1811                    }
1812
1813                    break;
1814                }
1815                case START_INTENT_FILTER_VERIFICATIONS: {
1816                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1817                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1818                            params.replacing, params.pkg);
1819                    break;
1820                }
1821                case INTENT_FILTER_VERIFIED: {
1822                    final int verificationId = msg.arg1;
1823
1824                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1825                            verificationId);
1826                    if (state == null) {
1827                        Slog.w(TAG, "Invalid IntentFilter verification token "
1828                                + verificationId + " received");
1829                        break;
1830                    }
1831
1832                    final int userId = state.getUserId();
1833
1834                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1835                            "Processing IntentFilter verification with token:"
1836                            + verificationId + " and userId:" + userId);
1837
1838                    final IntentFilterVerificationResponse response =
1839                            (IntentFilterVerificationResponse) msg.obj;
1840
1841                    state.setVerifierResponse(response.callerUid, response.code);
1842
1843                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1844                            "IntentFilter verification with token:" + verificationId
1845                            + " and userId:" + userId
1846                            + " is settings verifier response with response code:"
1847                            + response.code);
1848
1849                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1850                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1851                                + response.getFailedDomainsString());
1852                    }
1853
1854                    if (state.isVerificationComplete()) {
1855                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1856                    } else {
1857                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                                "IntentFilter verification with token:" + verificationId
1859                                + " was not said to be complete");
1860                    }
1861
1862                    break;
1863                }
1864                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1865                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1866                            mInstantAppResolverConnection,
1867                            (InstantAppRequest) msg.obj,
1868                            mInstantAppInstallerActivity,
1869                            mHandler);
1870                }
1871            }
1872        }
1873    }
1874
1875    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1876            boolean killApp, String[] grantedPermissions,
1877            boolean launchedForRestore, String installerPackage,
1878            IPackageInstallObserver2 installObserver) {
1879        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1880            // Send the removed broadcasts
1881            if (res.removedInfo != null) {
1882                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1883            }
1884
1885            // Now that we successfully installed the package, grant runtime
1886            // permissions if requested before broadcasting the install. Also
1887            // for legacy apps in permission review mode we clear the permission
1888            // review flag which is used to emulate runtime permissions for
1889            // legacy apps.
1890            if (grantPermissions) {
1891                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1892            }
1893
1894            final boolean update = res.removedInfo != null
1895                    && res.removedInfo.removedPackage != null;
1896            final String origInstallerPackageName = res.removedInfo != null
1897                    ? res.removedInfo.installerPackageName : null;
1898
1899            // If this is the first time we have child packages for a disabled privileged
1900            // app that had no children, we grant requested runtime permissions to the new
1901            // children if the parent on the system image had them already granted.
1902            if (res.pkg.parentPackage != null) {
1903                synchronized (mPackages) {
1904                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1905                }
1906            }
1907
1908            synchronized (mPackages) {
1909                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1910            }
1911
1912            final String packageName = res.pkg.applicationInfo.packageName;
1913
1914            // Determine the set of users who are adding this package for
1915            // the first time vs. those who are seeing an update.
1916            int[] firstUsers = EMPTY_INT_ARRAY;
1917            int[] updateUsers = EMPTY_INT_ARRAY;
1918            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1919            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1920            for (int newUser : res.newUsers) {
1921                if (ps.getInstantApp(newUser)) {
1922                    continue;
1923                }
1924                if (allNewUsers) {
1925                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1926                    continue;
1927                }
1928                boolean isNew = true;
1929                for (int origUser : res.origUsers) {
1930                    if (origUser == newUser) {
1931                        isNew = false;
1932                        break;
1933                    }
1934                }
1935                if (isNew) {
1936                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1937                } else {
1938                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1939                }
1940            }
1941
1942            // Send installed broadcasts if the package is not a static shared lib.
1943            if (res.pkg.staticSharedLibName == null) {
1944                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1945
1946                // Send added for users that see the package for the first time
1947                // sendPackageAddedForNewUsers also deals with system apps
1948                int appId = UserHandle.getAppId(res.uid);
1949                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1950                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1951
1952                // Send added for users that don't see the package for the first time
1953                Bundle extras = new Bundle(1);
1954                extras.putInt(Intent.EXTRA_UID, res.uid);
1955                if (update) {
1956                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1957                }
1958                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1959                        extras, 0 /*flags*/,
1960                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1961                if (origInstallerPackageName != null) {
1962                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1963                            extras, 0 /*flags*/,
1964                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1965                }
1966
1967                // Send replaced for users that don't see the package for the first time
1968                if (update) {
1969                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1970                            packageName, extras, 0 /*flags*/,
1971                            null /*targetPackage*/, null /*finishedReceiver*/,
1972                            updateUsers);
1973                    if (origInstallerPackageName != null) {
1974                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1975                                extras, 0 /*flags*/,
1976                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1977                    }
1978                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1979                            null /*package*/, null /*extras*/, 0 /*flags*/,
1980                            packageName /*targetPackage*/,
1981                            null /*finishedReceiver*/, updateUsers);
1982                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1983                    // First-install and we did a restore, so we're responsible for the
1984                    // first-launch broadcast.
1985                    if (DEBUG_BACKUP) {
1986                        Slog.i(TAG, "Post-restore of " + packageName
1987                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1988                    }
1989                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1990                }
1991
1992                // Send broadcast package appeared if forward locked/external for all users
1993                // treat asec-hosted packages like removable media on upgrade
1994                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1995                    if (DEBUG_INSTALL) {
1996                        Slog.i(TAG, "upgrading pkg " + res.pkg
1997                                + " is ASEC-hosted -> AVAILABLE");
1998                    }
1999                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2000                    ArrayList<String> pkgList = new ArrayList<>(1);
2001                    pkgList.add(packageName);
2002                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2003                }
2004            }
2005
2006            // Work that needs to happen on first install within each user
2007            if (firstUsers != null && firstUsers.length > 0) {
2008                synchronized (mPackages) {
2009                    for (int userId : firstUsers) {
2010                        // If this app is a browser and it's newly-installed for some
2011                        // users, clear any default-browser state in those users. The
2012                        // app's nature doesn't depend on the user, so we can just check
2013                        // its browser nature in any user and generalize.
2014                        if (packageIsBrowser(packageName, userId)) {
2015                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2016                        }
2017
2018                        // We may also need to apply pending (restored) runtime
2019                        // permission grants within these users.
2020                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2021                    }
2022                }
2023            }
2024
2025            // Log current value of "unknown sources" setting
2026            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2027                    getUnknownSourcesSettings());
2028
2029            // Force a gc to clear up things
2030            Runtime.getRuntime().gc();
2031
2032            // Remove the replaced package's older resources safely now
2033            // We delete after a gc for applications  on sdcard.
2034            if (res.removedInfo != null && res.removedInfo.args != null) {
2035                synchronized (mInstallLock) {
2036                    res.removedInfo.args.doPostDeleteLI(true);
2037                }
2038            }
2039
2040            // Notify DexManager that the package was installed for new users.
2041            // The updated users should already be indexed and the package code paths
2042            // should not change.
2043            // Don't notify the manager for ephemeral apps as they are not expected to
2044            // survive long enough to benefit of background optimizations.
2045            for (int userId : firstUsers) {
2046                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2047                // There's a race currently where some install events may interleave with an uninstall.
2048                // This can lead to package info being null (b/36642664).
2049                if (info != null) {
2050                    mDexManager.notifyPackageInstalled(info, userId);
2051                }
2052            }
2053        }
2054
2055        // If someone is watching installs - notify them
2056        if (installObserver != null) {
2057            try {
2058                Bundle extras = extrasForInstallResult(res);
2059                installObserver.onPackageInstalled(res.name, res.returnCode,
2060                        res.returnMsg, extras);
2061            } catch (RemoteException e) {
2062                Slog.i(TAG, "Observer no longer exists.");
2063            }
2064        }
2065    }
2066
2067    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2068            PackageParser.Package pkg) {
2069        if (pkg.parentPackage == null) {
2070            return;
2071        }
2072        if (pkg.requestedPermissions == null) {
2073            return;
2074        }
2075        final PackageSetting disabledSysParentPs = mSettings
2076                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2077        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2078                || !disabledSysParentPs.isPrivileged()
2079                || (disabledSysParentPs.childPackageNames != null
2080                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2081            return;
2082        }
2083        final int[] allUserIds = sUserManager.getUserIds();
2084        final int permCount = pkg.requestedPermissions.size();
2085        for (int i = 0; i < permCount; i++) {
2086            String permission = pkg.requestedPermissions.get(i);
2087            BasePermission bp = mSettings.mPermissions.get(permission);
2088            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2089                continue;
2090            }
2091            for (int userId : allUserIds) {
2092                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2093                        permission, userId)) {
2094                    grantRuntimePermission(pkg.packageName, permission, userId);
2095                }
2096            }
2097        }
2098    }
2099
2100    private StorageEventListener mStorageListener = new StorageEventListener() {
2101        @Override
2102        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2103            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2104                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2105                    final String volumeUuid = vol.getFsUuid();
2106
2107                    // Clean up any users or apps that were removed or recreated
2108                    // while this volume was missing
2109                    sUserManager.reconcileUsers(volumeUuid);
2110                    reconcileApps(volumeUuid);
2111
2112                    // Clean up any install sessions that expired or were
2113                    // cancelled while this volume was missing
2114                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2115
2116                    loadPrivatePackages(vol);
2117
2118                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2119                    unloadPrivatePackages(vol);
2120                }
2121            }
2122
2123            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2124                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2125                    updateExternalMediaStatus(true, false);
2126                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2127                    updateExternalMediaStatus(false, false);
2128                }
2129            }
2130        }
2131
2132        @Override
2133        public void onVolumeForgotten(String fsUuid) {
2134            if (TextUtils.isEmpty(fsUuid)) {
2135                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2136                return;
2137            }
2138
2139            // Remove any apps installed on the forgotten volume
2140            synchronized (mPackages) {
2141                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2142                for (PackageSetting ps : packages) {
2143                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2144                    deletePackageVersioned(new VersionedPackage(ps.name,
2145                            PackageManager.VERSION_CODE_HIGHEST),
2146                            new LegacyPackageDeleteObserver(null).getBinder(),
2147                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2148                    // Try very hard to release any references to this package
2149                    // so we don't risk the system server being killed due to
2150                    // open FDs
2151                    AttributeCache.instance().removePackage(ps.name);
2152                }
2153
2154                mSettings.onVolumeForgotten(fsUuid);
2155                mSettings.writeLPr();
2156            }
2157        }
2158    };
2159
2160    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2161            String[] grantedPermissions) {
2162        for (int userId : userIds) {
2163            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2164        }
2165    }
2166
2167    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2168            String[] grantedPermissions) {
2169        SettingBase sb = (SettingBase) pkg.mExtras;
2170        if (sb == null) {
2171            return;
2172        }
2173
2174        PermissionsState permissionsState = sb.getPermissionsState();
2175
2176        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2177                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2178
2179        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2180                >= Build.VERSION_CODES.M;
2181
2182        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2183
2184        for (String permission : pkg.requestedPermissions) {
2185            final BasePermission bp;
2186            synchronized (mPackages) {
2187                bp = mSettings.mPermissions.get(permission);
2188            }
2189            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2190                    && (!instantApp || bp.isInstant())
2191                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2192                    && (grantedPermissions == null
2193                           || ArrayUtils.contains(grantedPermissions, permission))) {
2194                final int flags = permissionsState.getPermissionFlags(permission, userId);
2195                if (supportsRuntimePermissions) {
2196                    // Installer cannot change immutable permissions.
2197                    if ((flags & immutableFlags) == 0) {
2198                        grantRuntimePermission(pkg.packageName, permission, userId);
2199                    }
2200                } else if (mPermissionReviewRequired) {
2201                    // In permission review mode we clear the review flag when we
2202                    // are asked to install the app with all permissions granted.
2203                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2204                        updatePermissionFlags(permission, pkg.packageName,
2205                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2206                    }
2207                }
2208            }
2209        }
2210    }
2211
2212    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2213        Bundle extras = null;
2214        switch (res.returnCode) {
2215            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2216                extras = new Bundle();
2217                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2218                        res.origPermission);
2219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2220                        res.origPackage);
2221                break;
2222            }
2223            case PackageManager.INSTALL_SUCCEEDED: {
2224                extras = new Bundle();
2225                extras.putBoolean(Intent.EXTRA_REPLACING,
2226                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2227                break;
2228            }
2229        }
2230        return extras;
2231    }
2232
2233    void scheduleWriteSettingsLocked() {
2234        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2235            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2236        }
2237    }
2238
2239    void scheduleWritePackageListLocked(int userId) {
2240        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2241            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2242            msg.arg1 = userId;
2243            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2244        }
2245    }
2246
2247    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2248        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2249        scheduleWritePackageRestrictionsLocked(userId);
2250    }
2251
2252    void scheduleWritePackageRestrictionsLocked(int userId) {
2253        final int[] userIds = (userId == UserHandle.USER_ALL)
2254                ? sUserManager.getUserIds() : new int[]{userId};
2255        for (int nextUserId : userIds) {
2256            if (!sUserManager.exists(nextUserId)) return;
2257            mDirtyUsers.add(nextUserId);
2258            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2259                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2260            }
2261        }
2262    }
2263
2264    public static PackageManagerService main(Context context, Installer installer,
2265            boolean factoryTest, boolean onlyCore) {
2266        // Self-check for initial settings.
2267        PackageManagerServiceCompilerMapping.checkProperties();
2268
2269        PackageManagerService m = new PackageManagerService(context, installer,
2270                factoryTest, onlyCore);
2271        m.enableSystemUserPackages();
2272        ServiceManager.addService("package", m);
2273        return m;
2274    }
2275
2276    private void enableSystemUserPackages() {
2277        if (!UserManager.isSplitSystemUser()) {
2278            return;
2279        }
2280        // For system user, enable apps based on the following conditions:
2281        // - app is whitelisted or belong to one of these groups:
2282        //   -- system app which has no launcher icons
2283        //   -- system app which has INTERACT_ACROSS_USERS permission
2284        //   -- system IME app
2285        // - app is not in the blacklist
2286        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2287        Set<String> enableApps = new ArraySet<>();
2288        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2289                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2290                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2291        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2292        enableApps.addAll(wlApps);
2293        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2294                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2295        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2296        enableApps.removeAll(blApps);
2297        Log.i(TAG, "Applications installed for system user: " + enableApps);
2298        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2299                UserHandle.SYSTEM);
2300        final int allAppsSize = allAps.size();
2301        synchronized (mPackages) {
2302            for (int i = 0; i < allAppsSize; i++) {
2303                String pName = allAps.get(i);
2304                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2305                // Should not happen, but we shouldn't be failing if it does
2306                if (pkgSetting == null) {
2307                    continue;
2308                }
2309                boolean install = enableApps.contains(pName);
2310                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2311                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2312                            + " for system user");
2313                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2314                }
2315            }
2316            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2317        }
2318    }
2319
2320    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2321        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2322                Context.DISPLAY_SERVICE);
2323        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2324    }
2325
2326    /**
2327     * Requests that files preopted on a secondary system partition be copied to the data partition
2328     * if possible.  Note that the actual copying of the files is accomplished by init for security
2329     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2330     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2331     */
2332    private static void requestCopyPreoptedFiles() {
2333        final int WAIT_TIME_MS = 100;
2334        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2335        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2336            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2337            // We will wait for up to 100 seconds.
2338            final long timeStart = SystemClock.uptimeMillis();
2339            final long timeEnd = timeStart + 100 * 1000;
2340            long timeNow = timeStart;
2341            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2342                try {
2343                    Thread.sleep(WAIT_TIME_MS);
2344                } catch (InterruptedException e) {
2345                    // Do nothing
2346                }
2347                timeNow = SystemClock.uptimeMillis();
2348                if (timeNow > timeEnd) {
2349                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2350                    Slog.wtf(TAG, "cppreopt did not finish!");
2351                    break;
2352                }
2353            }
2354
2355            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2356        }
2357    }
2358
2359    public PackageManagerService(Context context, Installer installer,
2360            boolean factoryTest, boolean onlyCore) {
2361        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2362        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2363        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2364                SystemClock.uptimeMillis());
2365
2366        if (mSdkVersion <= 0) {
2367            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2368        }
2369
2370        mContext = context;
2371
2372        mPermissionReviewRequired = context.getResources().getBoolean(
2373                R.bool.config_permissionReviewRequired);
2374
2375        mFactoryTest = factoryTest;
2376        mOnlyCore = onlyCore;
2377        mMetrics = new DisplayMetrics();
2378        mSettings = new Settings(mPackages);
2379        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2380                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2381        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2382                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2383        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2384                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2385        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2386                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2387        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2388                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2389        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2390                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2391
2392        String separateProcesses = SystemProperties.get("debug.separate_processes");
2393        if (separateProcesses != null && separateProcesses.length() > 0) {
2394            if ("*".equals(separateProcesses)) {
2395                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2396                mSeparateProcesses = null;
2397                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2398            } else {
2399                mDefParseFlags = 0;
2400                mSeparateProcesses = separateProcesses.split(",");
2401                Slog.w(TAG, "Running with debug.separate_processes: "
2402                        + separateProcesses);
2403            }
2404        } else {
2405            mDefParseFlags = 0;
2406            mSeparateProcesses = null;
2407        }
2408
2409        mInstaller = installer;
2410        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2411                "*dexopt*");
2412        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2413        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2414
2415        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2416                FgThread.get().getLooper());
2417
2418        getDefaultDisplayMetrics(context, mMetrics);
2419
2420        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2421        SystemConfig systemConfig = SystemConfig.getInstance();
2422        mGlobalGids = systemConfig.getGlobalGids();
2423        mSystemPermissions = systemConfig.getSystemPermissions();
2424        mAvailableFeatures = systemConfig.getAvailableFeatures();
2425        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2426
2427        mProtectedPackages = new ProtectedPackages(mContext);
2428
2429        synchronized (mInstallLock) {
2430        // writer
2431        synchronized (mPackages) {
2432            mHandlerThread = new ServiceThread(TAG,
2433                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2434            mHandlerThread.start();
2435            mHandler = new PackageHandler(mHandlerThread.getLooper());
2436            mProcessLoggingHandler = new ProcessLoggingHandler();
2437            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2438
2439            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2440            mInstantAppRegistry = new InstantAppRegistry(this);
2441
2442            File dataDir = Environment.getDataDirectory();
2443            mAppInstallDir = new File(dataDir, "app");
2444            mAppLib32InstallDir = new File(dataDir, "app-lib");
2445            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2446            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2447            sUserManager = new UserManagerService(context, this,
2448                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2449
2450            // Propagate permission configuration in to package manager.
2451            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2452                    = systemConfig.getPermissions();
2453            for (int i=0; i<permConfig.size(); i++) {
2454                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2455                BasePermission bp = mSettings.mPermissions.get(perm.name);
2456                if (bp == null) {
2457                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2458                    mSettings.mPermissions.put(perm.name, bp);
2459                }
2460                if (perm.gids != null) {
2461                    bp.setGids(perm.gids, perm.perUser);
2462                }
2463            }
2464
2465            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2466            final int builtInLibCount = libConfig.size();
2467            for (int i = 0; i < builtInLibCount; i++) {
2468                String name = libConfig.keyAt(i);
2469                String path = libConfig.valueAt(i);
2470                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2471                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2472            }
2473
2474            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2475
2476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2477            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2479
2480            // Clean up orphaned packages for which the code path doesn't exist
2481            // and they are an update to a system app - caused by bug/32321269
2482            final int packageSettingCount = mSettings.mPackages.size();
2483            for (int i = packageSettingCount - 1; i >= 0; i--) {
2484                PackageSetting ps = mSettings.mPackages.valueAt(i);
2485                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2486                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2487                    mSettings.mPackages.removeAt(i);
2488                    mSettings.enableSystemPackageLPw(ps.name);
2489                }
2490            }
2491
2492            if (mFirstBoot) {
2493                requestCopyPreoptedFiles();
2494            }
2495
2496            String customResolverActivity = Resources.getSystem().getString(
2497                    R.string.config_customResolverActivity);
2498            if (TextUtils.isEmpty(customResolverActivity)) {
2499                customResolverActivity = null;
2500            } else {
2501                mCustomResolverComponentName = ComponentName.unflattenFromString(
2502                        customResolverActivity);
2503            }
2504
2505            long startTime = SystemClock.uptimeMillis();
2506
2507            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2508                    startTime);
2509
2510            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2511            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2512
2513            if (bootClassPath == null) {
2514                Slog.w(TAG, "No BOOTCLASSPATH found!");
2515            }
2516
2517            if (systemServerClassPath == null) {
2518                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2519            }
2520
2521            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2522
2523            final VersionInfo ver = mSettings.getInternalVersion();
2524            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2525            if (mIsUpgrade) {
2526                logCriticalInfo(Log.INFO,
2527                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2528            }
2529
2530            // when upgrading from pre-M, promote system app permissions from install to runtime
2531            mPromoteSystemApps =
2532                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2533
2534            // When upgrading from pre-N, we need to handle package extraction like first boot,
2535            // as there is no profiling data available.
2536            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2537
2538            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2539
2540            // save off the names of pre-existing system packages prior to scanning; we don't
2541            // want to automatically grant runtime permissions for new system apps
2542            if (mPromoteSystemApps) {
2543                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2544                while (pkgSettingIter.hasNext()) {
2545                    PackageSetting ps = pkgSettingIter.next();
2546                    if (isSystemApp(ps)) {
2547                        mExistingSystemPackages.add(ps.name);
2548                    }
2549                }
2550            }
2551
2552            mCacheDir = preparePackageParserCache(mIsUpgrade);
2553
2554            // Set flag to monitor and not change apk file paths when
2555            // scanning install directories.
2556            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2557
2558            if (mIsUpgrade || mFirstBoot) {
2559                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2560            }
2561
2562            // Collect vendor overlay packages. (Do this before scanning any apps.)
2563            // For security and version matching reason, only consider
2564            // overlay packages if they reside in the right directory.
2565            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2566                    | PackageParser.PARSE_IS_SYSTEM
2567                    | PackageParser.PARSE_IS_SYSTEM_DIR
2568                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2569
2570            mParallelPackageParserCallback.findStaticOverlayPackages();
2571
2572            // Find base frameworks (resource packages without code).
2573            scanDirTracedLI(frameworkDir, mDefParseFlags
2574                    | PackageParser.PARSE_IS_SYSTEM
2575                    | PackageParser.PARSE_IS_SYSTEM_DIR
2576                    | PackageParser.PARSE_IS_PRIVILEGED,
2577                    scanFlags | SCAN_NO_DEX, 0);
2578
2579            // Collected privileged system packages.
2580            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2581            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2582                    | PackageParser.PARSE_IS_SYSTEM
2583                    | PackageParser.PARSE_IS_SYSTEM_DIR
2584                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2585
2586            // Collect ordinary system packages.
2587            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2588            scanDirTracedLI(systemAppDir, mDefParseFlags
2589                    | PackageParser.PARSE_IS_SYSTEM
2590                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2591
2592            // Collect all vendor packages.
2593            File vendorAppDir = new File("/vendor/app");
2594            try {
2595                vendorAppDir = vendorAppDir.getCanonicalFile();
2596            } catch (IOException e) {
2597                // failed to look up canonical path, continue with original one
2598            }
2599            scanDirTracedLI(vendorAppDir, mDefParseFlags
2600                    | PackageParser.PARSE_IS_SYSTEM
2601                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2602
2603            // Collect all OEM packages.
2604            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2605            scanDirTracedLI(oemAppDir, mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2608
2609            // Prune any system packages that no longer exist.
2610            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2611            if (!mOnlyCore) {
2612                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2613                while (psit.hasNext()) {
2614                    PackageSetting ps = psit.next();
2615
2616                    /*
2617                     * If this is not a system app, it can't be a
2618                     * disable system app.
2619                     */
2620                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2621                        continue;
2622                    }
2623
2624                    /*
2625                     * If the package is scanned, it's not erased.
2626                     */
2627                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2628                    if (scannedPkg != null) {
2629                        /*
2630                         * If the system app is both scanned and in the
2631                         * disabled packages list, then it must have been
2632                         * added via OTA. Remove it from the currently
2633                         * scanned package so the previously user-installed
2634                         * application can be scanned.
2635                         */
2636                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2637                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2638                                    + ps.name + "; removing system app.  Last known codePath="
2639                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2640                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2641                                    + scannedPkg.mVersionCode);
2642                            removePackageLI(scannedPkg, true);
2643                            mExpectingBetter.put(ps.name, ps.codePath);
2644                        }
2645
2646                        continue;
2647                    }
2648
2649                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2650                        psit.remove();
2651                        logCriticalInfo(Log.WARN, "System package " + ps.name
2652                                + " no longer exists; it's data will be wiped");
2653                        // Actual deletion of code and data will be handled by later
2654                        // reconciliation step
2655                    } else {
2656                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2657                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2658                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2659                        }
2660                    }
2661                }
2662            }
2663
2664            //look for any incomplete package installations
2665            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2666            for (int i = 0; i < deletePkgsList.size(); i++) {
2667                // Actual deletion of code and data will be handled by later
2668                // reconciliation step
2669                final String packageName = deletePkgsList.get(i).name;
2670                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2671                synchronized (mPackages) {
2672                    mSettings.removePackageLPw(packageName);
2673                }
2674            }
2675
2676            //delete tmp files
2677            deleteTempPackageFiles();
2678
2679            // Remove any shared userIDs that have no associated packages
2680            mSettings.pruneSharedUsersLPw();
2681
2682            if (!mOnlyCore) {
2683                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2684                        SystemClock.uptimeMillis());
2685                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2686
2687                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2688                        | PackageParser.PARSE_FORWARD_LOCK,
2689                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2690
2691                /**
2692                 * Remove disable package settings for any updated system
2693                 * apps that were removed via an OTA. If they're not a
2694                 * previously-updated app, remove them completely.
2695                 * Otherwise, just revoke their system-level permissions.
2696                 */
2697                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2698                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2699                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2700
2701                    String msg;
2702                    if (deletedPkg == null) {
2703                        msg = "Updated system package " + deletedAppName
2704                                + " no longer exists; it's data will be wiped";
2705                        // Actual deletion of code and data will be handled by later
2706                        // reconciliation step
2707                    } else {
2708                        msg = "Updated system app + " + deletedAppName
2709                                + " no longer present; removing system privileges for "
2710                                + deletedAppName;
2711
2712                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2713
2714                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2715                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2716                    }
2717                    logCriticalInfo(Log.WARN, msg);
2718                }
2719
2720                /**
2721                 * Make sure all system apps that we expected to appear on
2722                 * the userdata partition actually showed up. If they never
2723                 * appeared, crawl back and revive the system version.
2724                 */
2725                for (int i = 0; i < mExpectingBetter.size(); i++) {
2726                    final String packageName = mExpectingBetter.keyAt(i);
2727                    if (!mPackages.containsKey(packageName)) {
2728                        final File scanFile = mExpectingBetter.valueAt(i);
2729
2730                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2731                                + " but never showed up; reverting to system");
2732
2733                        int reparseFlags = mDefParseFlags;
2734                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2735                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2736                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2737                                    | PackageParser.PARSE_IS_PRIVILEGED;
2738                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2739                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2740                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2741                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2742                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2743                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2744                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2745                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2746                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2747                        } else {
2748                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2749                            continue;
2750                        }
2751
2752                        mSettings.enableSystemPackageLPw(packageName);
2753
2754                        try {
2755                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2756                        } catch (PackageManagerException e) {
2757                            Slog.e(TAG, "Failed to parse original system package: "
2758                                    + e.getMessage());
2759                        }
2760                    }
2761                }
2762            }
2763            mExpectingBetter.clear();
2764
2765            // Resolve the storage manager.
2766            mStorageManagerPackage = getStorageManagerPackageName();
2767
2768            // Resolve protected action filters. Only the setup wizard is allowed to
2769            // have a high priority filter for these actions.
2770            mSetupWizardPackage = getSetupWizardPackageName();
2771            if (mProtectedFilters.size() > 0) {
2772                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2773                    Slog.i(TAG, "No setup wizard;"
2774                        + " All protected intents capped to priority 0");
2775                }
2776                for (ActivityIntentInfo filter : mProtectedFilters) {
2777                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2778                        if (DEBUG_FILTERS) {
2779                            Slog.i(TAG, "Found setup wizard;"
2780                                + " allow priority " + filter.getPriority() + ";"
2781                                + " package: " + filter.activity.info.packageName
2782                                + " activity: " + filter.activity.className
2783                                + " priority: " + filter.getPriority());
2784                        }
2785                        // skip setup wizard; allow it to keep the high priority filter
2786                        continue;
2787                    }
2788                    if (DEBUG_FILTERS) {
2789                        Slog.i(TAG, "Protected action; cap priority to 0;"
2790                                + " package: " + filter.activity.info.packageName
2791                                + " activity: " + filter.activity.className
2792                                + " origPrio: " + filter.getPriority());
2793                    }
2794                    filter.setPriority(0);
2795                }
2796            }
2797            mDeferProtectedFilters = false;
2798            mProtectedFilters.clear();
2799
2800            // Now that we know all of the shared libraries, update all clients to have
2801            // the correct library paths.
2802            updateAllSharedLibrariesLPw(null);
2803
2804            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2805                // NOTE: We ignore potential failures here during a system scan (like
2806                // the rest of the commands above) because there's precious little we
2807                // can do about it. A settings error is reported, though.
2808                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2809            }
2810
2811            // Now that we know all the packages we are keeping,
2812            // read and update their last usage times.
2813            mPackageUsage.read(mPackages);
2814            mCompilerStats.read();
2815
2816            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2817                    SystemClock.uptimeMillis());
2818            Slog.i(TAG, "Time to scan packages: "
2819                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2820                    + " seconds");
2821
2822            // If the platform SDK has changed since the last time we booted,
2823            // we need to re-grant app permission to catch any new ones that
2824            // appear.  This is really a hack, and means that apps can in some
2825            // cases get permissions that the user didn't initially explicitly
2826            // allow...  it would be nice to have some better way to handle
2827            // this situation.
2828            int updateFlags = UPDATE_PERMISSIONS_ALL;
2829            if (ver.sdkVersion != mSdkVersion) {
2830                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2831                        + mSdkVersion + "; regranting permissions for internal storage");
2832                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2833            }
2834            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2835            ver.sdkVersion = mSdkVersion;
2836
2837            // If this is the first boot or an update from pre-M, and it is a normal
2838            // boot, then we need to initialize the default preferred apps across
2839            // all defined users.
2840            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2841                for (UserInfo user : sUserManager.getUsers(true)) {
2842                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2843                    applyFactoryDefaultBrowserLPw(user.id);
2844                    primeDomainVerificationsLPw(user.id);
2845                }
2846            }
2847
2848            // Prepare storage for system user really early during boot,
2849            // since core system apps like SettingsProvider and SystemUI
2850            // can't wait for user to start
2851            final int storageFlags;
2852            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2853                storageFlags = StorageManager.FLAG_STORAGE_DE;
2854            } else {
2855                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2856            }
2857            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2858                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2859                    true /* onlyCoreApps */);
2860            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2861                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2862                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2863                traceLog.traceBegin("AppDataFixup");
2864                try {
2865                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2866                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2867                } catch (InstallerException e) {
2868                    Slog.w(TAG, "Trouble fixing GIDs", e);
2869                }
2870                traceLog.traceEnd();
2871
2872                traceLog.traceBegin("AppDataPrepare");
2873                if (deferPackages == null || deferPackages.isEmpty()) {
2874                    return;
2875                }
2876                int count = 0;
2877                for (String pkgName : deferPackages) {
2878                    PackageParser.Package pkg = null;
2879                    synchronized (mPackages) {
2880                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2881                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2882                            pkg = ps.pkg;
2883                        }
2884                    }
2885                    if (pkg != null) {
2886                        synchronized (mInstallLock) {
2887                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2888                                    true /* maybeMigrateAppData */);
2889                        }
2890                        count++;
2891                    }
2892                }
2893                traceLog.traceEnd();
2894                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2895            }, "prepareAppData");
2896
2897            // If this is first boot after an OTA, and a normal boot, then
2898            // we need to clear code cache directories.
2899            // Note that we do *not* clear the application profiles. These remain valid
2900            // across OTAs and are used to drive profile verification (post OTA) and
2901            // profile compilation (without waiting to collect a fresh set of profiles).
2902            if (mIsUpgrade && !onlyCore) {
2903                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2904                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2905                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2906                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2907                        // No apps are running this early, so no need to freeze
2908                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2909                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2910                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2911                    }
2912                }
2913                ver.fingerprint = Build.FINGERPRINT;
2914            }
2915
2916            checkDefaultBrowser();
2917
2918            // clear only after permissions and other defaults have been updated
2919            mExistingSystemPackages.clear();
2920            mPromoteSystemApps = false;
2921
2922            // All the changes are done during package scanning.
2923            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2924
2925            // can downgrade to reader
2926            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2927            mSettings.writeLPr();
2928            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2929
2930            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2931                    SystemClock.uptimeMillis());
2932
2933            if (!mOnlyCore) {
2934                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2935                mRequiredInstallerPackage = getRequiredInstallerLPr();
2936                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2937                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2938                if (mIntentFilterVerifierComponent != null) {
2939                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2940                            mIntentFilterVerifierComponent);
2941                } else {
2942                    mIntentFilterVerifier = null;
2943                }
2944                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2945                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2946                        SharedLibraryInfo.VERSION_UNDEFINED);
2947                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2948                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2949                        SharedLibraryInfo.VERSION_UNDEFINED);
2950            } else {
2951                mRequiredVerifierPackage = null;
2952                mRequiredInstallerPackage = null;
2953                mRequiredUninstallerPackage = null;
2954                mIntentFilterVerifierComponent = null;
2955                mIntentFilterVerifier = null;
2956                mServicesSystemSharedLibraryPackageName = null;
2957                mSharedSystemSharedLibraryPackageName = null;
2958            }
2959
2960            mInstallerService = new PackageInstallerService(context, this);
2961            final Pair<ComponentName, String> instantAppResolverComponent =
2962                    getInstantAppResolverLPr();
2963            if (instantAppResolverComponent != null) {
2964                if (DEBUG_EPHEMERAL) {
2965                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2966                }
2967                mInstantAppResolverConnection = new EphemeralResolverConnection(
2968                        mContext, instantAppResolverComponent.first,
2969                        instantAppResolverComponent.second);
2970                mInstantAppResolverSettingsComponent =
2971                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2972            } else {
2973                mInstantAppResolverConnection = null;
2974                mInstantAppResolverSettingsComponent = null;
2975            }
2976            updateInstantAppInstallerLocked(null);
2977
2978            // Read and update the usage of dex files.
2979            // Do this at the end of PM init so that all the packages have their
2980            // data directory reconciled.
2981            // At this point we know the code paths of the packages, so we can validate
2982            // the disk file and build the internal cache.
2983            // The usage file is expected to be small so loading and verifying it
2984            // should take a fairly small time compare to the other activities (e.g. package
2985            // scanning).
2986            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2987            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2988            for (int userId : currentUserIds) {
2989                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2990            }
2991            mDexManager.load(userPackages);
2992        } // synchronized (mPackages)
2993        } // synchronized (mInstallLock)
2994
2995        // Now after opening every single application zip, make sure they
2996        // are all flushed.  Not really needed, but keeps things nice and
2997        // tidy.
2998        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2999        Runtime.getRuntime().gc();
3000        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3001
3002        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3003        FallbackCategoryProvider.loadFallbacks();
3004        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3005
3006        // The initial scanning above does many calls into installd while
3007        // holding the mPackages lock, but we're mostly interested in yelling
3008        // once we have a booted system.
3009        mInstaller.setWarnIfHeld(mPackages);
3010
3011        // Expose private service for system components to use.
3012        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3013        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3014    }
3015
3016    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3017        // we're only interested in updating the installer appliction when 1) it's not
3018        // already set or 2) the modified package is the installer
3019        if (mInstantAppInstallerActivity != null
3020                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3021                        .equals(modifiedPackage)) {
3022            return;
3023        }
3024        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3025    }
3026
3027    private static File preparePackageParserCache(boolean isUpgrade) {
3028        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3029            return null;
3030        }
3031
3032        // Disable package parsing on eng builds to allow for faster incremental development.
3033        if ("eng".equals(Build.TYPE)) {
3034            return null;
3035        }
3036
3037        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3038            Slog.i(TAG, "Disabling package parser cache due to system property.");
3039            return null;
3040        }
3041
3042        // The base directory for the package parser cache lives under /data/system/.
3043        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3044                "package_cache");
3045        if (cacheBaseDir == null) {
3046            return null;
3047        }
3048
3049        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3050        // This also serves to "GC" unused entries when the package cache version changes (which
3051        // can only happen during upgrades).
3052        if (isUpgrade) {
3053            FileUtils.deleteContents(cacheBaseDir);
3054        }
3055
3056
3057        // Return the versioned package cache directory. This is something like
3058        // "/data/system/package_cache/1"
3059        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3060
3061        // The following is a workaround to aid development on non-numbered userdebug
3062        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3063        // the system partition is newer.
3064        //
3065        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3066        // that starts with "eng." to signify that this is an engineering build and not
3067        // destined for release.
3068        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3069            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3070
3071            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3072            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3073            // in general and should not be used for production changes. In this specific case,
3074            // we know that they will work.
3075            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3076            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3077                FileUtils.deleteContents(cacheBaseDir);
3078                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3079            }
3080        }
3081
3082        return cacheDir;
3083    }
3084
3085    @Override
3086    public boolean isFirstBoot() {
3087        return mFirstBoot;
3088    }
3089
3090    @Override
3091    public boolean isOnlyCoreApps() {
3092        return mOnlyCore;
3093    }
3094
3095    @Override
3096    public boolean isUpgrade() {
3097        return mIsUpgrade;
3098    }
3099
3100    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3101        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3102
3103        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3104                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3105                UserHandle.USER_SYSTEM);
3106        if (matches.size() == 1) {
3107            return matches.get(0).getComponentInfo().packageName;
3108        } else if (matches.size() == 0) {
3109            Log.e(TAG, "There should probably be a verifier, but, none were found");
3110            return null;
3111        }
3112        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3113    }
3114
3115    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3116        synchronized (mPackages) {
3117            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3118            if (libraryEntry == null) {
3119                throw new IllegalStateException("Missing required shared library:" + name);
3120            }
3121            return libraryEntry.apk;
3122        }
3123    }
3124
3125    private @NonNull String getRequiredInstallerLPr() {
3126        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3127        intent.addCategory(Intent.CATEGORY_DEFAULT);
3128        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3129
3130        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3131                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3132                UserHandle.USER_SYSTEM);
3133        if (matches.size() == 1) {
3134            ResolveInfo resolveInfo = matches.get(0);
3135            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3136                throw new RuntimeException("The installer must be a privileged app");
3137            }
3138            return matches.get(0).getComponentInfo().packageName;
3139        } else {
3140            throw new RuntimeException("There must be exactly one installer; found " + matches);
3141        }
3142    }
3143
3144    private @NonNull String getRequiredUninstallerLPr() {
3145        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3146        intent.addCategory(Intent.CATEGORY_DEFAULT);
3147        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3148
3149        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3150                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3151                UserHandle.USER_SYSTEM);
3152        if (resolveInfo == null ||
3153                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3154            throw new RuntimeException("There must be exactly one uninstaller; found "
3155                    + resolveInfo);
3156        }
3157        return resolveInfo.getComponentInfo().packageName;
3158    }
3159
3160    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3161        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3162
3163        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3164                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3165                UserHandle.USER_SYSTEM);
3166        ResolveInfo best = null;
3167        final int N = matches.size();
3168        for (int i = 0; i < N; i++) {
3169            final ResolveInfo cur = matches.get(i);
3170            final String packageName = cur.getComponentInfo().packageName;
3171            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3172                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3173                continue;
3174            }
3175
3176            if (best == null || cur.priority > best.priority) {
3177                best = cur;
3178            }
3179        }
3180
3181        if (best != null) {
3182            return best.getComponentInfo().getComponentName();
3183        }
3184        Slog.w(TAG, "Intent filter verifier not found");
3185        return null;
3186    }
3187
3188    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3189        final String[] packageArray =
3190                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3191        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3192            if (DEBUG_EPHEMERAL) {
3193                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3194            }
3195            return null;
3196        }
3197
3198        final int callingUid = Binder.getCallingUid();
3199        final int resolveFlags =
3200                MATCH_DIRECT_BOOT_AWARE
3201                | MATCH_DIRECT_BOOT_UNAWARE
3202                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3203        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3204        final Intent resolverIntent = new Intent(actionName);
3205        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3206                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3207        // temporarily look for the old action
3208        if (resolvers.size() == 0) {
3209            if (DEBUG_EPHEMERAL) {
3210                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3211            }
3212            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3213            resolverIntent.setAction(actionName);
3214            resolvers = queryIntentServicesInternal(resolverIntent, null,
3215                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3216        }
3217        final int N = resolvers.size();
3218        if (N == 0) {
3219            if (DEBUG_EPHEMERAL) {
3220                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3221            }
3222            return null;
3223        }
3224
3225        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3226        for (int i = 0; i < N; i++) {
3227            final ResolveInfo info = resolvers.get(i);
3228
3229            if (info.serviceInfo == null) {
3230                continue;
3231            }
3232
3233            final String packageName = info.serviceInfo.packageName;
3234            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3235                if (DEBUG_EPHEMERAL) {
3236                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3237                            + " pkg: " + packageName + ", info:" + info);
3238                }
3239                continue;
3240            }
3241
3242            if (DEBUG_EPHEMERAL) {
3243                Slog.v(TAG, "Ephemeral resolver found;"
3244                        + " pkg: " + packageName + ", info:" + info);
3245            }
3246            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3247        }
3248        if (DEBUG_EPHEMERAL) {
3249            Slog.v(TAG, "Ephemeral resolver NOT found");
3250        }
3251        return null;
3252    }
3253
3254    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3255        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3256        intent.addCategory(Intent.CATEGORY_DEFAULT);
3257        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3258
3259        final int resolveFlags =
3260                MATCH_DIRECT_BOOT_AWARE
3261                | MATCH_DIRECT_BOOT_UNAWARE
3262                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3263        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3264                resolveFlags, UserHandle.USER_SYSTEM);
3265        // temporarily look for the old action
3266        if (matches.isEmpty()) {
3267            if (DEBUG_EPHEMERAL) {
3268                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3269            }
3270            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3271            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3272                    resolveFlags, UserHandle.USER_SYSTEM);
3273        }
3274        Iterator<ResolveInfo> iter = matches.iterator();
3275        while (iter.hasNext()) {
3276            final ResolveInfo rInfo = iter.next();
3277            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3278            if (ps != null) {
3279                final PermissionsState permissionsState = ps.getPermissionsState();
3280                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3281                    continue;
3282                }
3283            }
3284            iter.remove();
3285        }
3286        if (matches.size() == 0) {
3287            return null;
3288        } else if (matches.size() == 1) {
3289            return (ActivityInfo) matches.get(0).getComponentInfo();
3290        } else {
3291            throw new RuntimeException(
3292                    "There must be at most one ephemeral installer; found " + matches);
3293        }
3294    }
3295
3296    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3297            @NonNull ComponentName resolver) {
3298        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3299                .addCategory(Intent.CATEGORY_DEFAULT)
3300                .setPackage(resolver.getPackageName());
3301        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3302        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3303                UserHandle.USER_SYSTEM);
3304        // temporarily look for the old action
3305        if (matches.isEmpty()) {
3306            if (DEBUG_EPHEMERAL) {
3307                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3308            }
3309            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3310            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3311                    UserHandle.USER_SYSTEM);
3312        }
3313        if (matches.isEmpty()) {
3314            return null;
3315        }
3316        return matches.get(0).getComponentInfo().getComponentName();
3317    }
3318
3319    private void primeDomainVerificationsLPw(int userId) {
3320        if (DEBUG_DOMAIN_VERIFICATION) {
3321            Slog.d(TAG, "Priming domain verifications in user " + userId);
3322        }
3323
3324        SystemConfig systemConfig = SystemConfig.getInstance();
3325        ArraySet<String> packages = systemConfig.getLinkedApps();
3326
3327        for (String packageName : packages) {
3328            PackageParser.Package pkg = mPackages.get(packageName);
3329            if (pkg != null) {
3330                if (!pkg.isSystemApp()) {
3331                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3332                    continue;
3333                }
3334
3335                ArraySet<String> domains = null;
3336                for (PackageParser.Activity a : pkg.activities) {
3337                    for (ActivityIntentInfo filter : a.intents) {
3338                        if (hasValidDomains(filter)) {
3339                            if (domains == null) {
3340                                domains = new ArraySet<String>();
3341                            }
3342                            domains.addAll(filter.getHostsList());
3343                        }
3344                    }
3345                }
3346
3347                if (domains != null && domains.size() > 0) {
3348                    if (DEBUG_DOMAIN_VERIFICATION) {
3349                        Slog.v(TAG, "      + " + packageName);
3350                    }
3351                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3352                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3353                    // and then 'always' in the per-user state actually used for intent resolution.
3354                    final IntentFilterVerificationInfo ivi;
3355                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3356                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3357                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3358                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3359                } else {
3360                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3361                            + "' does not handle web links");
3362                }
3363            } else {
3364                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3365            }
3366        }
3367
3368        scheduleWritePackageRestrictionsLocked(userId);
3369        scheduleWriteSettingsLocked();
3370    }
3371
3372    private void applyFactoryDefaultBrowserLPw(int userId) {
3373        // The default browser app's package name is stored in a string resource,
3374        // with a product-specific overlay used for vendor customization.
3375        String browserPkg = mContext.getResources().getString(
3376                com.android.internal.R.string.default_browser);
3377        if (!TextUtils.isEmpty(browserPkg)) {
3378            // non-empty string => required to be a known package
3379            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3380            if (ps == null) {
3381                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3382                browserPkg = null;
3383            } else {
3384                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3385            }
3386        }
3387
3388        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3389        // default.  If there's more than one, just leave everything alone.
3390        if (browserPkg == null) {
3391            calculateDefaultBrowserLPw(userId);
3392        }
3393    }
3394
3395    private void calculateDefaultBrowserLPw(int userId) {
3396        List<String> allBrowsers = resolveAllBrowserApps(userId);
3397        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3398        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3399    }
3400
3401    private List<String> resolveAllBrowserApps(int userId) {
3402        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3403        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3404                PackageManager.MATCH_ALL, userId);
3405
3406        final int count = list.size();
3407        List<String> result = new ArrayList<String>(count);
3408        for (int i=0; i<count; i++) {
3409            ResolveInfo info = list.get(i);
3410            if (info.activityInfo == null
3411                    || !info.handleAllWebDataURI
3412                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3413                    || result.contains(info.activityInfo.packageName)) {
3414                continue;
3415            }
3416            result.add(info.activityInfo.packageName);
3417        }
3418
3419        return result;
3420    }
3421
3422    private boolean packageIsBrowser(String packageName, int userId) {
3423        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3424                PackageManager.MATCH_ALL, userId);
3425        final int N = list.size();
3426        for (int i = 0; i < N; i++) {
3427            ResolveInfo info = list.get(i);
3428            if (packageName.equals(info.activityInfo.packageName)) {
3429                return true;
3430            }
3431        }
3432        return false;
3433    }
3434
3435    private void checkDefaultBrowser() {
3436        final int myUserId = UserHandle.myUserId();
3437        final String packageName = getDefaultBrowserPackageName(myUserId);
3438        if (packageName != null) {
3439            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3440            if (info == null) {
3441                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3442                synchronized (mPackages) {
3443                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3444                }
3445            }
3446        }
3447    }
3448
3449    @Override
3450    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3451            throws RemoteException {
3452        try {
3453            return super.onTransact(code, data, reply, flags);
3454        } catch (RuntimeException e) {
3455            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3456                Slog.wtf(TAG, "Package Manager Crash", e);
3457            }
3458            throw e;
3459        }
3460    }
3461
3462    static int[] appendInts(int[] cur, int[] add) {
3463        if (add == null) return cur;
3464        if (cur == null) return add;
3465        final int N = add.length;
3466        for (int i=0; i<N; i++) {
3467            cur = appendInt(cur, add[i]);
3468        }
3469        return cur;
3470    }
3471
3472    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3473        if (!sUserManager.exists(userId)) return null;
3474        if (ps == null) {
3475            return null;
3476        }
3477        final PackageParser.Package p = ps.pkg;
3478        if (p == null) {
3479            return null;
3480        }
3481        // Filter out ephemeral app metadata:
3482        //   * The system/shell/root can see metadata for any app
3483        //   * An installed app can see metadata for 1) other installed apps
3484        //     and 2) ephemeral apps that have explicitly interacted with it
3485        //   * Ephemeral apps can only see their own data and exposed installed apps
3486        //   * Holding a signature permission allows seeing instant apps
3487        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3488        if (callingAppId != Process.SYSTEM_UID
3489                && callingAppId != Process.SHELL_UID
3490                && callingAppId != Process.ROOT_UID
3491                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3492                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3493            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3494            if (instantAppPackageName != null) {
3495                // ephemeral apps can only get information on themselves or
3496                // installed apps that are exposed.
3497                if (!instantAppPackageName.equals(p.packageName)
3498                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3499                    return null;
3500                }
3501            } else {
3502                if (ps.getInstantApp(userId)) {
3503                    // only get access to the ephemeral app if we've been granted access
3504                    if (!mInstantAppRegistry.isInstantAccessGranted(
3505                            userId, callingAppId, ps.appId)) {
3506                        return null;
3507                    }
3508                }
3509            }
3510        }
3511
3512        final PermissionsState permissionsState = ps.getPermissionsState();
3513
3514        // Compute GIDs only if requested
3515        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3516                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3517        // Compute granted permissions only if package has requested permissions
3518        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3519                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3520        final PackageUserState state = ps.readUserState(userId);
3521
3522        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3523                && ps.isSystem()) {
3524            flags |= MATCH_ANY_USER;
3525        }
3526
3527        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3528                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3529
3530        if (packageInfo == null) {
3531            return null;
3532        }
3533
3534        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3535
3536        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3537                resolveExternalPackageNameLPr(p);
3538
3539        return packageInfo;
3540    }
3541
3542    @Override
3543    public void checkPackageStartable(String packageName, int userId) {
3544        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3545
3546        synchronized (mPackages) {
3547            final PackageSetting ps = mSettings.mPackages.get(packageName);
3548            if (ps == null) {
3549                throw new SecurityException("Package " + packageName + " was not found!");
3550            }
3551
3552            if (!ps.getInstalled(userId)) {
3553                throw new SecurityException(
3554                        "Package " + packageName + " was not installed for user " + userId + "!");
3555            }
3556
3557            if (mSafeMode && !ps.isSystem()) {
3558                throw new SecurityException("Package " + packageName + " not a system app!");
3559            }
3560
3561            if (mFrozenPackages.contains(packageName)) {
3562                throw new SecurityException("Package " + packageName + " is currently frozen!");
3563            }
3564
3565            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3566                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3567                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3568            }
3569        }
3570    }
3571
3572    @Override
3573    public boolean isPackageAvailable(String packageName, int userId) {
3574        if (!sUserManager.exists(userId)) return false;
3575        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3576                false /* requireFullPermission */, false /* checkShell */, "is package available");
3577        synchronized (mPackages) {
3578            PackageParser.Package p = mPackages.get(packageName);
3579            if (p != null) {
3580                final PackageSetting ps = (PackageSetting) p.mExtras;
3581                if (ps != null) {
3582                    final PackageUserState state = ps.readUserState(userId);
3583                    if (state != null) {
3584                        return PackageParser.isAvailable(state);
3585                    }
3586                }
3587            }
3588        }
3589        return false;
3590    }
3591
3592    @Override
3593    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3594        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3595                flags, userId);
3596    }
3597
3598    @Override
3599    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3600            int flags, int userId) {
3601        return getPackageInfoInternal(versionedPackage.getPackageName(),
3602                // TODO: We will change version code to long, so in the new API it is long
3603                (int) versionedPackage.getVersionCode(), flags, userId);
3604    }
3605
3606    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3607            int flags, int userId) {
3608        if (!sUserManager.exists(userId)) return null;
3609        flags = updateFlagsForPackage(flags, userId, packageName);
3610        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3611                false /* requireFullPermission */, false /* checkShell */, "get package info");
3612
3613        // reader
3614        synchronized (mPackages) {
3615            // Normalize package name to handle renamed packages and static libs
3616            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3617
3618            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3619            if (matchFactoryOnly) {
3620                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3621                if (ps != null) {
3622                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
3623                        return null;
3624                    }
3625                    return generatePackageInfo(ps, flags, userId);
3626                }
3627            }
3628
3629            PackageParser.Package p = mPackages.get(packageName);
3630            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3631                return null;
3632            }
3633            if (DEBUG_PACKAGE_INFO)
3634                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3635            if (p != null) {
3636                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3637                        Binder.getCallingUid(), userId, flags)) {
3638                    return null;
3639                }
3640                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3641            }
3642            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3643                final PackageSetting ps = mSettings.mPackages.get(packageName);
3644                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
3645                    return null;
3646                }
3647                return generatePackageInfo(ps, flags, userId);
3648            }
3649        }
3650        return null;
3651    }
3652
3653    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3654            int flags) {
3655        // Callers can access only the libs they depend on, otherwise they need to explicitly
3656        // ask for the shared libraries given the caller is allowed to access all static libs.
3657        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3658            // System/shell/root get to see all static libs
3659            final int appId = UserHandle.getAppId(uid);
3660            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3661                    || appId == Process.ROOT_UID) {
3662                return false;
3663            }
3664        }
3665
3666        // No package means no static lib as it is always on internal storage
3667        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3668            return false;
3669        }
3670
3671        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3672                ps.pkg.staticSharedLibVersion);
3673        if (libEntry == null) {
3674            return false;
3675        }
3676
3677        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3678        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3679        if (uidPackageNames == null) {
3680            return true;
3681        }
3682
3683        for (String uidPackageName : uidPackageNames) {
3684            if (ps.name.equals(uidPackageName)) {
3685                return false;
3686            }
3687            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3688            if (uidPs != null) {
3689                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3690                        libEntry.info.getName());
3691                if (index < 0) {
3692                    continue;
3693                }
3694                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3695                    return false;
3696                }
3697            }
3698        }
3699        return true;
3700    }
3701
3702    @Override
3703    public String[] currentToCanonicalPackageNames(String[] names) {
3704        String[] out = new String[names.length];
3705        // reader
3706        synchronized (mPackages) {
3707            for (int i=names.length-1; i>=0; i--) {
3708                PackageSetting ps = mSettings.mPackages.get(names[i]);
3709                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3710            }
3711        }
3712        return out;
3713    }
3714
3715    @Override
3716    public String[] canonicalToCurrentPackageNames(String[] names) {
3717        String[] out = new String[names.length];
3718        // reader
3719        synchronized (mPackages) {
3720            for (int i=names.length-1; i>=0; i--) {
3721                String cur = mSettings.getRenamedPackageLPr(names[i]);
3722                out[i] = cur != null ? cur : names[i];
3723            }
3724        }
3725        return out;
3726    }
3727
3728    @Override
3729    public int getPackageUid(String packageName, int flags, int userId) {
3730        if (!sUserManager.exists(userId)) return -1;
3731        flags = updateFlagsForPackage(flags, userId, packageName);
3732        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3733                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3734
3735        // reader
3736        synchronized (mPackages) {
3737            final PackageParser.Package p = mPackages.get(packageName);
3738            if (p != null && p.isMatch(flags)) {
3739                return UserHandle.getUid(userId, p.applicationInfo.uid);
3740            }
3741            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3742                final PackageSetting ps = mSettings.mPackages.get(packageName);
3743                if (ps != null && ps.isMatch(flags)) {
3744                    return UserHandle.getUid(userId, ps.appId);
3745                }
3746            }
3747        }
3748
3749        return -1;
3750    }
3751
3752    @Override
3753    public int[] getPackageGids(String packageName, int flags, int userId) {
3754        if (!sUserManager.exists(userId)) return null;
3755        flags = updateFlagsForPackage(flags, userId, packageName);
3756        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3757                false /* requireFullPermission */, false /* checkShell */,
3758                "getPackageGids");
3759
3760        // reader
3761        synchronized (mPackages) {
3762            final PackageParser.Package p = mPackages.get(packageName);
3763            if (p != null && p.isMatch(flags)) {
3764                PackageSetting ps = (PackageSetting) p.mExtras;
3765                // TODO: Shouldn't this be checking for package installed state for userId and
3766                // return null?
3767                return ps.getPermissionsState().computeGids(userId);
3768            }
3769            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3770                final PackageSetting ps = mSettings.mPackages.get(packageName);
3771                if (ps != null && ps.isMatch(flags)) {
3772                    return ps.getPermissionsState().computeGids(userId);
3773                }
3774            }
3775        }
3776
3777        return null;
3778    }
3779
3780    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3781        if (bp.perm != null) {
3782            return PackageParser.generatePermissionInfo(bp.perm, flags);
3783        }
3784        PermissionInfo pi = new PermissionInfo();
3785        pi.name = bp.name;
3786        pi.packageName = bp.sourcePackage;
3787        pi.nonLocalizedLabel = bp.name;
3788        pi.protectionLevel = bp.protectionLevel;
3789        return pi;
3790    }
3791
3792    @Override
3793    public PermissionInfo getPermissionInfo(String name, int flags) {
3794        // reader
3795        synchronized (mPackages) {
3796            final BasePermission p = mSettings.mPermissions.get(name);
3797            if (p != null) {
3798                return generatePermissionInfo(p, flags);
3799            }
3800            return null;
3801        }
3802    }
3803
3804    @Override
3805    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3806            int flags) {
3807        // reader
3808        synchronized (mPackages) {
3809            if (group != null && !mPermissionGroups.containsKey(group)) {
3810                // This is thrown as NameNotFoundException
3811                return null;
3812            }
3813
3814            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3815            for (BasePermission p : mSettings.mPermissions.values()) {
3816                if (group == null) {
3817                    if (p.perm == null || p.perm.info.group == null) {
3818                        out.add(generatePermissionInfo(p, flags));
3819                    }
3820                } else {
3821                    if (p.perm != null && group.equals(p.perm.info.group)) {
3822                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3823                    }
3824                }
3825            }
3826            return new ParceledListSlice<>(out);
3827        }
3828    }
3829
3830    @Override
3831    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3832        // reader
3833        synchronized (mPackages) {
3834            return PackageParser.generatePermissionGroupInfo(
3835                    mPermissionGroups.get(name), flags);
3836        }
3837    }
3838
3839    @Override
3840    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3841        // reader
3842        synchronized (mPackages) {
3843            final int N = mPermissionGroups.size();
3844            ArrayList<PermissionGroupInfo> out
3845                    = new ArrayList<PermissionGroupInfo>(N);
3846            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3847                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3848            }
3849            return new ParceledListSlice<>(out);
3850        }
3851    }
3852
3853    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3854            int uid, int userId) {
3855        if (!sUserManager.exists(userId)) return null;
3856        PackageSetting ps = mSettings.mPackages.get(packageName);
3857        if (ps != null) {
3858            if (filterSharedLibPackageLPr(ps, uid, userId, flags)) {
3859                return null;
3860            }
3861            if (ps.pkg == null) {
3862                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3863                if (pInfo != null) {
3864                    return pInfo.applicationInfo;
3865                }
3866                return null;
3867            }
3868            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3869                    ps.readUserState(userId), userId);
3870            if (ai != null) {
3871                rebaseEnabledOverlays(ai, userId);
3872                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3873            }
3874            return ai;
3875        }
3876        return null;
3877    }
3878
3879    @Override
3880    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3881        if (!sUserManager.exists(userId)) return null;
3882        flags = updateFlagsForApplication(flags, userId, packageName);
3883        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3884                false /* requireFullPermission */, false /* checkShell */, "get application info");
3885
3886        // writer
3887        synchronized (mPackages) {
3888            // Normalize package name to handle renamed packages and static libs
3889            packageName = resolveInternalPackageNameLPr(packageName,
3890                    PackageManager.VERSION_CODE_HIGHEST);
3891
3892            PackageParser.Package p = mPackages.get(packageName);
3893            if (DEBUG_PACKAGE_INFO) Log.v(
3894                    TAG, "getApplicationInfo " + packageName
3895                    + ": " + p);
3896            if (p != null) {
3897                PackageSetting ps = mSettings.mPackages.get(packageName);
3898                if (ps == null) return null;
3899                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
3900                    return null;
3901                }
3902                // Note: isEnabledLP() does not apply here - always return info
3903                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3904                        p, flags, ps.readUserState(userId), userId);
3905                if (ai != null) {
3906                    rebaseEnabledOverlays(ai, userId);
3907                    ai.packageName = resolveExternalPackageNameLPr(p);
3908                }
3909                return ai;
3910            }
3911            if ("android".equals(packageName)||"system".equals(packageName)) {
3912                return mAndroidApplication;
3913            }
3914            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3915                // Already generates the external package name
3916                return generateApplicationInfoFromSettingsLPw(packageName,
3917                        Binder.getCallingUid(), flags, userId);
3918            }
3919        }
3920        return null;
3921    }
3922
3923    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3924        List<String> paths = new ArrayList<>();
3925        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3926            mEnabledOverlayPaths.get(userId);
3927        if (userSpecificOverlays != null) {
3928            if (!"android".equals(ai.packageName)) {
3929                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3930                if (frameworkOverlays != null) {
3931                    paths.addAll(frameworkOverlays);
3932                }
3933            }
3934
3935            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3936            if (appOverlays != null) {
3937                paths.addAll(appOverlays);
3938            }
3939        }
3940        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3941    }
3942
3943    private String normalizePackageNameLPr(String packageName) {
3944        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3945        return normalizedPackageName != null ? normalizedPackageName : packageName;
3946    }
3947
3948    @Override
3949    public void deletePreloadsFileCache() {
3950        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3951            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3952        }
3953        File dir = Environment.getDataPreloadsFileCacheDirectory();
3954        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3955        FileUtils.deleteContents(dir);
3956    }
3957
3958    @Override
3959    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3960            final IPackageDataObserver observer) {
3961        mContext.enforceCallingOrSelfPermission(
3962                android.Manifest.permission.CLEAR_APP_CACHE, null);
3963        mHandler.post(() -> {
3964            boolean success = false;
3965            try {
3966                freeStorage(volumeUuid, freeStorageSize, 0);
3967                success = true;
3968            } catch (IOException e) {
3969                Slog.w(TAG, e);
3970            }
3971            if (observer != null) {
3972                try {
3973                    observer.onRemoveCompleted(null, success);
3974                } catch (RemoteException e) {
3975                    Slog.w(TAG, e);
3976                }
3977            }
3978        });
3979    }
3980
3981    @Override
3982    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3983            final IntentSender pi) {
3984        mContext.enforceCallingOrSelfPermission(
3985                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3986        mHandler.post(() -> {
3987            boolean success = false;
3988            try {
3989                freeStorage(volumeUuid, freeStorageSize, 0);
3990                success = true;
3991            } catch (IOException e) {
3992                Slog.w(TAG, e);
3993            }
3994            if (pi != null) {
3995                try {
3996                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3997                } catch (SendIntentException e) {
3998                    Slog.w(TAG, e);
3999                }
4000            }
4001        });
4002    }
4003
4004    /**
4005     * Blocking call to clear various types of cached data across the system
4006     * until the requested bytes are available.
4007     */
4008    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4009        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4010        final File file = storage.findPathForUuid(volumeUuid);
4011        if (file.getUsableSpace() >= bytes) return;
4012
4013        if (ENABLE_FREE_CACHE_V2) {
4014            final boolean aggressive = (storageFlags
4015                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4016            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4017                    volumeUuid);
4018
4019            // 1. Pre-flight to determine if we have any chance to succeed
4020            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4021            if (internalVolume && (aggressive || SystemProperties
4022                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4023                deletePreloadsFileCache();
4024                if (file.getUsableSpace() >= bytes) return;
4025            }
4026
4027            // 3. Consider parsed APK data (aggressive only)
4028            if (internalVolume && aggressive) {
4029                FileUtils.deleteContents(mCacheDir);
4030                if (file.getUsableSpace() >= bytes) return;
4031            }
4032
4033            // 4. Consider cached app data (above quotas)
4034            try {
4035                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
4036            } catch (InstallerException ignored) {
4037            }
4038            if (file.getUsableSpace() >= bytes) return;
4039
4040            // 5. Consider shared libraries with refcount=0 and age>2h
4041            // 6. Consider dexopt output (aggressive only)
4042            // 7. Consider ephemeral apps not used in last week
4043
4044            // 8. Consider cached app data (below quotas)
4045            try {
4046                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
4047                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4048            } catch (InstallerException ignored) {
4049            }
4050            if (file.getUsableSpace() >= bytes) return;
4051
4052            // 9. Consider DropBox entries
4053            // 10. Consider ephemeral cookies
4054
4055        } else {
4056            try {
4057                mInstaller.freeCache(volumeUuid, bytes, 0);
4058            } catch (InstallerException ignored) {
4059            }
4060            if (file.getUsableSpace() >= bytes) return;
4061        }
4062
4063        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4064    }
4065
4066    /**
4067     * Update given flags based on encryption status of current user.
4068     */
4069    private int updateFlags(int flags, int userId) {
4070        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4071                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4072            // Caller expressed an explicit opinion about what encryption
4073            // aware/unaware components they want to see, so fall through and
4074            // give them what they want
4075        } else {
4076            // Caller expressed no opinion, so match based on user state
4077            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4078                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4079            } else {
4080                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4081            }
4082        }
4083        return flags;
4084    }
4085
4086    private UserManagerInternal getUserManagerInternal() {
4087        if (mUserManagerInternal == null) {
4088            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4089        }
4090        return mUserManagerInternal;
4091    }
4092
4093    private DeviceIdleController.LocalService getDeviceIdleController() {
4094        if (mDeviceIdleController == null) {
4095            mDeviceIdleController =
4096                    LocalServices.getService(DeviceIdleController.LocalService.class);
4097        }
4098        return mDeviceIdleController;
4099    }
4100
4101    /**
4102     * Update given flags when being used to request {@link PackageInfo}.
4103     */
4104    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4105        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4106        boolean triaged = true;
4107        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4108                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4109            // Caller is asking for component details, so they'd better be
4110            // asking for specific encryption matching behavior, or be triaged
4111            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4112                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4113                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4114                triaged = false;
4115            }
4116        }
4117        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4118                | PackageManager.MATCH_SYSTEM_ONLY
4119                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4120            triaged = false;
4121        }
4122        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4123            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4124                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4125                    + Debug.getCallers(5));
4126        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4127                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4128            // If the caller wants all packages and has a restricted profile associated with it,
4129            // then match all users. This is to make sure that launchers that need to access work
4130            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4131            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4132            flags |= PackageManager.MATCH_ANY_USER;
4133        }
4134        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4135            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4136                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4137        }
4138        return updateFlags(flags, userId);
4139    }
4140
4141    /**
4142     * Update given flags when being used to request {@link ApplicationInfo}.
4143     */
4144    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4145        return updateFlagsForPackage(flags, userId, cookie);
4146    }
4147
4148    /**
4149     * Update given flags when being used to request {@link ComponentInfo}.
4150     */
4151    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4152        if (cookie instanceof Intent) {
4153            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4154                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4155            }
4156        }
4157
4158        boolean triaged = true;
4159        // Caller is asking for component details, so they'd better be
4160        // asking for specific encryption matching behavior, or be triaged
4161        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4162                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4163                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4164            triaged = false;
4165        }
4166        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4167            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4168                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4169        }
4170
4171        return updateFlags(flags, userId);
4172    }
4173
4174    /**
4175     * Update given intent when being used to request {@link ResolveInfo}.
4176     */
4177    private Intent updateIntentForResolve(Intent intent) {
4178        if (intent.getSelector() != null) {
4179            intent = intent.getSelector();
4180        }
4181        if (DEBUG_PREFERRED) {
4182            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4183        }
4184        return intent;
4185    }
4186
4187    /**
4188     * Update given flags when being used to request {@link ResolveInfo}.
4189     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4190     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4191     * flag set. However, this flag is only honoured in three circumstances:
4192     * <ul>
4193     * <li>when called from a system process</li>
4194     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4195     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4196     * action and a {@code android.intent.category.BROWSABLE} category</li>
4197     * </ul>
4198     */
4199    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4200        return updateFlagsForResolve(flags, userId, intent, callingUid,
4201                false /*includeInstantApps*/, false /*onlyExposedExplicitly*/);
4202    }
4203    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4204            boolean includeInstantApps) {
4205        return updateFlagsForResolve(flags, userId, intent, callingUid,
4206                includeInstantApps, false /*onlyExposedExplicitly*/);
4207    }
4208    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4209            boolean includeInstantApps, boolean onlyExposedExplicitly) {
4210        // Safe mode means we shouldn't match any third-party components
4211        if (mSafeMode) {
4212            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4213        }
4214        if (getInstantAppPackageName(callingUid) != null) {
4215            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4216            if (onlyExposedExplicitly) {
4217                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4218            }
4219            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4220            flags |= PackageManager.MATCH_INSTANT;
4221        } else {
4222            // Otherwise, prevent leaking ephemeral components
4223            final boolean isSpecialProcess =
4224                    callingUid == Process.SYSTEM_UID
4225                    || callingUid == Process.SHELL_UID
4226                    || callingUid == 0;
4227            final boolean allowMatchInstant =
4228                    (includeInstantApps
4229                            && Intent.ACTION_VIEW.equals(intent.getAction())
4230                            && hasWebURI(intent))
4231                    || isSpecialProcess
4232                    || mContext.checkCallingOrSelfPermission(
4233                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4234            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4235                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4236            if (!allowMatchInstant) {
4237                flags &= ~PackageManager.MATCH_INSTANT;
4238            }
4239        }
4240        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4241    }
4242
4243    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4244            int userId) {
4245        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4246        if (ret != null) {
4247            rebaseEnabledOverlays(ret.applicationInfo, userId);
4248        }
4249        return ret;
4250    }
4251
4252    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4253            PackageUserState state, int userId) {
4254        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4255        if (ai != null) {
4256            rebaseEnabledOverlays(ai.applicationInfo, userId);
4257        }
4258        return ai;
4259    }
4260
4261    @Override
4262    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4263        if (!sUserManager.exists(userId)) return null;
4264        flags = updateFlagsForComponent(flags, userId, component);
4265        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4266                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4267        synchronized (mPackages) {
4268            PackageParser.Activity a = mActivities.mActivities.get(component);
4269
4270            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4271            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4272                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4273                if (ps == null) return null;
4274                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4275            }
4276            if (mResolveComponentName.equals(component)) {
4277                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4278                        userId);
4279            }
4280        }
4281        return null;
4282    }
4283
4284    @Override
4285    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4286            String resolvedType) {
4287        synchronized (mPackages) {
4288            if (component.equals(mResolveComponentName)) {
4289                // The resolver supports EVERYTHING!
4290                return true;
4291            }
4292            PackageParser.Activity a = mActivities.mActivities.get(component);
4293            if (a == null) {
4294                return false;
4295            }
4296            for (int i=0; i<a.intents.size(); i++) {
4297                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4298                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4299                    return true;
4300                }
4301            }
4302            return false;
4303        }
4304    }
4305
4306    @Override
4307    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4308        if (!sUserManager.exists(userId)) return null;
4309        flags = updateFlagsForComponent(flags, userId, component);
4310        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4311                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4312        synchronized (mPackages) {
4313            PackageParser.Activity a = mReceivers.mActivities.get(component);
4314            if (DEBUG_PACKAGE_INFO) Log.v(
4315                TAG, "getReceiverInfo " + component + ": " + a);
4316            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4317                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4318                if (ps == null) return null;
4319                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4320            }
4321        }
4322        return null;
4323    }
4324
4325    @Override
4326    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4327        if (!sUserManager.exists(userId)) return null;
4328        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4329
4330        flags = updateFlagsForPackage(flags, userId, null);
4331
4332        final boolean canSeeStaticLibraries =
4333                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4334                        == PERMISSION_GRANTED
4335                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4336                        == PERMISSION_GRANTED
4337                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4338                        == PERMISSION_GRANTED
4339                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4340                        == PERMISSION_GRANTED;
4341
4342        synchronized (mPackages) {
4343            List<SharedLibraryInfo> result = null;
4344
4345            final int libCount = mSharedLibraries.size();
4346            for (int i = 0; i < libCount; i++) {
4347                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4348                if (versionedLib == null) {
4349                    continue;
4350                }
4351
4352                final int versionCount = versionedLib.size();
4353                for (int j = 0; j < versionCount; j++) {
4354                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4355                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4356                        break;
4357                    }
4358                    final long identity = Binder.clearCallingIdentity();
4359                    try {
4360                        PackageInfo packageInfo = getPackageInfoVersioned(
4361                                libInfo.getDeclaringPackage(), flags, userId);
4362                        if (packageInfo == null) {
4363                            continue;
4364                        }
4365                    } finally {
4366                        Binder.restoreCallingIdentity(identity);
4367                    }
4368
4369                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4370                            libInfo.getVersion(), libInfo.getType(),
4371                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4372                            flags, userId));
4373
4374                    if (result == null) {
4375                        result = new ArrayList<>();
4376                    }
4377                    result.add(resLibInfo);
4378                }
4379            }
4380
4381            return result != null ? new ParceledListSlice<>(result) : null;
4382        }
4383    }
4384
4385    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4386            SharedLibraryInfo libInfo, int flags, int userId) {
4387        List<VersionedPackage> versionedPackages = null;
4388        final int packageCount = mSettings.mPackages.size();
4389        for (int i = 0; i < packageCount; i++) {
4390            PackageSetting ps = mSettings.mPackages.valueAt(i);
4391
4392            if (ps == null) {
4393                continue;
4394            }
4395
4396            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4397                continue;
4398            }
4399
4400            final String libName = libInfo.getName();
4401            if (libInfo.isStatic()) {
4402                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4403                if (libIdx < 0) {
4404                    continue;
4405                }
4406                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4407                    continue;
4408                }
4409                if (versionedPackages == null) {
4410                    versionedPackages = new ArrayList<>();
4411                }
4412                // If the dependent is a static shared lib, use the public package name
4413                String dependentPackageName = ps.name;
4414                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4415                    dependentPackageName = ps.pkg.manifestPackageName;
4416                }
4417                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4418            } else if (ps.pkg != null) {
4419                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4420                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4421                    if (versionedPackages == null) {
4422                        versionedPackages = new ArrayList<>();
4423                    }
4424                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4425                }
4426            }
4427        }
4428
4429        return versionedPackages;
4430    }
4431
4432    @Override
4433    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4434        if (!sUserManager.exists(userId)) return null;
4435        flags = updateFlagsForComponent(flags, userId, component);
4436        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4437                false /* requireFullPermission */, false /* checkShell */, "get service info");
4438        synchronized (mPackages) {
4439            PackageParser.Service s = mServices.mServices.get(component);
4440            if (DEBUG_PACKAGE_INFO) Log.v(
4441                TAG, "getServiceInfo " + component + ": " + s);
4442            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4443                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4444                if (ps == null) return null;
4445                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4446                        ps.readUserState(userId), userId);
4447                if (si != null) {
4448                    rebaseEnabledOverlays(si.applicationInfo, userId);
4449                }
4450                return si;
4451            }
4452        }
4453        return null;
4454    }
4455
4456    @Override
4457    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4458        if (!sUserManager.exists(userId)) return null;
4459        flags = updateFlagsForComponent(flags, userId, component);
4460        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4461                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4462        synchronized (mPackages) {
4463            PackageParser.Provider p = mProviders.mProviders.get(component);
4464            if (DEBUG_PACKAGE_INFO) Log.v(
4465                TAG, "getProviderInfo " + component + ": " + p);
4466            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4467                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4468                if (ps == null) return null;
4469                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4470                        ps.readUserState(userId), userId);
4471                if (pi != null) {
4472                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4473                }
4474                return pi;
4475            }
4476        }
4477        return null;
4478    }
4479
4480    @Override
4481    public String[] getSystemSharedLibraryNames() {
4482        synchronized (mPackages) {
4483            Set<String> libs = null;
4484            final int libCount = mSharedLibraries.size();
4485            for (int i = 0; i < libCount; i++) {
4486                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4487                if (versionedLib == null) {
4488                    continue;
4489                }
4490                final int versionCount = versionedLib.size();
4491                for (int j = 0; j < versionCount; j++) {
4492                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4493                    if (!libEntry.info.isStatic()) {
4494                        if (libs == null) {
4495                            libs = new ArraySet<>();
4496                        }
4497                        libs.add(libEntry.info.getName());
4498                        break;
4499                    }
4500                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4501                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4502                            UserHandle.getUserId(Binder.getCallingUid()),
4503                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4504                        if (libs == null) {
4505                            libs = new ArraySet<>();
4506                        }
4507                        libs.add(libEntry.info.getName());
4508                        break;
4509                    }
4510                }
4511            }
4512
4513            if (libs != null) {
4514                String[] libsArray = new String[libs.size()];
4515                libs.toArray(libsArray);
4516                return libsArray;
4517            }
4518
4519            return null;
4520        }
4521    }
4522
4523    @Override
4524    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4525        synchronized (mPackages) {
4526            return mServicesSystemSharedLibraryPackageName;
4527        }
4528    }
4529
4530    @Override
4531    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4532        synchronized (mPackages) {
4533            return mSharedSystemSharedLibraryPackageName;
4534        }
4535    }
4536
4537    private void updateSequenceNumberLP(String packageName, int[] userList) {
4538        for (int i = userList.length - 1; i >= 0; --i) {
4539            final int userId = userList[i];
4540            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4541            if (changedPackages == null) {
4542                changedPackages = new SparseArray<>();
4543                mChangedPackages.put(userId, changedPackages);
4544            }
4545            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4546            if (sequenceNumbers == null) {
4547                sequenceNumbers = new HashMap<>();
4548                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4549            }
4550            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4551            if (sequenceNumber != null) {
4552                changedPackages.remove(sequenceNumber);
4553            }
4554            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4555            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4556        }
4557        mChangedPackagesSequenceNumber++;
4558    }
4559
4560    @Override
4561    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4562        synchronized (mPackages) {
4563            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4564                return null;
4565            }
4566            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4567            if (changedPackages == null) {
4568                return null;
4569            }
4570            final List<String> packageNames =
4571                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4572            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4573                final String packageName = changedPackages.get(i);
4574                if (packageName != null) {
4575                    packageNames.add(packageName);
4576                }
4577            }
4578            return packageNames.isEmpty()
4579                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4580        }
4581    }
4582
4583    @Override
4584    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4585        ArrayList<FeatureInfo> res;
4586        synchronized (mAvailableFeatures) {
4587            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4588            res.addAll(mAvailableFeatures.values());
4589        }
4590        final FeatureInfo fi = new FeatureInfo();
4591        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4592                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4593        res.add(fi);
4594
4595        return new ParceledListSlice<>(res);
4596    }
4597
4598    @Override
4599    public boolean hasSystemFeature(String name, int version) {
4600        synchronized (mAvailableFeatures) {
4601            final FeatureInfo feat = mAvailableFeatures.get(name);
4602            if (feat == null) {
4603                return false;
4604            } else {
4605                return feat.version >= version;
4606            }
4607        }
4608    }
4609
4610    @Override
4611    public int checkPermission(String permName, String pkgName, int userId) {
4612        if (!sUserManager.exists(userId)) {
4613            return PackageManager.PERMISSION_DENIED;
4614        }
4615
4616        synchronized (mPackages) {
4617            final PackageParser.Package p = mPackages.get(pkgName);
4618            if (p != null && p.mExtras != null) {
4619                final PackageSetting ps = (PackageSetting) p.mExtras;
4620                final PermissionsState permissionsState = ps.getPermissionsState();
4621                if (permissionsState.hasPermission(permName, userId)) {
4622                    return PackageManager.PERMISSION_GRANTED;
4623                }
4624                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4625                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4626                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4627                    return PackageManager.PERMISSION_GRANTED;
4628                }
4629            }
4630        }
4631
4632        return PackageManager.PERMISSION_DENIED;
4633    }
4634
4635    @Override
4636    public int checkUidPermission(String permName, int uid) {
4637        final int userId = UserHandle.getUserId(uid);
4638
4639        if (!sUserManager.exists(userId)) {
4640            return PackageManager.PERMISSION_DENIED;
4641        }
4642
4643        synchronized (mPackages) {
4644            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4645            if (obj != null) {
4646                final SettingBase ps = (SettingBase) obj;
4647                final PermissionsState permissionsState = ps.getPermissionsState();
4648                if (permissionsState.hasPermission(permName, userId)) {
4649                    return PackageManager.PERMISSION_GRANTED;
4650                }
4651                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4652                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4653                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4654                    return PackageManager.PERMISSION_GRANTED;
4655                }
4656            } else {
4657                ArraySet<String> perms = mSystemPermissions.get(uid);
4658                if (perms != null) {
4659                    if (perms.contains(permName)) {
4660                        return PackageManager.PERMISSION_GRANTED;
4661                    }
4662                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4663                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4664                        return PackageManager.PERMISSION_GRANTED;
4665                    }
4666                }
4667            }
4668        }
4669
4670        return PackageManager.PERMISSION_DENIED;
4671    }
4672
4673    @Override
4674    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4675        if (UserHandle.getCallingUserId() != userId) {
4676            mContext.enforceCallingPermission(
4677                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4678                    "isPermissionRevokedByPolicy for user " + userId);
4679        }
4680
4681        if (checkPermission(permission, packageName, userId)
4682                == PackageManager.PERMISSION_GRANTED) {
4683            return false;
4684        }
4685
4686        final long identity = Binder.clearCallingIdentity();
4687        try {
4688            final int flags = getPermissionFlags(permission, packageName, userId);
4689            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4690        } finally {
4691            Binder.restoreCallingIdentity(identity);
4692        }
4693    }
4694
4695    @Override
4696    public String getPermissionControllerPackageName() {
4697        synchronized (mPackages) {
4698            return mRequiredInstallerPackage;
4699        }
4700    }
4701
4702    /**
4703     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4704     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4705     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4706     * @param message the message to log on security exception
4707     */
4708    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4709            boolean checkShell, String message) {
4710        if (userId < 0) {
4711            throw new IllegalArgumentException("Invalid userId " + userId);
4712        }
4713        if (checkShell) {
4714            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4715        }
4716        if (userId == UserHandle.getUserId(callingUid)) return;
4717        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4718            if (requireFullPermission) {
4719                mContext.enforceCallingOrSelfPermission(
4720                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4721            } else {
4722                try {
4723                    mContext.enforceCallingOrSelfPermission(
4724                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4725                } catch (SecurityException se) {
4726                    mContext.enforceCallingOrSelfPermission(
4727                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4728                }
4729            }
4730        }
4731    }
4732
4733    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4734        if (callingUid == Process.SHELL_UID) {
4735            if (userHandle >= 0
4736                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4737                throw new SecurityException("Shell does not have permission to access user "
4738                        + userHandle);
4739            } else if (userHandle < 0) {
4740                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4741                        + Debug.getCallers(3));
4742            }
4743        }
4744    }
4745
4746    private BasePermission findPermissionTreeLP(String permName) {
4747        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4748            if (permName.startsWith(bp.name) &&
4749                    permName.length() > bp.name.length() &&
4750                    permName.charAt(bp.name.length()) == '.') {
4751                return bp;
4752            }
4753        }
4754        return null;
4755    }
4756
4757    private BasePermission checkPermissionTreeLP(String permName) {
4758        if (permName != null) {
4759            BasePermission bp = findPermissionTreeLP(permName);
4760            if (bp != null) {
4761                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4762                    return bp;
4763                }
4764                throw new SecurityException("Calling uid "
4765                        + Binder.getCallingUid()
4766                        + " is not allowed to add to permission tree "
4767                        + bp.name + " owned by uid " + bp.uid);
4768            }
4769        }
4770        throw new SecurityException("No permission tree found for " + permName);
4771    }
4772
4773    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4774        if (s1 == null) {
4775            return s2 == null;
4776        }
4777        if (s2 == null) {
4778            return false;
4779        }
4780        if (s1.getClass() != s2.getClass()) {
4781            return false;
4782        }
4783        return s1.equals(s2);
4784    }
4785
4786    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4787        if (pi1.icon != pi2.icon) return false;
4788        if (pi1.logo != pi2.logo) return false;
4789        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4790        if (!compareStrings(pi1.name, pi2.name)) return false;
4791        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4792        // We'll take care of setting this one.
4793        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4794        // These are not currently stored in settings.
4795        //if (!compareStrings(pi1.group, pi2.group)) return false;
4796        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4797        //if (pi1.labelRes != pi2.labelRes) return false;
4798        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4799        return true;
4800    }
4801
4802    int permissionInfoFootprint(PermissionInfo info) {
4803        int size = info.name.length();
4804        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4805        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4806        return size;
4807    }
4808
4809    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4810        int size = 0;
4811        for (BasePermission perm : mSettings.mPermissions.values()) {
4812            if (perm.uid == tree.uid) {
4813                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4814            }
4815        }
4816        return size;
4817    }
4818
4819    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4820        // We calculate the max size of permissions defined by this uid and throw
4821        // if that plus the size of 'info' would exceed our stated maximum.
4822        if (tree.uid != Process.SYSTEM_UID) {
4823            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4824            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4825                throw new SecurityException("Permission tree size cap exceeded");
4826            }
4827        }
4828    }
4829
4830    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4831        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4832            throw new SecurityException("Label must be specified in permission");
4833        }
4834        BasePermission tree = checkPermissionTreeLP(info.name);
4835        BasePermission bp = mSettings.mPermissions.get(info.name);
4836        boolean added = bp == null;
4837        boolean changed = true;
4838        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4839        if (added) {
4840            enforcePermissionCapLocked(info, tree);
4841            bp = new BasePermission(info.name, tree.sourcePackage,
4842                    BasePermission.TYPE_DYNAMIC);
4843        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4844            throw new SecurityException(
4845                    "Not allowed to modify non-dynamic permission "
4846                    + info.name);
4847        } else {
4848            if (bp.protectionLevel == fixedLevel
4849                    && bp.perm.owner.equals(tree.perm.owner)
4850                    && bp.uid == tree.uid
4851                    && comparePermissionInfos(bp.perm.info, info)) {
4852                changed = false;
4853            }
4854        }
4855        bp.protectionLevel = fixedLevel;
4856        info = new PermissionInfo(info);
4857        info.protectionLevel = fixedLevel;
4858        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4859        bp.perm.info.packageName = tree.perm.info.packageName;
4860        bp.uid = tree.uid;
4861        if (added) {
4862            mSettings.mPermissions.put(info.name, bp);
4863        }
4864        if (changed) {
4865            if (!async) {
4866                mSettings.writeLPr();
4867            } else {
4868                scheduleWriteSettingsLocked();
4869            }
4870        }
4871        return added;
4872    }
4873
4874    @Override
4875    public boolean addPermission(PermissionInfo info) {
4876        synchronized (mPackages) {
4877            return addPermissionLocked(info, false);
4878        }
4879    }
4880
4881    @Override
4882    public boolean addPermissionAsync(PermissionInfo info) {
4883        synchronized (mPackages) {
4884            return addPermissionLocked(info, true);
4885        }
4886    }
4887
4888    @Override
4889    public void removePermission(String name) {
4890        synchronized (mPackages) {
4891            checkPermissionTreeLP(name);
4892            BasePermission bp = mSettings.mPermissions.get(name);
4893            if (bp != null) {
4894                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4895                    throw new SecurityException(
4896                            "Not allowed to modify non-dynamic permission "
4897                            + name);
4898                }
4899                mSettings.mPermissions.remove(name);
4900                mSettings.writeLPr();
4901            }
4902        }
4903    }
4904
4905    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4906            BasePermission bp) {
4907        int index = pkg.requestedPermissions.indexOf(bp.name);
4908        if (index == -1) {
4909            throw new SecurityException("Package " + pkg.packageName
4910                    + " has not requested permission " + bp.name);
4911        }
4912        if (!bp.isRuntime() && !bp.isDevelopment()) {
4913            throw new SecurityException("Permission " + bp.name
4914                    + " is not a changeable permission type");
4915        }
4916    }
4917
4918    @Override
4919    public void grantRuntimePermission(String packageName, String name, final int userId) {
4920        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4921    }
4922
4923    private void grantRuntimePermission(String packageName, String name, final int userId,
4924            boolean overridePolicy) {
4925        if (!sUserManager.exists(userId)) {
4926            Log.e(TAG, "No such user:" + userId);
4927            return;
4928        }
4929
4930        mContext.enforceCallingOrSelfPermission(
4931                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4932                "grantRuntimePermission");
4933
4934        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4935                true /* requireFullPermission */, true /* checkShell */,
4936                "grantRuntimePermission");
4937
4938        final int uid;
4939        final SettingBase sb;
4940
4941        synchronized (mPackages) {
4942            final PackageParser.Package pkg = mPackages.get(packageName);
4943            if (pkg == null) {
4944                throw new IllegalArgumentException("Unknown package: " + packageName);
4945            }
4946
4947            final BasePermission bp = mSettings.mPermissions.get(name);
4948            if (bp == null) {
4949                throw new IllegalArgumentException("Unknown permission: " + name);
4950            }
4951
4952            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4953
4954            // If a permission review is required for legacy apps we represent
4955            // their permissions as always granted runtime ones since we need
4956            // to keep the review required permission flag per user while an
4957            // install permission's state is shared across all users.
4958            if (mPermissionReviewRequired
4959                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4960                    && bp.isRuntime()) {
4961                return;
4962            }
4963
4964            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4965            sb = (SettingBase) pkg.mExtras;
4966            if (sb == null) {
4967                throw new IllegalArgumentException("Unknown package: " + packageName);
4968            }
4969
4970            final PermissionsState permissionsState = sb.getPermissionsState();
4971
4972            final int flags = permissionsState.getPermissionFlags(name, userId);
4973            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4974                throw new SecurityException("Cannot grant system fixed permission "
4975                        + name + " for package " + packageName);
4976            }
4977            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4978                throw new SecurityException("Cannot grant policy fixed permission "
4979                        + name + " for package " + packageName);
4980            }
4981
4982            if (bp.isDevelopment()) {
4983                // Development permissions must be handled specially, since they are not
4984                // normal runtime permissions.  For now they apply to all users.
4985                if (permissionsState.grantInstallPermission(bp) !=
4986                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4987                    scheduleWriteSettingsLocked();
4988                }
4989                return;
4990            }
4991
4992            final PackageSetting ps = mSettings.mPackages.get(packageName);
4993            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4994                throw new SecurityException("Cannot grant non-ephemeral permission"
4995                        + name + " for package " + packageName);
4996            }
4997
4998            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4999                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5000                return;
5001            }
5002
5003            final int result = permissionsState.grantRuntimePermission(bp, userId);
5004            switch (result) {
5005                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5006                    return;
5007                }
5008
5009                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5010                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5011                    mHandler.post(new Runnable() {
5012                        @Override
5013                        public void run() {
5014                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5015                        }
5016                    });
5017                }
5018                break;
5019            }
5020
5021            if (bp.isRuntime()) {
5022                logPermissionGranted(mContext, name, packageName);
5023            }
5024
5025            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5026
5027            // Not critical if that is lost - app has to request again.
5028            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5029        }
5030
5031        // Only need to do this if user is initialized. Otherwise it's a new user
5032        // and there are no processes running as the user yet and there's no need
5033        // to make an expensive call to remount processes for the changed permissions.
5034        if (READ_EXTERNAL_STORAGE.equals(name)
5035                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5036            final long token = Binder.clearCallingIdentity();
5037            try {
5038                if (sUserManager.isInitialized(userId)) {
5039                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5040                            StorageManagerInternal.class);
5041                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5042                }
5043            } finally {
5044                Binder.restoreCallingIdentity(token);
5045            }
5046        }
5047    }
5048
5049    @Override
5050    public void revokeRuntimePermission(String packageName, String name, int userId) {
5051        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5052    }
5053
5054    private void revokeRuntimePermission(String packageName, String name, int userId,
5055            boolean overridePolicy) {
5056        if (!sUserManager.exists(userId)) {
5057            Log.e(TAG, "No such user:" + userId);
5058            return;
5059        }
5060
5061        mContext.enforceCallingOrSelfPermission(
5062                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5063                "revokeRuntimePermission");
5064
5065        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5066                true /* requireFullPermission */, true /* checkShell */,
5067                "revokeRuntimePermission");
5068
5069        final int appId;
5070
5071        synchronized (mPackages) {
5072            final PackageParser.Package pkg = mPackages.get(packageName);
5073            if (pkg == null) {
5074                throw new IllegalArgumentException("Unknown package: " + packageName);
5075            }
5076
5077            final BasePermission bp = mSettings.mPermissions.get(name);
5078            if (bp == null) {
5079                throw new IllegalArgumentException("Unknown permission: " + name);
5080            }
5081
5082            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5083
5084            // If a permission review is required for legacy apps we represent
5085            // their permissions as always granted runtime ones since we need
5086            // to keep the review required permission flag per user while an
5087            // install permission's state is shared across all users.
5088            if (mPermissionReviewRequired
5089                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5090                    && bp.isRuntime()) {
5091                return;
5092            }
5093
5094            SettingBase sb = (SettingBase) pkg.mExtras;
5095            if (sb == null) {
5096                throw new IllegalArgumentException("Unknown package: " + packageName);
5097            }
5098
5099            final PermissionsState permissionsState = sb.getPermissionsState();
5100
5101            final int flags = permissionsState.getPermissionFlags(name, userId);
5102            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5103                throw new SecurityException("Cannot revoke system fixed permission "
5104                        + name + " for package " + packageName);
5105            }
5106            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5107                throw new SecurityException("Cannot revoke policy fixed permission "
5108                        + name + " for package " + packageName);
5109            }
5110
5111            if (bp.isDevelopment()) {
5112                // Development permissions must be handled specially, since they are not
5113                // normal runtime permissions.  For now they apply to all users.
5114                if (permissionsState.revokeInstallPermission(bp) !=
5115                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5116                    scheduleWriteSettingsLocked();
5117                }
5118                return;
5119            }
5120
5121            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5122                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5123                return;
5124            }
5125
5126            if (bp.isRuntime()) {
5127                logPermissionRevoked(mContext, name, packageName);
5128            }
5129
5130            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5131
5132            // Critical, after this call app should never have the permission.
5133            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5134
5135            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5136        }
5137
5138        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5139    }
5140
5141    /**
5142     * Get the first event id for the permission.
5143     *
5144     * <p>There are four events for each permission: <ul>
5145     *     <li>Request permission: first id + 0</li>
5146     *     <li>Grant permission: first id + 1</li>
5147     *     <li>Request for permission denied: first id + 2</li>
5148     *     <li>Revoke permission: first id + 3</li>
5149     * </ul></p>
5150     *
5151     * @param name name of the permission
5152     *
5153     * @return The first event id for the permission
5154     */
5155    private static int getBaseEventId(@NonNull String name) {
5156        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5157
5158        if (eventIdIndex == -1) {
5159            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5160                    || "user".equals(Build.TYPE)) {
5161                Log.i(TAG, "Unknown permission " + name);
5162
5163                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5164            } else {
5165                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5166                //
5167                // Also update
5168                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5169                // - metrics_constants.proto
5170                throw new IllegalStateException("Unknown permission " + name);
5171            }
5172        }
5173
5174        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5175    }
5176
5177    /**
5178     * Log that a permission was revoked.
5179     *
5180     * @param context Context of the caller
5181     * @param name name of the permission
5182     * @param packageName package permission if for
5183     */
5184    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5185            @NonNull String packageName) {
5186        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5187    }
5188
5189    /**
5190     * Log that a permission request was granted.
5191     *
5192     * @param context Context of the caller
5193     * @param name name of the permission
5194     * @param packageName package permission if for
5195     */
5196    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5197            @NonNull String packageName) {
5198        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5199    }
5200
5201    @Override
5202    public void resetRuntimePermissions() {
5203        mContext.enforceCallingOrSelfPermission(
5204                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5205                "revokeRuntimePermission");
5206
5207        int callingUid = Binder.getCallingUid();
5208        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5209            mContext.enforceCallingOrSelfPermission(
5210                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5211                    "resetRuntimePermissions");
5212        }
5213
5214        synchronized (mPackages) {
5215            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5216            for (int userId : UserManagerService.getInstance().getUserIds()) {
5217                final int packageCount = mPackages.size();
5218                for (int i = 0; i < packageCount; i++) {
5219                    PackageParser.Package pkg = mPackages.valueAt(i);
5220                    if (!(pkg.mExtras instanceof PackageSetting)) {
5221                        continue;
5222                    }
5223                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5224                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5225                }
5226            }
5227        }
5228    }
5229
5230    @Override
5231    public int getPermissionFlags(String name, String packageName, int userId) {
5232        if (!sUserManager.exists(userId)) {
5233            return 0;
5234        }
5235
5236        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5237
5238        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5239                true /* requireFullPermission */, false /* checkShell */,
5240                "getPermissionFlags");
5241
5242        synchronized (mPackages) {
5243            final PackageParser.Package pkg = mPackages.get(packageName);
5244            if (pkg == null) {
5245                return 0;
5246            }
5247
5248            final BasePermission bp = mSettings.mPermissions.get(name);
5249            if (bp == null) {
5250                return 0;
5251            }
5252
5253            SettingBase sb = (SettingBase) pkg.mExtras;
5254            if (sb == null) {
5255                return 0;
5256            }
5257
5258            PermissionsState permissionsState = sb.getPermissionsState();
5259            return permissionsState.getPermissionFlags(name, userId);
5260        }
5261    }
5262
5263    @Override
5264    public void updatePermissionFlags(String name, String packageName, int flagMask,
5265            int flagValues, int userId) {
5266        if (!sUserManager.exists(userId)) {
5267            return;
5268        }
5269
5270        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5271
5272        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5273                true /* requireFullPermission */, true /* checkShell */,
5274                "updatePermissionFlags");
5275
5276        // Only the system can change these flags and nothing else.
5277        if (getCallingUid() != Process.SYSTEM_UID) {
5278            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5279            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5280            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5281            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5282            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5283        }
5284
5285        synchronized (mPackages) {
5286            final PackageParser.Package pkg = mPackages.get(packageName);
5287            if (pkg == null) {
5288                throw new IllegalArgumentException("Unknown package: " + packageName);
5289            }
5290
5291            final BasePermission bp = mSettings.mPermissions.get(name);
5292            if (bp == null) {
5293                throw new IllegalArgumentException("Unknown permission: " + name);
5294            }
5295
5296            SettingBase sb = (SettingBase) pkg.mExtras;
5297            if (sb == null) {
5298                throw new IllegalArgumentException("Unknown package: " + packageName);
5299            }
5300
5301            PermissionsState permissionsState = sb.getPermissionsState();
5302
5303            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5304
5305            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5306                // Install and runtime permissions are stored in different places,
5307                // so figure out what permission changed and persist the change.
5308                if (permissionsState.getInstallPermissionState(name) != null) {
5309                    scheduleWriteSettingsLocked();
5310                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5311                        || hadState) {
5312                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5313                }
5314            }
5315        }
5316    }
5317
5318    /**
5319     * Update the permission flags for all packages and runtime permissions of a user in order
5320     * to allow device or profile owner to remove POLICY_FIXED.
5321     */
5322    @Override
5323    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5324        if (!sUserManager.exists(userId)) {
5325            return;
5326        }
5327
5328        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5329
5330        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5331                true /* requireFullPermission */, true /* checkShell */,
5332                "updatePermissionFlagsForAllApps");
5333
5334        // Only the system can change system fixed flags.
5335        if (getCallingUid() != Process.SYSTEM_UID) {
5336            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5337            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5338        }
5339
5340        synchronized (mPackages) {
5341            boolean changed = false;
5342            final int packageCount = mPackages.size();
5343            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5344                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5345                SettingBase sb = (SettingBase) pkg.mExtras;
5346                if (sb == null) {
5347                    continue;
5348                }
5349                PermissionsState permissionsState = sb.getPermissionsState();
5350                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5351                        userId, flagMask, flagValues);
5352            }
5353            if (changed) {
5354                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5355            }
5356        }
5357    }
5358
5359    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5360        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5361                != PackageManager.PERMISSION_GRANTED
5362            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5363                != PackageManager.PERMISSION_GRANTED) {
5364            throw new SecurityException(message + " requires "
5365                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5366                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5367        }
5368    }
5369
5370    @Override
5371    public boolean shouldShowRequestPermissionRationale(String permissionName,
5372            String packageName, int userId) {
5373        if (UserHandle.getCallingUserId() != userId) {
5374            mContext.enforceCallingPermission(
5375                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5376                    "canShowRequestPermissionRationale for user " + userId);
5377        }
5378
5379        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5380        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5381            return false;
5382        }
5383
5384        if (checkPermission(permissionName, packageName, userId)
5385                == PackageManager.PERMISSION_GRANTED) {
5386            return false;
5387        }
5388
5389        final int flags;
5390
5391        final long identity = Binder.clearCallingIdentity();
5392        try {
5393            flags = getPermissionFlags(permissionName,
5394                    packageName, userId);
5395        } finally {
5396            Binder.restoreCallingIdentity(identity);
5397        }
5398
5399        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5400                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5401                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5402
5403        if ((flags & fixedFlags) != 0) {
5404            return false;
5405        }
5406
5407        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5408    }
5409
5410    @Override
5411    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5412        mContext.enforceCallingOrSelfPermission(
5413                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5414                "addOnPermissionsChangeListener");
5415
5416        synchronized (mPackages) {
5417            mOnPermissionChangeListeners.addListenerLocked(listener);
5418        }
5419    }
5420
5421    @Override
5422    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5423        synchronized (mPackages) {
5424            mOnPermissionChangeListeners.removeListenerLocked(listener);
5425        }
5426    }
5427
5428    @Override
5429    public boolean isProtectedBroadcast(String actionName) {
5430        synchronized (mPackages) {
5431            if (mProtectedBroadcasts.contains(actionName)) {
5432                return true;
5433            } else if (actionName != null) {
5434                // TODO: remove these terrible hacks
5435                if (actionName.startsWith("android.net.netmon.lingerExpired")
5436                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5437                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5438                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5439                    return true;
5440                }
5441            }
5442        }
5443        return false;
5444    }
5445
5446    @Override
5447    public int checkSignatures(String pkg1, String pkg2) {
5448        synchronized (mPackages) {
5449            final PackageParser.Package p1 = mPackages.get(pkg1);
5450            final PackageParser.Package p2 = mPackages.get(pkg2);
5451            if (p1 == null || p1.mExtras == null
5452                    || p2 == null || p2.mExtras == null) {
5453                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5454            }
5455            return compareSignatures(p1.mSignatures, p2.mSignatures);
5456        }
5457    }
5458
5459    @Override
5460    public int checkUidSignatures(int uid1, int uid2) {
5461        // Map to base uids.
5462        uid1 = UserHandle.getAppId(uid1);
5463        uid2 = UserHandle.getAppId(uid2);
5464        // reader
5465        synchronized (mPackages) {
5466            Signature[] s1;
5467            Signature[] s2;
5468            Object obj = mSettings.getUserIdLPr(uid1);
5469            if (obj != null) {
5470                if (obj instanceof SharedUserSetting) {
5471                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5472                } else if (obj instanceof PackageSetting) {
5473                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5474                } else {
5475                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5476                }
5477            } else {
5478                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5479            }
5480            obj = mSettings.getUserIdLPr(uid2);
5481            if (obj != null) {
5482                if (obj instanceof SharedUserSetting) {
5483                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5484                } else if (obj instanceof PackageSetting) {
5485                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5486                } else {
5487                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5488                }
5489            } else {
5490                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5491            }
5492            return compareSignatures(s1, s2);
5493        }
5494    }
5495
5496    /**
5497     * This method should typically only be used when granting or revoking
5498     * permissions, since the app may immediately restart after this call.
5499     * <p>
5500     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5501     * guard your work against the app being relaunched.
5502     */
5503    private void killUid(int appId, int userId, String reason) {
5504        final long identity = Binder.clearCallingIdentity();
5505        try {
5506            IActivityManager am = ActivityManager.getService();
5507            if (am != null) {
5508                try {
5509                    am.killUid(appId, userId, reason);
5510                } catch (RemoteException e) {
5511                    /* ignore - same process */
5512                }
5513            }
5514        } finally {
5515            Binder.restoreCallingIdentity(identity);
5516        }
5517    }
5518
5519    /**
5520     * Compares two sets of signatures. Returns:
5521     * <br />
5522     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5523     * <br />
5524     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5525     * <br />
5526     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5527     * <br />
5528     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5529     * <br />
5530     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5531     */
5532    static int compareSignatures(Signature[] s1, Signature[] s2) {
5533        if (s1 == null) {
5534            return s2 == null
5535                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5536                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5537        }
5538
5539        if (s2 == null) {
5540            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5541        }
5542
5543        if (s1.length != s2.length) {
5544            return PackageManager.SIGNATURE_NO_MATCH;
5545        }
5546
5547        // Since both signature sets are of size 1, we can compare without HashSets.
5548        if (s1.length == 1) {
5549            return s1[0].equals(s2[0]) ?
5550                    PackageManager.SIGNATURE_MATCH :
5551                    PackageManager.SIGNATURE_NO_MATCH;
5552        }
5553
5554        ArraySet<Signature> set1 = new ArraySet<Signature>();
5555        for (Signature sig : s1) {
5556            set1.add(sig);
5557        }
5558        ArraySet<Signature> set2 = new ArraySet<Signature>();
5559        for (Signature sig : s2) {
5560            set2.add(sig);
5561        }
5562        // Make sure s2 contains all signatures in s1.
5563        if (set1.equals(set2)) {
5564            return PackageManager.SIGNATURE_MATCH;
5565        }
5566        return PackageManager.SIGNATURE_NO_MATCH;
5567    }
5568
5569    /**
5570     * If the database version for this type of package (internal storage or
5571     * external storage) is less than the version where package signatures
5572     * were updated, return true.
5573     */
5574    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5575        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5576        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5577    }
5578
5579    /**
5580     * Used for backward compatibility to make sure any packages with
5581     * certificate chains get upgraded to the new style. {@code existingSigs}
5582     * will be in the old format (since they were stored on disk from before the
5583     * system upgrade) and {@code scannedSigs} will be in the newer format.
5584     */
5585    private int compareSignaturesCompat(PackageSignatures existingSigs,
5586            PackageParser.Package scannedPkg) {
5587        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5588            return PackageManager.SIGNATURE_NO_MATCH;
5589        }
5590
5591        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5592        for (Signature sig : existingSigs.mSignatures) {
5593            existingSet.add(sig);
5594        }
5595        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5596        for (Signature sig : scannedPkg.mSignatures) {
5597            try {
5598                Signature[] chainSignatures = sig.getChainSignatures();
5599                for (Signature chainSig : chainSignatures) {
5600                    scannedCompatSet.add(chainSig);
5601                }
5602            } catch (CertificateEncodingException e) {
5603                scannedCompatSet.add(sig);
5604            }
5605        }
5606        /*
5607         * Make sure the expanded scanned set contains all signatures in the
5608         * existing one.
5609         */
5610        if (scannedCompatSet.equals(existingSet)) {
5611            // Migrate the old signatures to the new scheme.
5612            existingSigs.assignSignatures(scannedPkg.mSignatures);
5613            // The new KeySets will be re-added later in the scanning process.
5614            synchronized (mPackages) {
5615                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5616            }
5617            return PackageManager.SIGNATURE_MATCH;
5618        }
5619        return PackageManager.SIGNATURE_NO_MATCH;
5620    }
5621
5622    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5623        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5624        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5625    }
5626
5627    private int compareSignaturesRecover(PackageSignatures existingSigs,
5628            PackageParser.Package scannedPkg) {
5629        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5630            return PackageManager.SIGNATURE_NO_MATCH;
5631        }
5632
5633        String msg = null;
5634        try {
5635            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5636                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5637                        + scannedPkg.packageName);
5638                return PackageManager.SIGNATURE_MATCH;
5639            }
5640        } catch (CertificateException e) {
5641            msg = e.getMessage();
5642        }
5643
5644        logCriticalInfo(Log.INFO,
5645                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5646        return PackageManager.SIGNATURE_NO_MATCH;
5647    }
5648
5649    @Override
5650    public List<String> getAllPackages() {
5651        synchronized (mPackages) {
5652            return new ArrayList<String>(mPackages.keySet());
5653        }
5654    }
5655
5656    @Override
5657    public String[] getPackagesForUid(int uid) {
5658        final int userId = UserHandle.getUserId(uid);
5659        uid = UserHandle.getAppId(uid);
5660        // reader
5661        synchronized (mPackages) {
5662            Object obj = mSettings.getUserIdLPr(uid);
5663            if (obj instanceof SharedUserSetting) {
5664                final SharedUserSetting sus = (SharedUserSetting) obj;
5665                final int N = sus.packages.size();
5666                String[] res = new String[N];
5667                final Iterator<PackageSetting> it = sus.packages.iterator();
5668                int i = 0;
5669                while (it.hasNext()) {
5670                    PackageSetting ps = it.next();
5671                    if (ps.getInstalled(userId)) {
5672                        res[i++] = ps.name;
5673                    } else {
5674                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5675                    }
5676                }
5677                return res;
5678            } else if (obj instanceof PackageSetting) {
5679                final PackageSetting ps = (PackageSetting) obj;
5680                if (ps.getInstalled(userId)) {
5681                    return new String[]{ps.name};
5682                }
5683            }
5684        }
5685        return null;
5686    }
5687
5688    @Override
5689    public String getNameForUid(int uid) {
5690        // reader
5691        synchronized (mPackages) {
5692            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5693            if (obj instanceof SharedUserSetting) {
5694                final SharedUserSetting sus = (SharedUserSetting) obj;
5695                return sus.name + ":" + sus.userId;
5696            } else if (obj instanceof PackageSetting) {
5697                final PackageSetting ps = (PackageSetting) obj;
5698                return ps.name;
5699            }
5700        }
5701        return null;
5702    }
5703
5704    @Override
5705    public int getUidForSharedUser(String sharedUserName) {
5706        if(sharedUserName == null) {
5707            return -1;
5708        }
5709        // reader
5710        synchronized (mPackages) {
5711            SharedUserSetting suid;
5712            try {
5713                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5714                if (suid != null) {
5715                    return suid.userId;
5716                }
5717            } catch (PackageManagerException ignore) {
5718                // can't happen, but, still need to catch it
5719            }
5720            return -1;
5721        }
5722    }
5723
5724    @Override
5725    public int getFlagsForUid(int uid) {
5726        synchronized (mPackages) {
5727            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5728            if (obj instanceof SharedUserSetting) {
5729                final SharedUserSetting sus = (SharedUserSetting) obj;
5730                return sus.pkgFlags;
5731            } else if (obj instanceof PackageSetting) {
5732                final PackageSetting ps = (PackageSetting) obj;
5733                return ps.pkgFlags;
5734            }
5735        }
5736        return 0;
5737    }
5738
5739    @Override
5740    public int getPrivateFlagsForUid(int uid) {
5741        synchronized (mPackages) {
5742            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5743            if (obj instanceof SharedUserSetting) {
5744                final SharedUserSetting sus = (SharedUserSetting) obj;
5745                return sus.pkgPrivateFlags;
5746            } else if (obj instanceof PackageSetting) {
5747                final PackageSetting ps = (PackageSetting) obj;
5748                return ps.pkgPrivateFlags;
5749            }
5750        }
5751        return 0;
5752    }
5753
5754    @Override
5755    public boolean isUidPrivileged(int uid) {
5756        uid = UserHandle.getAppId(uid);
5757        // reader
5758        synchronized (mPackages) {
5759            Object obj = mSettings.getUserIdLPr(uid);
5760            if (obj instanceof SharedUserSetting) {
5761                final SharedUserSetting sus = (SharedUserSetting) obj;
5762                final Iterator<PackageSetting> it = sus.packages.iterator();
5763                while (it.hasNext()) {
5764                    if (it.next().isPrivileged()) {
5765                        return true;
5766                    }
5767                }
5768            } else if (obj instanceof PackageSetting) {
5769                final PackageSetting ps = (PackageSetting) obj;
5770                return ps.isPrivileged();
5771            }
5772        }
5773        return false;
5774    }
5775
5776    @Override
5777    public String[] getAppOpPermissionPackages(String permissionName) {
5778        synchronized (mPackages) {
5779            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5780            if (pkgs == null) {
5781                return null;
5782            }
5783            return pkgs.toArray(new String[pkgs.size()]);
5784        }
5785    }
5786
5787    @Override
5788    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5789            int flags, int userId) {
5790        return resolveIntentInternal(
5791                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5792    }
5793
5794    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5795            int flags, int userId, boolean resolveForStart) {
5796        try {
5797            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5798
5799            if (!sUserManager.exists(userId)) return null;
5800            final int callingUid = Binder.getCallingUid();
5801            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5802            enforceCrossUserPermission(callingUid, userId,
5803                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5804
5805            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5806            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5807                    flags, userId, resolveForStart);
5808            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5809
5810            final ResolveInfo bestChoice =
5811                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5812            return bestChoice;
5813        } finally {
5814            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5815        }
5816    }
5817
5818    @Override
5819    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5820        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5821            throw new SecurityException(
5822                    "findPersistentPreferredActivity can only be run by the system");
5823        }
5824        if (!sUserManager.exists(userId)) {
5825            return null;
5826        }
5827        final int callingUid = Binder.getCallingUid();
5828        intent = updateIntentForResolve(intent);
5829        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5830        final int flags = updateFlagsForResolve(
5831                0, userId, intent, callingUid, false /*includeInstantApps*/);
5832        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5833                userId);
5834        synchronized (mPackages) {
5835            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5836                    userId);
5837        }
5838    }
5839
5840    @Override
5841    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5842            IntentFilter filter, int match, ComponentName activity) {
5843        final int userId = UserHandle.getCallingUserId();
5844        if (DEBUG_PREFERRED) {
5845            Log.v(TAG, "setLastChosenActivity intent=" + intent
5846                + " resolvedType=" + resolvedType
5847                + " flags=" + flags
5848                + " filter=" + filter
5849                + " match=" + match
5850                + " activity=" + activity);
5851            filter.dump(new PrintStreamPrinter(System.out), "    ");
5852        }
5853        intent.setComponent(null);
5854        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5855                userId);
5856        // Find any earlier preferred or last chosen entries and nuke them
5857        findPreferredActivity(intent, resolvedType,
5858                flags, query, 0, false, true, false, userId);
5859        // Add the new activity as the last chosen for this filter
5860        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5861                "Setting last chosen");
5862    }
5863
5864    @Override
5865    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5866        final int userId = UserHandle.getCallingUserId();
5867        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5868        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5869                userId);
5870        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5871                false, false, false, userId);
5872    }
5873
5874    /**
5875     * Returns whether or not instant apps have been disabled remotely.
5876     */
5877    private boolean isEphemeralDisabled() {
5878        return mEphemeralAppsDisabled;
5879    }
5880
5881    private boolean isInstantAppAllowed(
5882            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5883            boolean skipPackageCheck) {
5884        if (mInstantAppResolverConnection == null) {
5885            return false;
5886        }
5887        if (mInstantAppInstallerActivity == null) {
5888            return false;
5889        }
5890        if (intent.getComponent() != null) {
5891            return false;
5892        }
5893        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5894            return false;
5895        }
5896        if (!skipPackageCheck && intent.getPackage() != null) {
5897            return false;
5898        }
5899        final boolean isWebUri = hasWebURI(intent);
5900        if (!isWebUri || intent.getData().getHost() == null) {
5901            return false;
5902        }
5903        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5904        // Or if there's already an ephemeral app installed that handles the action
5905        synchronized (mPackages) {
5906            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5907            for (int n = 0; n < count; n++) {
5908                final ResolveInfo info = resolvedActivities.get(n);
5909                final String packageName = info.activityInfo.packageName;
5910                final PackageSetting ps = mSettings.mPackages.get(packageName);
5911                if (ps != null) {
5912                    // only check domain verification status if the app is not a browser
5913                    if (!info.handleAllWebDataURI) {
5914                        // Try to get the status from User settings first
5915                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5916                        final int status = (int) (packedStatus >> 32);
5917                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5918                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5919                            if (DEBUG_EPHEMERAL) {
5920                                Slog.v(TAG, "DENY instant app;"
5921                                    + " pkg: " + packageName + ", status: " + status);
5922                            }
5923                            return false;
5924                        }
5925                    }
5926                    if (ps.getInstantApp(userId)) {
5927                        if (DEBUG_EPHEMERAL) {
5928                            Slog.v(TAG, "DENY instant app installed;"
5929                                    + " pkg: " + packageName);
5930                        }
5931                        return false;
5932                    }
5933                }
5934            }
5935        }
5936        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5937        return true;
5938    }
5939
5940    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5941            Intent origIntent, String resolvedType, String callingPackage,
5942            Bundle verificationBundle, int userId) {
5943        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5944                new InstantAppRequest(responseObj, origIntent, resolvedType,
5945                        callingPackage, userId, verificationBundle));
5946        mHandler.sendMessage(msg);
5947    }
5948
5949    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5950            int flags, List<ResolveInfo> query, int userId) {
5951        if (query != null) {
5952            final int N = query.size();
5953            if (N == 1) {
5954                return query.get(0);
5955            } else if (N > 1) {
5956                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5957                // If there is more than one activity with the same priority,
5958                // then let the user decide between them.
5959                ResolveInfo r0 = query.get(0);
5960                ResolveInfo r1 = query.get(1);
5961                if (DEBUG_INTENT_MATCHING || debug) {
5962                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5963                            + r1.activityInfo.name + "=" + r1.priority);
5964                }
5965                // If the first activity has a higher priority, or a different
5966                // default, then it is always desirable to pick it.
5967                if (r0.priority != r1.priority
5968                        || r0.preferredOrder != r1.preferredOrder
5969                        || r0.isDefault != r1.isDefault) {
5970                    return query.get(0);
5971                }
5972                // If we have saved a preference for a preferred activity for
5973                // this Intent, use that.
5974                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5975                        flags, query, r0.priority, true, false, debug, userId);
5976                if (ri != null) {
5977                    return ri;
5978                }
5979                // If we have an ephemeral app, use it
5980                for (int i = 0; i < N; i++) {
5981                    ri = query.get(i);
5982                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5983                        final String packageName = ri.activityInfo.packageName;
5984                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5985                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5986                        final int status = (int)(packedStatus >> 32);
5987                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5988                            return ri;
5989                        }
5990                    }
5991                }
5992                ri = new ResolveInfo(mResolveInfo);
5993                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5994                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5995                // If all of the options come from the same package, show the application's
5996                // label and icon instead of the generic resolver's.
5997                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5998                // and then throw away the ResolveInfo itself, meaning that the caller loses
5999                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6000                // a fallback for this case; we only set the target package's resources on
6001                // the ResolveInfo, not the ActivityInfo.
6002                final String intentPackage = intent.getPackage();
6003                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6004                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6005                    ri.resolvePackageName = intentPackage;
6006                    if (userNeedsBadging(userId)) {
6007                        ri.noResourceId = true;
6008                    } else {
6009                        ri.icon = appi.icon;
6010                    }
6011                    ri.iconResourceId = appi.icon;
6012                    ri.labelRes = appi.labelRes;
6013                }
6014                ri.activityInfo.applicationInfo = new ApplicationInfo(
6015                        ri.activityInfo.applicationInfo);
6016                if (userId != 0) {
6017                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6018                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6019                }
6020                // Make sure that the resolver is displayable in car mode
6021                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6022                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6023                return ri;
6024            }
6025        }
6026        return null;
6027    }
6028
6029    /**
6030     * Return true if the given list is not empty and all of its contents have
6031     * an activityInfo with the given package name.
6032     */
6033    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6034        if (ArrayUtils.isEmpty(list)) {
6035            return false;
6036        }
6037        for (int i = 0, N = list.size(); i < N; i++) {
6038            final ResolveInfo ri = list.get(i);
6039            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6040            if (ai == null || !packageName.equals(ai.packageName)) {
6041                return false;
6042            }
6043        }
6044        return true;
6045    }
6046
6047    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6048            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6049        final int N = query.size();
6050        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6051                .get(userId);
6052        // Get the list of persistent preferred activities that handle the intent
6053        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6054        List<PersistentPreferredActivity> pprefs = ppir != null
6055                ? ppir.queryIntent(intent, resolvedType,
6056                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6057                        userId)
6058                : null;
6059        if (pprefs != null && pprefs.size() > 0) {
6060            final int M = pprefs.size();
6061            for (int i=0; i<M; i++) {
6062                final PersistentPreferredActivity ppa = pprefs.get(i);
6063                if (DEBUG_PREFERRED || debug) {
6064                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6065                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6066                            + "\n  component=" + ppa.mComponent);
6067                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6068                }
6069                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6070                        flags | MATCH_DISABLED_COMPONENTS, userId);
6071                if (DEBUG_PREFERRED || debug) {
6072                    Slog.v(TAG, "Found persistent preferred activity:");
6073                    if (ai != null) {
6074                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6075                    } else {
6076                        Slog.v(TAG, "  null");
6077                    }
6078                }
6079                if (ai == null) {
6080                    // This previously registered persistent preferred activity
6081                    // component is no longer known. Ignore it and do NOT remove it.
6082                    continue;
6083                }
6084                for (int j=0; j<N; j++) {
6085                    final ResolveInfo ri = query.get(j);
6086                    if (!ri.activityInfo.applicationInfo.packageName
6087                            .equals(ai.applicationInfo.packageName)) {
6088                        continue;
6089                    }
6090                    if (!ri.activityInfo.name.equals(ai.name)) {
6091                        continue;
6092                    }
6093                    //  Found a persistent preference that can handle the intent.
6094                    if (DEBUG_PREFERRED || debug) {
6095                        Slog.v(TAG, "Returning persistent preferred activity: " +
6096                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6097                    }
6098                    return ri;
6099                }
6100            }
6101        }
6102        return null;
6103    }
6104
6105    // TODO: handle preferred activities missing while user has amnesia
6106    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6107            List<ResolveInfo> query, int priority, boolean always,
6108            boolean removeMatches, boolean debug, int userId) {
6109        if (!sUserManager.exists(userId)) return null;
6110        final int callingUid = Binder.getCallingUid();
6111        flags = updateFlagsForResolve(
6112                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6113        intent = updateIntentForResolve(intent);
6114        // writer
6115        synchronized (mPackages) {
6116            // Try to find a matching persistent preferred activity.
6117            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6118                    debug, userId);
6119
6120            // If a persistent preferred activity matched, use it.
6121            if (pri != null) {
6122                return pri;
6123            }
6124
6125            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6126            // Get the list of preferred activities that handle the intent
6127            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6128            List<PreferredActivity> prefs = pir != null
6129                    ? pir.queryIntent(intent, resolvedType,
6130                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6131                            userId)
6132                    : null;
6133            if (prefs != null && prefs.size() > 0) {
6134                boolean changed = false;
6135                try {
6136                    // First figure out how good the original match set is.
6137                    // We will only allow preferred activities that came
6138                    // from the same match quality.
6139                    int match = 0;
6140
6141                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6142
6143                    final int N = query.size();
6144                    for (int j=0; j<N; j++) {
6145                        final ResolveInfo ri = query.get(j);
6146                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6147                                + ": 0x" + Integer.toHexString(match));
6148                        if (ri.match > match) {
6149                            match = ri.match;
6150                        }
6151                    }
6152
6153                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6154                            + Integer.toHexString(match));
6155
6156                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6157                    final int M = prefs.size();
6158                    for (int i=0; i<M; i++) {
6159                        final PreferredActivity pa = prefs.get(i);
6160                        if (DEBUG_PREFERRED || debug) {
6161                            Slog.v(TAG, "Checking PreferredActivity ds="
6162                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6163                                    + "\n  component=" + pa.mPref.mComponent);
6164                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6165                        }
6166                        if (pa.mPref.mMatch != match) {
6167                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6168                                    + Integer.toHexString(pa.mPref.mMatch));
6169                            continue;
6170                        }
6171                        // If it's not an "always" type preferred activity and that's what we're
6172                        // looking for, skip it.
6173                        if (always && !pa.mPref.mAlways) {
6174                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6175                            continue;
6176                        }
6177                        final ActivityInfo ai = getActivityInfo(
6178                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6179                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6180                                userId);
6181                        if (DEBUG_PREFERRED || debug) {
6182                            Slog.v(TAG, "Found preferred activity:");
6183                            if (ai != null) {
6184                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6185                            } else {
6186                                Slog.v(TAG, "  null");
6187                            }
6188                        }
6189                        if (ai == null) {
6190                            // This previously registered preferred activity
6191                            // component is no longer known.  Most likely an update
6192                            // to the app was installed and in the new version this
6193                            // component no longer exists.  Clean it up by removing
6194                            // it from the preferred activities list, and skip it.
6195                            Slog.w(TAG, "Removing dangling preferred activity: "
6196                                    + pa.mPref.mComponent);
6197                            pir.removeFilter(pa);
6198                            changed = true;
6199                            continue;
6200                        }
6201                        for (int j=0; j<N; j++) {
6202                            final ResolveInfo ri = query.get(j);
6203                            if (!ri.activityInfo.applicationInfo.packageName
6204                                    .equals(ai.applicationInfo.packageName)) {
6205                                continue;
6206                            }
6207                            if (!ri.activityInfo.name.equals(ai.name)) {
6208                                continue;
6209                            }
6210
6211                            if (removeMatches) {
6212                                pir.removeFilter(pa);
6213                                changed = true;
6214                                if (DEBUG_PREFERRED) {
6215                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6216                                }
6217                                break;
6218                            }
6219
6220                            // Okay we found a previously set preferred or last chosen app.
6221                            // If the result set is different from when this
6222                            // was created, we need to clear it and re-ask the
6223                            // user their preference, if we're looking for an "always" type entry.
6224                            if (always && !pa.mPref.sameSet(query)) {
6225                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6226                                        + intent + " type " + resolvedType);
6227                                if (DEBUG_PREFERRED) {
6228                                    Slog.v(TAG, "Removing preferred activity since set changed "
6229                                            + pa.mPref.mComponent);
6230                                }
6231                                pir.removeFilter(pa);
6232                                // Re-add the filter as a "last chosen" entry (!always)
6233                                PreferredActivity lastChosen = new PreferredActivity(
6234                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6235                                pir.addFilter(lastChosen);
6236                                changed = true;
6237                                return null;
6238                            }
6239
6240                            // Yay! Either the set matched or we're looking for the last chosen
6241                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6242                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6243                            return ri;
6244                        }
6245                    }
6246                } finally {
6247                    if (changed) {
6248                        if (DEBUG_PREFERRED) {
6249                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6250                        }
6251                        scheduleWritePackageRestrictionsLocked(userId);
6252                    }
6253                }
6254            }
6255        }
6256        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6257        return null;
6258    }
6259
6260    /*
6261     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6262     */
6263    @Override
6264    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6265            int targetUserId) {
6266        mContext.enforceCallingOrSelfPermission(
6267                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6268        List<CrossProfileIntentFilter> matches =
6269                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6270        if (matches != null) {
6271            int size = matches.size();
6272            for (int i = 0; i < size; i++) {
6273                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6274            }
6275        }
6276        if (hasWebURI(intent)) {
6277            // cross-profile app linking works only towards the parent.
6278            final int callingUid = Binder.getCallingUid();
6279            final UserInfo parent = getProfileParent(sourceUserId);
6280            synchronized(mPackages) {
6281                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6282                        false /*includeInstantApps*/);
6283                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6284                        intent, resolvedType, flags, sourceUserId, parent.id);
6285                return xpDomainInfo != null;
6286            }
6287        }
6288        return false;
6289    }
6290
6291    private UserInfo getProfileParent(int userId) {
6292        final long identity = Binder.clearCallingIdentity();
6293        try {
6294            return sUserManager.getProfileParent(userId);
6295        } finally {
6296            Binder.restoreCallingIdentity(identity);
6297        }
6298    }
6299
6300    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6301            String resolvedType, int userId) {
6302        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6303        if (resolver != null) {
6304            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6305        }
6306        return null;
6307    }
6308
6309    @Override
6310    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6311            String resolvedType, int flags, int userId) {
6312        try {
6313            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6314
6315            return new ParceledListSlice<>(
6316                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6317        } finally {
6318            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6319        }
6320    }
6321
6322    /**
6323     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6324     * instant, returns {@code null}.
6325     */
6326    private String getInstantAppPackageName(int callingUid) {
6327        // If the caller is an isolated app use the owner's uid for the lookup.
6328        if (Process.isIsolated(callingUid)) {
6329            callingUid = mIsolatedOwners.get(callingUid);
6330        }
6331        final int appId = UserHandle.getAppId(callingUid);
6332        synchronized (mPackages) {
6333            final Object obj = mSettings.getUserIdLPr(appId);
6334            if (obj instanceof PackageSetting) {
6335                final PackageSetting ps = (PackageSetting) obj;
6336                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6337                return isInstantApp ? ps.pkg.packageName : null;
6338            }
6339        }
6340        return null;
6341    }
6342
6343    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6344            String resolvedType, int flags, int userId) {
6345        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6346    }
6347
6348    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6349            String resolvedType, int flags, int userId, boolean resolveForStart) {
6350        if (!sUserManager.exists(userId)) return Collections.emptyList();
6351        final int callingUid = Binder.getCallingUid();
6352        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6353        enforceCrossUserPermission(callingUid, userId,
6354                false /* requireFullPermission */, false /* checkShell */,
6355                "query intent activities");
6356        final String pkgName = intent.getPackage();
6357        ComponentName comp = intent.getComponent();
6358        if (comp == null) {
6359            if (intent.getSelector() != null) {
6360                intent = intent.getSelector();
6361                comp = intent.getComponent();
6362            }
6363        }
6364
6365        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
6366                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6367        if (comp != null) {
6368            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6369            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6370            if (ai != null) {
6371                // When specifying an explicit component, we prevent the activity from being
6372                // used when either 1) the calling package is normal and the activity is within
6373                // an ephemeral application or 2) the calling package is ephemeral and the
6374                // activity is not visible to ephemeral applications.
6375                final boolean matchInstantApp =
6376                        (flags & PackageManager.MATCH_INSTANT) != 0;
6377                final boolean matchVisibleToInstantAppOnly =
6378                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6379                final boolean matchExplicitlyVisibleOnly =
6380                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6381                final boolean isCallerInstantApp =
6382                        instantAppPkgName != null;
6383                final boolean isTargetSameInstantApp =
6384                        comp.getPackageName().equals(instantAppPkgName);
6385                final boolean isTargetInstantApp =
6386                        (ai.applicationInfo.privateFlags
6387                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6388                final boolean isTargetVisibleToInstantApp =
6389                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6390                final boolean isTargetExplicitlyVisibleToInstantApp =
6391                        isTargetVisibleToInstantApp
6392                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6393                final boolean isTargetHiddenFromInstantApp =
6394                        !isTargetVisibleToInstantApp
6395                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6396                final boolean blockResolution =
6397                        !isTargetSameInstantApp
6398                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6399                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6400                                        && isTargetHiddenFromInstantApp));
6401                if (!blockResolution) {
6402                    final ResolveInfo ri = new ResolveInfo();
6403                    ri.activityInfo = ai;
6404                    list.add(ri);
6405                }
6406            }
6407            return applyPostResolutionFilter(list, instantAppPkgName);
6408        }
6409
6410        // reader
6411        boolean sortResult = false;
6412        boolean addEphemeral = false;
6413        List<ResolveInfo> result;
6414        final boolean ephemeralDisabled = isEphemeralDisabled();
6415        synchronized (mPackages) {
6416            if (pkgName == null) {
6417                List<CrossProfileIntentFilter> matchingFilters =
6418                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6419                // Check for results that need to skip the current profile.
6420                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6421                        resolvedType, flags, userId);
6422                if (xpResolveInfo != null) {
6423                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6424                    xpResult.add(xpResolveInfo);
6425                    return applyPostResolutionFilter(
6426                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6427                }
6428
6429                // Check for results in the current profile.
6430                result = filterIfNotSystemUser(mActivities.queryIntent(
6431                        intent, resolvedType, flags, userId), userId);
6432                addEphemeral = !ephemeralDisabled
6433                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6434                // Check for cross profile results.
6435                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6436                xpResolveInfo = queryCrossProfileIntents(
6437                        matchingFilters, intent, resolvedType, flags, userId,
6438                        hasNonNegativePriorityResult);
6439                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6440                    boolean isVisibleToUser = filterIfNotSystemUser(
6441                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6442                    if (isVisibleToUser) {
6443                        result.add(xpResolveInfo);
6444                        sortResult = true;
6445                    }
6446                }
6447                if (hasWebURI(intent)) {
6448                    CrossProfileDomainInfo xpDomainInfo = null;
6449                    final UserInfo parent = getProfileParent(userId);
6450                    if (parent != null) {
6451                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6452                                flags, userId, parent.id);
6453                    }
6454                    if (xpDomainInfo != null) {
6455                        if (xpResolveInfo != null) {
6456                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6457                            // in the result.
6458                            result.remove(xpResolveInfo);
6459                        }
6460                        if (result.size() == 0 && !addEphemeral) {
6461                            // No result in current profile, but found candidate in parent user.
6462                            // And we are not going to add emphemeral app, so we can return the
6463                            // result straight away.
6464                            result.add(xpDomainInfo.resolveInfo);
6465                            return applyPostResolutionFilter(result, instantAppPkgName);
6466                        }
6467                    } else if (result.size() <= 1 && !addEphemeral) {
6468                        // No result in parent user and <= 1 result in current profile, and we
6469                        // are not going to add emphemeral app, so we can return the result without
6470                        // further processing.
6471                        return applyPostResolutionFilter(result, instantAppPkgName);
6472                    }
6473                    // We have more than one candidate (combining results from current and parent
6474                    // profile), so we need filtering and sorting.
6475                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6476                            intent, flags, result, xpDomainInfo, userId);
6477                    sortResult = true;
6478                }
6479            } else {
6480                final PackageParser.Package pkg = mPackages.get(pkgName);
6481                if (pkg != null) {
6482                    return applyPostResolutionFilter(filterIfNotSystemUser(
6483                            mActivities.queryIntentForPackage(
6484                                    intent, resolvedType, flags, pkg.activities, userId),
6485                            userId), instantAppPkgName);
6486                } else {
6487                    // the caller wants to resolve for a particular package; however, there
6488                    // were no installed results, so, try to find an ephemeral result
6489                    addEphemeral = !ephemeralDisabled
6490                            && isInstantAppAllowed(
6491                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6492                    result = new ArrayList<ResolveInfo>();
6493                }
6494            }
6495        }
6496        if (addEphemeral) {
6497            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6498        }
6499        if (sortResult) {
6500            Collections.sort(result, mResolvePrioritySorter);
6501        }
6502        return applyPostResolutionFilter(result, instantAppPkgName);
6503    }
6504
6505    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6506            String resolvedType, int flags, int userId) {
6507        // first, check to see if we've got an instant app already installed
6508        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6509        ResolveInfo localInstantApp = null;
6510        boolean blockResolution = false;
6511        if (!alreadyResolvedLocally) {
6512            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6513                    flags
6514                        | PackageManager.GET_RESOLVED_FILTER
6515                        | PackageManager.MATCH_INSTANT
6516                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6517                    userId);
6518            for (int i = instantApps.size() - 1; i >= 0; --i) {
6519                final ResolveInfo info = instantApps.get(i);
6520                final String packageName = info.activityInfo.packageName;
6521                final PackageSetting ps = mSettings.mPackages.get(packageName);
6522                if (ps.getInstantApp(userId)) {
6523                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6524                    final int status = (int)(packedStatus >> 32);
6525                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6526                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6527                        // there's a local instant application installed, but, the user has
6528                        // chosen to never use it; skip resolution and don't acknowledge
6529                        // an instant application is even available
6530                        if (DEBUG_EPHEMERAL) {
6531                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6532                        }
6533                        blockResolution = true;
6534                        break;
6535                    } else {
6536                        // we have a locally installed instant application; skip resolution
6537                        // but acknowledge there's an instant application available
6538                        if (DEBUG_EPHEMERAL) {
6539                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6540                        }
6541                        localInstantApp = info;
6542                        break;
6543                    }
6544                }
6545            }
6546        }
6547        // no app installed, let's see if one's available
6548        AuxiliaryResolveInfo auxiliaryResponse = null;
6549        if (!blockResolution) {
6550            if (localInstantApp == null) {
6551                // we don't have an instant app locally, resolve externally
6552                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6553                final InstantAppRequest requestObject = new InstantAppRequest(
6554                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6555                        null /*callingPackage*/, userId, null /*verificationBundle*/);
6556                auxiliaryResponse =
6557                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6558                                mContext, mInstantAppResolverConnection, requestObject);
6559                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6560            } else {
6561                // we have an instant application locally, but, we can't admit that since
6562                // callers shouldn't be able to determine prior browsing. create a dummy
6563                // auxiliary response so the downstream code behaves as if there's an
6564                // instant application available externally. when it comes time to start
6565                // the instant application, we'll do the right thing.
6566                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6567                auxiliaryResponse = new AuxiliaryResolveInfo(
6568                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
6569            }
6570        }
6571        if (auxiliaryResponse != null) {
6572            if (DEBUG_EPHEMERAL) {
6573                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6574            }
6575            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6576            final PackageSetting ps =
6577                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6578            if (ps != null) {
6579                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6580                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6581                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6582                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6583                // make sure this resolver is the default
6584                ephemeralInstaller.isDefault = true;
6585                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6586                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6587                // add a non-generic filter
6588                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6589                ephemeralInstaller.filter.addDataPath(
6590                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6591                ephemeralInstaller.isInstantAppAvailable = true;
6592                result.add(ephemeralInstaller);
6593            }
6594        }
6595        return result;
6596    }
6597
6598    private static class CrossProfileDomainInfo {
6599        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6600        ResolveInfo resolveInfo;
6601        /* Best domain verification status of the activities found in the other profile */
6602        int bestDomainVerificationStatus;
6603    }
6604
6605    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6606            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6607        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6608                sourceUserId)) {
6609            return null;
6610        }
6611        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6612                resolvedType, flags, parentUserId);
6613
6614        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6615            return null;
6616        }
6617        CrossProfileDomainInfo result = null;
6618        int size = resultTargetUser.size();
6619        for (int i = 0; i < size; i++) {
6620            ResolveInfo riTargetUser = resultTargetUser.get(i);
6621            // Intent filter verification is only for filters that specify a host. So don't return
6622            // those that handle all web uris.
6623            if (riTargetUser.handleAllWebDataURI) {
6624                continue;
6625            }
6626            String packageName = riTargetUser.activityInfo.packageName;
6627            PackageSetting ps = mSettings.mPackages.get(packageName);
6628            if (ps == null) {
6629                continue;
6630            }
6631            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6632            int status = (int)(verificationState >> 32);
6633            if (result == null) {
6634                result = new CrossProfileDomainInfo();
6635                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6636                        sourceUserId, parentUserId);
6637                result.bestDomainVerificationStatus = status;
6638            } else {
6639                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6640                        result.bestDomainVerificationStatus);
6641            }
6642        }
6643        // Don't consider matches with status NEVER across profiles.
6644        if (result != null && result.bestDomainVerificationStatus
6645                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6646            return null;
6647        }
6648        return result;
6649    }
6650
6651    /**
6652     * Verification statuses are ordered from the worse to the best, except for
6653     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6654     */
6655    private int bestDomainVerificationStatus(int status1, int status2) {
6656        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6657            return status2;
6658        }
6659        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6660            return status1;
6661        }
6662        return (int) MathUtils.max(status1, status2);
6663    }
6664
6665    private boolean isUserEnabled(int userId) {
6666        long callingId = Binder.clearCallingIdentity();
6667        try {
6668            UserInfo userInfo = sUserManager.getUserInfo(userId);
6669            return userInfo != null && userInfo.isEnabled();
6670        } finally {
6671            Binder.restoreCallingIdentity(callingId);
6672        }
6673    }
6674
6675    /**
6676     * Filter out activities with systemUserOnly flag set, when current user is not System.
6677     *
6678     * @return filtered list
6679     */
6680    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6681        if (userId == UserHandle.USER_SYSTEM) {
6682            return resolveInfos;
6683        }
6684        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6685            ResolveInfo info = resolveInfos.get(i);
6686            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6687                resolveInfos.remove(i);
6688            }
6689        }
6690        return resolveInfos;
6691    }
6692
6693    /**
6694     * Filters out ephemeral activities.
6695     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6696     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6697     *
6698     * @param resolveInfos The pre-filtered list of resolved activities
6699     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6700     *          is performed.
6701     * @return A filtered list of resolved activities.
6702     */
6703    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6704            String ephemeralPkgName) {
6705        // TODO: When adding on-demand split support for non-instant apps, remove this check
6706        // and always apply post filtering
6707        if (ephemeralPkgName == null) {
6708            return resolveInfos;
6709        }
6710        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6711            final ResolveInfo info = resolveInfos.get(i);
6712            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6713            // allow activities that are defined in the provided package
6714            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6715                if (info.activityInfo.splitName != null
6716                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6717                                info.activityInfo.splitName)) {
6718                    // requested activity is defined in a split that hasn't been installed yet.
6719                    // add the installer to the resolve list
6720                    if (DEBUG_EPHEMERAL) {
6721                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6722                    }
6723                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6724                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6725                            info.activityInfo.packageName, info.activityInfo.splitName,
6726                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
6727                    // make sure this resolver is the default
6728                    installerInfo.isDefault = true;
6729                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6730                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6731                    // add a non-generic filter
6732                    installerInfo.filter = new IntentFilter();
6733                    // load resources from the correct package
6734                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6735                    resolveInfos.set(i, installerInfo);
6736                }
6737                continue;
6738            }
6739            // allow activities that have been explicitly exposed to ephemeral apps
6740            if (!isEphemeralApp
6741                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6742                continue;
6743            }
6744            resolveInfos.remove(i);
6745        }
6746        return resolveInfos;
6747    }
6748
6749    /**
6750     * @param resolveInfos list of resolve infos in descending priority order
6751     * @return if the list contains a resolve info with non-negative priority
6752     */
6753    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6754        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6755    }
6756
6757    private static boolean hasWebURI(Intent intent) {
6758        if (intent.getData() == null) {
6759            return false;
6760        }
6761        final String scheme = intent.getScheme();
6762        if (TextUtils.isEmpty(scheme)) {
6763            return false;
6764        }
6765        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6766    }
6767
6768    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6769            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6770            int userId) {
6771        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6772
6773        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6774            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6775                    candidates.size());
6776        }
6777
6778        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6779        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6780        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6781        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6782        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6783        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6784
6785        synchronized (mPackages) {
6786            final int count = candidates.size();
6787            // First, try to use linked apps. Partition the candidates into four lists:
6788            // one for the final results, one for the "do not use ever", one for "undefined status"
6789            // and finally one for "browser app type".
6790            for (int n=0; n<count; n++) {
6791                ResolveInfo info = candidates.get(n);
6792                String packageName = info.activityInfo.packageName;
6793                PackageSetting ps = mSettings.mPackages.get(packageName);
6794                if (ps != null) {
6795                    // Add to the special match all list (Browser use case)
6796                    if (info.handleAllWebDataURI) {
6797                        matchAllList.add(info);
6798                        continue;
6799                    }
6800                    // Try to get the status from User settings first
6801                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6802                    int status = (int)(packedStatus >> 32);
6803                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6804                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6805                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6806                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6807                                    + " : linkgen=" + linkGeneration);
6808                        }
6809                        // Use link-enabled generation as preferredOrder, i.e.
6810                        // prefer newly-enabled over earlier-enabled.
6811                        info.preferredOrder = linkGeneration;
6812                        alwaysList.add(info);
6813                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6814                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6815                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6816                        }
6817                        neverList.add(info);
6818                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6819                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6820                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6821                        }
6822                        alwaysAskList.add(info);
6823                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6824                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6825                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6826                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6827                        }
6828                        undefinedList.add(info);
6829                    }
6830                }
6831            }
6832
6833            // We'll want to include browser possibilities in a few cases
6834            boolean includeBrowser = false;
6835
6836            // First try to add the "always" resolution(s) for the current user, if any
6837            if (alwaysList.size() > 0) {
6838                result.addAll(alwaysList);
6839            } else {
6840                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6841                result.addAll(undefinedList);
6842                // Maybe add one for the other profile.
6843                if (xpDomainInfo != null && (
6844                        xpDomainInfo.bestDomainVerificationStatus
6845                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6846                    result.add(xpDomainInfo.resolveInfo);
6847                }
6848                includeBrowser = true;
6849            }
6850
6851            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6852            // If there were 'always' entries their preferred order has been set, so we also
6853            // back that off to make the alternatives equivalent
6854            if (alwaysAskList.size() > 0) {
6855                for (ResolveInfo i : result) {
6856                    i.preferredOrder = 0;
6857                }
6858                result.addAll(alwaysAskList);
6859                includeBrowser = true;
6860            }
6861
6862            if (includeBrowser) {
6863                // Also add browsers (all of them or only the default one)
6864                if (DEBUG_DOMAIN_VERIFICATION) {
6865                    Slog.v(TAG, "   ...including browsers in candidate set");
6866                }
6867                if ((matchFlags & MATCH_ALL) != 0) {
6868                    result.addAll(matchAllList);
6869                } else {
6870                    // Browser/generic handling case.  If there's a default browser, go straight
6871                    // to that (but only if there is no other higher-priority match).
6872                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6873                    int maxMatchPrio = 0;
6874                    ResolveInfo defaultBrowserMatch = null;
6875                    final int numCandidates = matchAllList.size();
6876                    for (int n = 0; n < numCandidates; n++) {
6877                        ResolveInfo info = matchAllList.get(n);
6878                        // track the highest overall match priority...
6879                        if (info.priority > maxMatchPrio) {
6880                            maxMatchPrio = info.priority;
6881                        }
6882                        // ...and the highest-priority default browser match
6883                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6884                            if (defaultBrowserMatch == null
6885                                    || (defaultBrowserMatch.priority < info.priority)) {
6886                                if (debug) {
6887                                    Slog.v(TAG, "Considering default browser match " + info);
6888                                }
6889                                defaultBrowserMatch = info;
6890                            }
6891                        }
6892                    }
6893                    if (defaultBrowserMatch != null
6894                            && defaultBrowserMatch.priority >= maxMatchPrio
6895                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6896                    {
6897                        if (debug) {
6898                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6899                        }
6900                        result.add(defaultBrowserMatch);
6901                    } else {
6902                        result.addAll(matchAllList);
6903                    }
6904                }
6905
6906                // If there is nothing selected, add all candidates and remove the ones that the user
6907                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6908                if (result.size() == 0) {
6909                    result.addAll(candidates);
6910                    result.removeAll(neverList);
6911                }
6912            }
6913        }
6914        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6915            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6916                    result.size());
6917            for (ResolveInfo info : result) {
6918                Slog.v(TAG, "  + " + info.activityInfo);
6919            }
6920        }
6921        return result;
6922    }
6923
6924    // Returns a packed value as a long:
6925    //
6926    // high 'int'-sized word: link status: undefined/ask/never/always.
6927    // low 'int'-sized word: relative priority among 'always' results.
6928    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6929        long result = ps.getDomainVerificationStatusForUser(userId);
6930        // if none available, get the master status
6931        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6932            if (ps.getIntentFilterVerificationInfo() != null) {
6933                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6934            }
6935        }
6936        return result;
6937    }
6938
6939    private ResolveInfo querySkipCurrentProfileIntents(
6940            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6941            int flags, int sourceUserId) {
6942        if (matchingFilters != null) {
6943            int size = matchingFilters.size();
6944            for (int i = 0; i < size; i ++) {
6945                CrossProfileIntentFilter filter = matchingFilters.get(i);
6946                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6947                    // Checking if there are activities in the target user that can handle the
6948                    // intent.
6949                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6950                            resolvedType, flags, sourceUserId);
6951                    if (resolveInfo != null) {
6952                        return resolveInfo;
6953                    }
6954                }
6955            }
6956        }
6957        return null;
6958    }
6959
6960    // Return matching ResolveInfo in target user if any.
6961    private ResolveInfo queryCrossProfileIntents(
6962            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6963            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6964        if (matchingFilters != null) {
6965            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6966            // match the same intent. For performance reasons, it is better not to
6967            // run queryIntent twice for the same userId
6968            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6969            int size = matchingFilters.size();
6970            for (int i = 0; i < size; i++) {
6971                CrossProfileIntentFilter filter = matchingFilters.get(i);
6972                int targetUserId = filter.getTargetUserId();
6973                boolean skipCurrentProfile =
6974                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6975                boolean skipCurrentProfileIfNoMatchFound =
6976                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6977                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6978                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6979                    // Checking if there are activities in the target user that can handle the
6980                    // intent.
6981                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6982                            resolvedType, flags, sourceUserId);
6983                    if (resolveInfo != null) return resolveInfo;
6984                    alreadyTriedUserIds.put(targetUserId, true);
6985                }
6986            }
6987        }
6988        return null;
6989    }
6990
6991    /**
6992     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6993     * will forward the intent to the filter's target user.
6994     * Otherwise, returns null.
6995     */
6996    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6997            String resolvedType, int flags, int sourceUserId) {
6998        int targetUserId = filter.getTargetUserId();
6999        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7000                resolvedType, flags, targetUserId);
7001        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7002            // If all the matches in the target profile are suspended, return null.
7003            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7004                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7005                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7006                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7007                            targetUserId);
7008                }
7009            }
7010        }
7011        return null;
7012    }
7013
7014    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7015            int sourceUserId, int targetUserId) {
7016        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7017        long ident = Binder.clearCallingIdentity();
7018        boolean targetIsProfile;
7019        try {
7020            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7021        } finally {
7022            Binder.restoreCallingIdentity(ident);
7023        }
7024        String className;
7025        if (targetIsProfile) {
7026            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7027        } else {
7028            className = FORWARD_INTENT_TO_PARENT;
7029        }
7030        ComponentName forwardingActivityComponentName = new ComponentName(
7031                mAndroidApplication.packageName, className);
7032        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7033                sourceUserId);
7034        if (!targetIsProfile) {
7035            forwardingActivityInfo.showUserIcon = targetUserId;
7036            forwardingResolveInfo.noResourceId = true;
7037        }
7038        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7039        forwardingResolveInfo.priority = 0;
7040        forwardingResolveInfo.preferredOrder = 0;
7041        forwardingResolveInfo.match = 0;
7042        forwardingResolveInfo.isDefault = true;
7043        forwardingResolveInfo.filter = filter;
7044        forwardingResolveInfo.targetUserId = targetUserId;
7045        return forwardingResolveInfo;
7046    }
7047
7048    @Override
7049    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7050            Intent[] specifics, String[] specificTypes, Intent intent,
7051            String resolvedType, int flags, int userId) {
7052        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7053                specificTypes, intent, resolvedType, flags, userId));
7054    }
7055
7056    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7057            Intent[] specifics, String[] specificTypes, Intent intent,
7058            String resolvedType, int flags, int userId) {
7059        if (!sUserManager.exists(userId)) return Collections.emptyList();
7060        final int callingUid = Binder.getCallingUid();
7061        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7062                false /*includeInstantApps*/);
7063        enforceCrossUserPermission(callingUid, userId,
7064                false /*requireFullPermission*/, false /*checkShell*/,
7065                "query intent activity options");
7066        final String resultsAction = intent.getAction();
7067
7068        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7069                | PackageManager.GET_RESOLVED_FILTER, userId);
7070
7071        if (DEBUG_INTENT_MATCHING) {
7072            Log.v(TAG, "Query " + intent + ": " + results);
7073        }
7074
7075        int specificsPos = 0;
7076        int N;
7077
7078        // todo: note that the algorithm used here is O(N^2).  This
7079        // isn't a problem in our current environment, but if we start running
7080        // into situations where we have more than 5 or 10 matches then this
7081        // should probably be changed to something smarter...
7082
7083        // First we go through and resolve each of the specific items
7084        // that were supplied, taking care of removing any corresponding
7085        // duplicate items in the generic resolve list.
7086        if (specifics != null) {
7087            for (int i=0; i<specifics.length; i++) {
7088                final Intent sintent = specifics[i];
7089                if (sintent == null) {
7090                    continue;
7091                }
7092
7093                if (DEBUG_INTENT_MATCHING) {
7094                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7095                }
7096
7097                String action = sintent.getAction();
7098                if (resultsAction != null && resultsAction.equals(action)) {
7099                    // If this action was explicitly requested, then don't
7100                    // remove things that have it.
7101                    action = null;
7102                }
7103
7104                ResolveInfo ri = null;
7105                ActivityInfo ai = null;
7106
7107                ComponentName comp = sintent.getComponent();
7108                if (comp == null) {
7109                    ri = resolveIntent(
7110                        sintent,
7111                        specificTypes != null ? specificTypes[i] : null,
7112                            flags, userId);
7113                    if (ri == null) {
7114                        continue;
7115                    }
7116                    if (ri == mResolveInfo) {
7117                        // ACK!  Must do something better with this.
7118                    }
7119                    ai = ri.activityInfo;
7120                    comp = new ComponentName(ai.applicationInfo.packageName,
7121                            ai.name);
7122                } else {
7123                    ai = getActivityInfo(comp, flags, userId);
7124                    if (ai == null) {
7125                        continue;
7126                    }
7127                }
7128
7129                // Look for any generic query activities that are duplicates
7130                // of this specific one, and remove them from the results.
7131                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7132                N = results.size();
7133                int j;
7134                for (j=specificsPos; j<N; j++) {
7135                    ResolveInfo sri = results.get(j);
7136                    if ((sri.activityInfo.name.equals(comp.getClassName())
7137                            && sri.activityInfo.applicationInfo.packageName.equals(
7138                                    comp.getPackageName()))
7139                        || (action != null && sri.filter.matchAction(action))) {
7140                        results.remove(j);
7141                        if (DEBUG_INTENT_MATCHING) Log.v(
7142                            TAG, "Removing duplicate item from " + j
7143                            + " due to specific " + specificsPos);
7144                        if (ri == null) {
7145                            ri = sri;
7146                        }
7147                        j--;
7148                        N--;
7149                    }
7150                }
7151
7152                // Add this specific item to its proper place.
7153                if (ri == null) {
7154                    ri = new ResolveInfo();
7155                    ri.activityInfo = ai;
7156                }
7157                results.add(specificsPos, ri);
7158                ri.specificIndex = i;
7159                specificsPos++;
7160            }
7161        }
7162
7163        // Now we go through the remaining generic results and remove any
7164        // duplicate actions that are found here.
7165        N = results.size();
7166        for (int i=specificsPos; i<N-1; i++) {
7167            final ResolveInfo rii = results.get(i);
7168            if (rii.filter == null) {
7169                continue;
7170            }
7171
7172            // Iterate over all of the actions of this result's intent
7173            // filter...  typically this should be just one.
7174            final Iterator<String> it = rii.filter.actionsIterator();
7175            if (it == null) {
7176                continue;
7177            }
7178            while (it.hasNext()) {
7179                final String action = it.next();
7180                if (resultsAction != null && resultsAction.equals(action)) {
7181                    // If this action was explicitly requested, then don't
7182                    // remove things that have it.
7183                    continue;
7184                }
7185                for (int j=i+1; j<N; j++) {
7186                    final ResolveInfo rij = results.get(j);
7187                    if (rij.filter != null && rij.filter.hasAction(action)) {
7188                        results.remove(j);
7189                        if (DEBUG_INTENT_MATCHING) Log.v(
7190                            TAG, "Removing duplicate item from " + j
7191                            + " due to action " + action + " at " + i);
7192                        j--;
7193                        N--;
7194                    }
7195                }
7196            }
7197
7198            // If the caller didn't request filter information, drop it now
7199            // so we don't have to marshall/unmarshall it.
7200            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7201                rii.filter = null;
7202            }
7203        }
7204
7205        // Filter out the caller activity if so requested.
7206        if (caller != null) {
7207            N = results.size();
7208            for (int i=0; i<N; i++) {
7209                ActivityInfo ainfo = results.get(i).activityInfo;
7210                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7211                        && caller.getClassName().equals(ainfo.name)) {
7212                    results.remove(i);
7213                    break;
7214                }
7215            }
7216        }
7217
7218        // If the caller didn't request filter information,
7219        // drop them now so we don't have to
7220        // marshall/unmarshall it.
7221        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7222            N = results.size();
7223            for (int i=0; i<N; i++) {
7224                results.get(i).filter = null;
7225            }
7226        }
7227
7228        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7229        return results;
7230    }
7231
7232    @Override
7233    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7234            String resolvedType, int flags, int userId) {
7235        return new ParceledListSlice<>(
7236                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7237    }
7238
7239    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7240            String resolvedType, int flags, int userId) {
7241        if (!sUserManager.exists(userId)) return Collections.emptyList();
7242        final int callingUid = Binder.getCallingUid();
7243        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7244                false /*includeInstantApps*/);
7245        ComponentName comp = intent.getComponent();
7246        if (comp == null) {
7247            if (intent.getSelector() != null) {
7248                intent = intent.getSelector();
7249                comp = intent.getComponent();
7250            }
7251        }
7252        if (comp != null) {
7253            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7254            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7255            if (ai != null) {
7256                ResolveInfo ri = new ResolveInfo();
7257                ri.activityInfo = ai;
7258                list.add(ri);
7259            }
7260            return list;
7261        }
7262
7263        // reader
7264        synchronized (mPackages) {
7265            String pkgName = intent.getPackage();
7266            if (pkgName == null) {
7267                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7268            }
7269            final PackageParser.Package pkg = mPackages.get(pkgName);
7270            if (pkg != null) {
7271                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7272                        userId);
7273            }
7274            return Collections.emptyList();
7275        }
7276    }
7277
7278    @Override
7279    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7280        final int callingUid = Binder.getCallingUid();
7281        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7282    }
7283
7284    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7285            int userId, int callingUid) {
7286        if (!sUserManager.exists(userId)) return null;
7287        flags = updateFlagsForResolve(
7288                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7289        List<ResolveInfo> query = queryIntentServicesInternal(
7290                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7291        if (query != null) {
7292            if (query.size() >= 1) {
7293                // If there is more than one service with the same priority,
7294                // just arbitrarily pick the first one.
7295                return query.get(0);
7296            }
7297        }
7298        return null;
7299    }
7300
7301    @Override
7302    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7303            String resolvedType, int flags, int userId) {
7304        final int callingUid = Binder.getCallingUid();
7305        return new ParceledListSlice<>(queryIntentServicesInternal(
7306                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7307    }
7308
7309    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7310            String resolvedType, int flags, int userId, int callingUid,
7311            boolean includeInstantApps) {
7312        if (!sUserManager.exists(userId)) return Collections.emptyList();
7313        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7314        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7315        ComponentName comp = intent.getComponent();
7316        if (comp == null) {
7317            if (intent.getSelector() != null) {
7318                intent = intent.getSelector();
7319                comp = intent.getComponent();
7320            }
7321        }
7322        if (comp != null) {
7323            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7324            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7325            if (si != null) {
7326                // When specifying an explicit component, we prevent the service from being
7327                // used when either 1) the service is in an instant application and the
7328                // caller is not the same instant application or 2) the calling package is
7329                // ephemeral and the activity is not visible to ephemeral applications.
7330                final boolean matchInstantApp =
7331                        (flags & PackageManager.MATCH_INSTANT) != 0;
7332                final boolean matchVisibleToInstantAppOnly =
7333                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7334                final boolean isCallerInstantApp =
7335                        instantAppPkgName != null;
7336                final boolean isTargetSameInstantApp =
7337                        comp.getPackageName().equals(instantAppPkgName);
7338                final boolean isTargetInstantApp =
7339                        (si.applicationInfo.privateFlags
7340                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7341                final boolean isTargetHiddenFromInstantApp =
7342                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7343                final boolean blockResolution =
7344                        !isTargetSameInstantApp
7345                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7346                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7347                                        && isTargetHiddenFromInstantApp));
7348                if (!blockResolution) {
7349                    final ResolveInfo ri = new ResolveInfo();
7350                    ri.serviceInfo = si;
7351                    list.add(ri);
7352                }
7353            }
7354            return list;
7355        }
7356
7357        // reader
7358        synchronized (mPackages) {
7359            String pkgName = intent.getPackage();
7360            if (pkgName == null) {
7361                return applyPostServiceResolutionFilter(
7362                        mServices.queryIntent(intent, resolvedType, flags, userId),
7363                        instantAppPkgName);
7364            }
7365            final PackageParser.Package pkg = mPackages.get(pkgName);
7366            if (pkg != null) {
7367                return applyPostServiceResolutionFilter(
7368                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7369                                userId),
7370                        instantAppPkgName);
7371            }
7372            return Collections.emptyList();
7373        }
7374    }
7375
7376    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7377            String instantAppPkgName) {
7378        // TODO: When adding on-demand split support for non-instant apps, remove this check
7379        // and always apply post filtering
7380        if (instantAppPkgName == null) {
7381            return resolveInfos;
7382        }
7383        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7384            final ResolveInfo info = resolveInfos.get(i);
7385            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7386            // allow services that are defined in the provided package
7387            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7388                if (info.serviceInfo.splitName != null
7389                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7390                                info.serviceInfo.splitName)) {
7391                    // requested service is defined in a split that hasn't been installed yet.
7392                    // add the installer to the resolve list
7393                    if (DEBUG_EPHEMERAL) {
7394                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7395                    }
7396                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7397                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7398                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7399                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7400                    // make sure this resolver is the default
7401                    installerInfo.isDefault = true;
7402                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7403                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7404                    // add a non-generic filter
7405                    installerInfo.filter = new IntentFilter();
7406                    // load resources from the correct package
7407                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7408                    resolveInfos.set(i, installerInfo);
7409                }
7410                continue;
7411            }
7412            // allow services that have been explicitly exposed to ephemeral apps
7413            if (!isEphemeralApp
7414                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7415                continue;
7416            }
7417            resolveInfos.remove(i);
7418        }
7419        return resolveInfos;
7420    }
7421
7422    @Override
7423    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7424            String resolvedType, int flags, int userId) {
7425        return new ParceledListSlice<>(
7426                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7427    }
7428
7429    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7430            Intent intent, String resolvedType, int flags, int userId) {
7431        if (!sUserManager.exists(userId)) return Collections.emptyList();
7432        final int callingUid = Binder.getCallingUid();
7433        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7434        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7435                false /*includeInstantApps*/);
7436        ComponentName comp = intent.getComponent();
7437        if (comp == null) {
7438            if (intent.getSelector() != null) {
7439                intent = intent.getSelector();
7440                comp = intent.getComponent();
7441            }
7442        }
7443        if (comp != null) {
7444            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7445            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7446            if (pi != null) {
7447                // When specifying an explicit component, we prevent the provider from being
7448                // used when either 1) the provider is in an instant application and the
7449                // caller is not the same instant application or 2) the calling package is an
7450                // instant application and the provider is not visible to instant applications.
7451                final boolean matchInstantApp =
7452                        (flags & PackageManager.MATCH_INSTANT) != 0;
7453                final boolean matchVisibleToInstantAppOnly =
7454                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7455                final boolean isCallerInstantApp =
7456                        instantAppPkgName != null;
7457                final boolean isTargetSameInstantApp =
7458                        comp.getPackageName().equals(instantAppPkgName);
7459                final boolean isTargetInstantApp =
7460                        (pi.applicationInfo.privateFlags
7461                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7462                final boolean isTargetHiddenFromInstantApp =
7463                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7464                final boolean blockResolution =
7465                        !isTargetSameInstantApp
7466                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7467                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7468                                        && isTargetHiddenFromInstantApp));
7469                if (!blockResolution) {
7470                    final ResolveInfo ri = new ResolveInfo();
7471                    ri.providerInfo = pi;
7472                    list.add(ri);
7473                }
7474            }
7475            return list;
7476        }
7477
7478        // reader
7479        synchronized (mPackages) {
7480            String pkgName = intent.getPackage();
7481            if (pkgName == null) {
7482                return applyPostContentProviderResolutionFilter(
7483                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7484                        instantAppPkgName);
7485            }
7486            final PackageParser.Package pkg = mPackages.get(pkgName);
7487            if (pkg != null) {
7488                return applyPostContentProviderResolutionFilter(
7489                        mProviders.queryIntentForPackage(
7490                        intent, resolvedType, flags, pkg.providers, userId),
7491                        instantAppPkgName);
7492            }
7493            return Collections.emptyList();
7494        }
7495    }
7496
7497    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7498            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7499        // TODO: When adding on-demand split support for non-instant applications, remove
7500        // this check and always apply post filtering
7501        if (instantAppPkgName == null) {
7502            return resolveInfos;
7503        }
7504        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7505            final ResolveInfo info = resolveInfos.get(i);
7506            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7507            // allow providers that are defined in the provided package
7508            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7509                if (info.providerInfo.splitName != null
7510                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7511                                info.providerInfo.splitName)) {
7512                    // requested provider is defined in a split that hasn't been installed yet.
7513                    // add the installer to the resolve list
7514                    if (DEBUG_EPHEMERAL) {
7515                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7516                    }
7517                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7518                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7519                            info.providerInfo.packageName, info.providerInfo.splitName,
7520                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
7521                    // make sure this resolver is the default
7522                    installerInfo.isDefault = true;
7523                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7524                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7525                    // add a non-generic filter
7526                    installerInfo.filter = new IntentFilter();
7527                    // load resources from the correct package
7528                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7529                    resolveInfos.set(i, installerInfo);
7530                }
7531                continue;
7532            }
7533            // allow providers that have been explicitly exposed to instant applications
7534            if (!isEphemeralApp
7535                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7536                continue;
7537            }
7538            resolveInfos.remove(i);
7539        }
7540        return resolveInfos;
7541    }
7542
7543    @Override
7544    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7545        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7546        flags = updateFlagsForPackage(flags, userId, null);
7547        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7548        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7549                true /* requireFullPermission */, false /* checkShell */,
7550                "get installed packages");
7551
7552        // writer
7553        synchronized (mPackages) {
7554            ArrayList<PackageInfo> list;
7555            if (listUninstalled) {
7556                list = new ArrayList<>(mSettings.mPackages.size());
7557                for (PackageSetting ps : mSettings.mPackages.values()) {
7558                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7559                        continue;
7560                    }
7561                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7562                    if (pi != null) {
7563                        list.add(pi);
7564                    }
7565                }
7566            } else {
7567                list = new ArrayList<>(mPackages.size());
7568                for (PackageParser.Package p : mPackages.values()) {
7569                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7570                            Binder.getCallingUid(), userId, flags)) {
7571                        continue;
7572                    }
7573                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7574                            p.mExtras, flags, userId);
7575                    if (pi != null) {
7576                        list.add(pi);
7577                    }
7578                }
7579            }
7580
7581            return new ParceledListSlice<>(list);
7582        }
7583    }
7584
7585    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7586            String[] permissions, boolean[] tmp, int flags, int userId) {
7587        int numMatch = 0;
7588        final PermissionsState permissionsState = ps.getPermissionsState();
7589        for (int i=0; i<permissions.length; i++) {
7590            final String permission = permissions[i];
7591            if (permissionsState.hasPermission(permission, userId)) {
7592                tmp[i] = true;
7593                numMatch++;
7594            } else {
7595                tmp[i] = false;
7596            }
7597        }
7598        if (numMatch == 0) {
7599            return;
7600        }
7601        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7602
7603        // The above might return null in cases of uninstalled apps or install-state
7604        // skew across users/profiles.
7605        if (pi != null) {
7606            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7607                if (numMatch == permissions.length) {
7608                    pi.requestedPermissions = permissions;
7609                } else {
7610                    pi.requestedPermissions = new String[numMatch];
7611                    numMatch = 0;
7612                    for (int i=0; i<permissions.length; i++) {
7613                        if (tmp[i]) {
7614                            pi.requestedPermissions[numMatch] = permissions[i];
7615                            numMatch++;
7616                        }
7617                    }
7618                }
7619            }
7620            list.add(pi);
7621        }
7622    }
7623
7624    @Override
7625    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7626            String[] permissions, int flags, int userId) {
7627        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7628        flags = updateFlagsForPackage(flags, userId, permissions);
7629        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7630                true /* requireFullPermission */, false /* checkShell */,
7631                "get packages holding permissions");
7632        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7633
7634        // writer
7635        synchronized (mPackages) {
7636            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7637            boolean[] tmpBools = new boolean[permissions.length];
7638            if (listUninstalled) {
7639                for (PackageSetting ps : mSettings.mPackages.values()) {
7640                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7641                            userId);
7642                }
7643            } else {
7644                for (PackageParser.Package pkg : mPackages.values()) {
7645                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7646                    if (ps != null) {
7647                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7648                                userId);
7649                    }
7650                }
7651            }
7652
7653            return new ParceledListSlice<PackageInfo>(list);
7654        }
7655    }
7656
7657    @Override
7658    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7659        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7660        flags = updateFlagsForApplication(flags, userId, null);
7661        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7662
7663        // writer
7664        synchronized (mPackages) {
7665            ArrayList<ApplicationInfo> list;
7666            if (listUninstalled) {
7667                list = new ArrayList<>(mSettings.mPackages.size());
7668                for (PackageSetting ps : mSettings.mPackages.values()) {
7669                    ApplicationInfo ai;
7670                    int effectiveFlags = flags;
7671                    if (ps.isSystem()) {
7672                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7673                    }
7674                    if (ps.pkg != null) {
7675                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7676                            continue;
7677                        }
7678                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7679                                ps.readUserState(userId), userId);
7680                        if (ai != null) {
7681                            rebaseEnabledOverlays(ai, userId);
7682                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7683                        }
7684                    } else {
7685                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7686                        // and already converts to externally visible package name
7687                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7688                                Binder.getCallingUid(), effectiveFlags, userId);
7689                    }
7690                    if (ai != null) {
7691                        list.add(ai);
7692                    }
7693                }
7694            } else {
7695                list = new ArrayList<>(mPackages.size());
7696                for (PackageParser.Package p : mPackages.values()) {
7697                    if (p.mExtras != null) {
7698                        PackageSetting ps = (PackageSetting) p.mExtras;
7699                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7700                            continue;
7701                        }
7702                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7703                                ps.readUserState(userId), userId);
7704                        if (ai != null) {
7705                            rebaseEnabledOverlays(ai, userId);
7706                            ai.packageName = resolveExternalPackageNameLPr(p);
7707                            list.add(ai);
7708                        }
7709                    }
7710                }
7711            }
7712
7713            return new ParceledListSlice<>(list);
7714        }
7715    }
7716
7717    @Override
7718    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7719        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7720            return null;
7721        }
7722
7723        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7724                "getEphemeralApplications");
7725        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7726                true /* requireFullPermission */, false /* checkShell */,
7727                "getEphemeralApplications");
7728        synchronized (mPackages) {
7729            List<InstantAppInfo> instantApps = mInstantAppRegistry
7730                    .getInstantAppsLPr(userId);
7731            if (instantApps != null) {
7732                return new ParceledListSlice<>(instantApps);
7733            }
7734        }
7735        return null;
7736    }
7737
7738    @Override
7739    public boolean isInstantApp(String packageName, int userId) {
7740        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7741                true /* requireFullPermission */, false /* checkShell */,
7742                "isInstantApp");
7743        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7744            return false;
7745        }
7746        int uid = Binder.getCallingUid();
7747        if (Process.isIsolated(uid)) {
7748            uid = mIsolatedOwners.get(uid);
7749        }
7750
7751        synchronized (mPackages) {
7752            final PackageSetting ps = mSettings.mPackages.get(packageName);
7753            PackageParser.Package pkg = mPackages.get(packageName);
7754            final boolean returnAllowed =
7755                    ps != null
7756                    && (isCallerSameApp(packageName, uid)
7757                            || mContext.checkCallingOrSelfPermission(
7758                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7759                                            == PERMISSION_GRANTED
7760                            || mInstantAppRegistry.isInstantAccessGranted(
7761                                    userId, UserHandle.getAppId(uid), ps.appId));
7762            if (returnAllowed) {
7763                return ps.getInstantApp(userId);
7764            }
7765        }
7766        return false;
7767    }
7768
7769    @Override
7770    public byte[] getInstantAppCookie(String packageName, int userId) {
7771        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7772            return null;
7773        }
7774
7775        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7776                true /* requireFullPermission */, false /* checkShell */,
7777                "getInstantAppCookie");
7778        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7779            return null;
7780        }
7781        synchronized (mPackages) {
7782            return mInstantAppRegistry.getInstantAppCookieLPw(
7783                    packageName, userId);
7784        }
7785    }
7786
7787    @Override
7788    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7789        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7790            return true;
7791        }
7792
7793        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7794                true /* requireFullPermission */, true /* checkShell */,
7795                "setInstantAppCookie");
7796        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7797            return false;
7798        }
7799        synchronized (mPackages) {
7800            return mInstantAppRegistry.setInstantAppCookieLPw(
7801                    packageName, cookie, userId);
7802        }
7803    }
7804
7805    @Override
7806    public Bitmap getInstantAppIcon(String packageName, int userId) {
7807        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7808            return null;
7809        }
7810
7811        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7812                "getInstantAppIcon");
7813
7814        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7815                true /* requireFullPermission */, false /* checkShell */,
7816                "getInstantAppIcon");
7817
7818        synchronized (mPackages) {
7819            return mInstantAppRegistry.getInstantAppIconLPw(
7820                    packageName, userId);
7821        }
7822    }
7823
7824    private boolean isCallerSameApp(String packageName, int uid) {
7825        PackageParser.Package pkg = mPackages.get(packageName);
7826        return pkg != null
7827                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7828    }
7829
7830    @Override
7831    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7832        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7833    }
7834
7835    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7836        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7837
7838        // reader
7839        synchronized (mPackages) {
7840            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7841            final int userId = UserHandle.getCallingUserId();
7842            while (i.hasNext()) {
7843                final PackageParser.Package p = i.next();
7844                if (p.applicationInfo == null) continue;
7845
7846                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7847                        && !p.applicationInfo.isDirectBootAware();
7848                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7849                        && p.applicationInfo.isDirectBootAware();
7850
7851                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7852                        && (!mSafeMode || isSystemApp(p))
7853                        && (matchesUnaware || matchesAware)) {
7854                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7855                    if (ps != null) {
7856                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7857                                ps.readUserState(userId), userId);
7858                        if (ai != null) {
7859                            rebaseEnabledOverlays(ai, userId);
7860                            finalList.add(ai);
7861                        }
7862                    }
7863                }
7864            }
7865        }
7866
7867        return finalList;
7868    }
7869
7870    @Override
7871    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7872        if (!sUserManager.exists(userId)) return null;
7873        flags = updateFlagsForComponent(flags, userId, name);
7874        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7875        // reader
7876        synchronized (mPackages) {
7877            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7878            PackageSetting ps = provider != null
7879                    ? mSettings.mPackages.get(provider.owner.packageName)
7880                    : null;
7881            if (ps != null) {
7882                final boolean isInstantApp = ps.getInstantApp(userId);
7883                // normal application; filter out instant application provider
7884                if (instantAppPkgName == null && isInstantApp) {
7885                    return null;
7886                }
7887                // instant application; filter out other instant applications
7888                if (instantAppPkgName != null
7889                        && isInstantApp
7890                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7891                    return null;
7892                }
7893                // instant application; filter out non-exposed provider
7894                if (instantAppPkgName != null
7895                        && !isInstantApp
7896                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7897                    return null;
7898                }
7899                // provider not enabled
7900                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7901                    return null;
7902                }
7903                return PackageParser.generateProviderInfo(
7904                        provider, flags, ps.readUserState(userId), userId);
7905            }
7906            return null;
7907        }
7908    }
7909
7910    /**
7911     * @deprecated
7912     */
7913    @Deprecated
7914    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7915        // reader
7916        synchronized (mPackages) {
7917            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7918                    .entrySet().iterator();
7919            final int userId = UserHandle.getCallingUserId();
7920            while (i.hasNext()) {
7921                Map.Entry<String, PackageParser.Provider> entry = i.next();
7922                PackageParser.Provider p = entry.getValue();
7923                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7924
7925                if (ps != null && p.syncable
7926                        && (!mSafeMode || (p.info.applicationInfo.flags
7927                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7928                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7929                            ps.readUserState(userId), userId);
7930                    if (info != null) {
7931                        outNames.add(entry.getKey());
7932                        outInfo.add(info);
7933                    }
7934                }
7935            }
7936        }
7937    }
7938
7939    @Override
7940    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7941            int uid, int flags, String metaDataKey) {
7942        final int userId = processName != null ? UserHandle.getUserId(uid)
7943                : UserHandle.getCallingUserId();
7944        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7945        flags = updateFlagsForComponent(flags, userId, processName);
7946
7947        ArrayList<ProviderInfo> finalList = null;
7948        // reader
7949        synchronized (mPackages) {
7950            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7951            while (i.hasNext()) {
7952                final PackageParser.Provider p = i.next();
7953                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7954                if (ps != null && p.info.authority != null
7955                        && (processName == null
7956                                || (p.info.processName.equals(processName)
7957                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7958                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7959
7960                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7961                    // parameter.
7962                    if (metaDataKey != null
7963                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7964                        continue;
7965                    }
7966
7967                    if (finalList == null) {
7968                        finalList = new ArrayList<ProviderInfo>(3);
7969                    }
7970                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7971                            ps.readUserState(userId), userId);
7972                    if (info != null) {
7973                        finalList.add(info);
7974                    }
7975                }
7976            }
7977        }
7978
7979        if (finalList != null) {
7980            Collections.sort(finalList, mProviderInitOrderSorter);
7981            return new ParceledListSlice<ProviderInfo>(finalList);
7982        }
7983
7984        return ParceledListSlice.emptyList();
7985    }
7986
7987    @Override
7988    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7989        // reader
7990        synchronized (mPackages) {
7991            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7992            return PackageParser.generateInstrumentationInfo(i, flags);
7993        }
7994    }
7995
7996    @Override
7997    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7998            String targetPackage, int flags) {
7999        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8000    }
8001
8002    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8003            int flags) {
8004        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8005
8006        // reader
8007        synchronized (mPackages) {
8008            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8009            while (i.hasNext()) {
8010                final PackageParser.Instrumentation p = i.next();
8011                if (targetPackage == null
8012                        || targetPackage.equals(p.info.targetPackage)) {
8013                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8014                            flags);
8015                    if (ii != null) {
8016                        finalList.add(ii);
8017                    }
8018                }
8019            }
8020        }
8021
8022        return finalList;
8023    }
8024
8025    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8026        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8027        try {
8028            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8029        } finally {
8030            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8031        }
8032    }
8033
8034    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8035        final File[] files = dir.listFiles();
8036        if (ArrayUtils.isEmpty(files)) {
8037            Log.d(TAG, "No files in app dir " + dir);
8038            return;
8039        }
8040
8041        if (DEBUG_PACKAGE_SCANNING) {
8042            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8043                    + " flags=0x" + Integer.toHexString(parseFlags));
8044        }
8045        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8046                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8047                mParallelPackageParserCallback);
8048
8049        // Submit files for parsing in parallel
8050        int fileCount = 0;
8051        for (File file : files) {
8052            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8053                    && !PackageInstallerService.isStageName(file.getName());
8054            if (!isPackage) {
8055                // Ignore entries which are not packages
8056                continue;
8057            }
8058            parallelPackageParser.submit(file, parseFlags);
8059            fileCount++;
8060        }
8061
8062        // Process results one by one
8063        for (; fileCount > 0; fileCount--) {
8064            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8065            Throwable throwable = parseResult.throwable;
8066            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8067
8068            if (throwable == null) {
8069                // Static shared libraries have synthetic package names
8070                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8071                    renameStaticSharedLibraryPackage(parseResult.pkg);
8072                }
8073                try {
8074                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8075                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8076                                currentTime, null);
8077                    }
8078                } catch (PackageManagerException e) {
8079                    errorCode = e.error;
8080                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8081                }
8082            } else if (throwable instanceof PackageParser.PackageParserException) {
8083                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8084                        throwable;
8085                errorCode = e.error;
8086                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8087            } else {
8088                throw new IllegalStateException("Unexpected exception occurred while parsing "
8089                        + parseResult.scanFile, throwable);
8090            }
8091
8092            // Delete invalid userdata apps
8093            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8094                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8095                logCriticalInfo(Log.WARN,
8096                        "Deleting invalid package at " + parseResult.scanFile);
8097                removeCodePathLI(parseResult.scanFile);
8098            }
8099        }
8100        parallelPackageParser.close();
8101    }
8102
8103    private static File getSettingsProblemFile() {
8104        File dataDir = Environment.getDataDirectory();
8105        File systemDir = new File(dataDir, "system");
8106        File fname = new File(systemDir, "uiderrors.txt");
8107        return fname;
8108    }
8109
8110    static void reportSettingsProblem(int priority, String msg) {
8111        logCriticalInfo(priority, msg);
8112    }
8113
8114    public static void logCriticalInfo(int priority, String msg) {
8115        Slog.println(priority, TAG, msg);
8116        EventLogTags.writePmCriticalInfo(msg);
8117        try {
8118            File fname = getSettingsProblemFile();
8119            FileOutputStream out = new FileOutputStream(fname, true);
8120            PrintWriter pw = new FastPrintWriter(out);
8121            SimpleDateFormat formatter = new SimpleDateFormat();
8122            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8123            pw.println(dateString + ": " + msg);
8124            pw.close();
8125            FileUtils.setPermissions(
8126                    fname.toString(),
8127                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8128                    -1, -1);
8129        } catch (java.io.IOException e) {
8130        }
8131    }
8132
8133    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8134        if (srcFile.isDirectory()) {
8135            final File baseFile = new File(pkg.baseCodePath);
8136            long maxModifiedTime = baseFile.lastModified();
8137            if (pkg.splitCodePaths != null) {
8138                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8139                    final File splitFile = new File(pkg.splitCodePaths[i]);
8140                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8141                }
8142            }
8143            return maxModifiedTime;
8144        }
8145        return srcFile.lastModified();
8146    }
8147
8148    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8149            final int policyFlags) throws PackageManagerException {
8150        // When upgrading from pre-N MR1, verify the package time stamp using the package
8151        // directory and not the APK file.
8152        final long lastModifiedTime = mIsPreNMR1Upgrade
8153                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8154        if (ps != null
8155                && ps.codePath.equals(srcFile)
8156                && ps.timeStamp == lastModifiedTime
8157                && !isCompatSignatureUpdateNeeded(pkg)
8158                && !isRecoverSignatureUpdateNeeded(pkg)) {
8159            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8160            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8161            ArraySet<PublicKey> signingKs;
8162            synchronized (mPackages) {
8163                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8164            }
8165            if (ps.signatures.mSignatures != null
8166                    && ps.signatures.mSignatures.length != 0
8167                    && signingKs != null) {
8168                // Optimization: reuse the existing cached certificates
8169                // if the package appears to be unchanged.
8170                pkg.mSignatures = ps.signatures.mSignatures;
8171                pkg.mSigningKeys = signingKs;
8172                return;
8173            }
8174
8175            Slog.w(TAG, "PackageSetting for " + ps.name
8176                    + " is missing signatures.  Collecting certs again to recover them.");
8177        } else {
8178            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8179        }
8180
8181        try {
8182            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8183            PackageParser.collectCertificates(pkg, policyFlags);
8184        } catch (PackageParserException e) {
8185            throw PackageManagerException.from(e);
8186        } finally {
8187            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8188        }
8189    }
8190
8191    /**
8192     *  Traces a package scan.
8193     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8194     */
8195    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8196            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8197        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8198        try {
8199            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8200        } finally {
8201            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8202        }
8203    }
8204
8205    /**
8206     *  Scans a package and returns the newly parsed package.
8207     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8208     */
8209    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8210            long currentTime, UserHandle user) throws PackageManagerException {
8211        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8212        PackageParser pp = new PackageParser();
8213        pp.setSeparateProcesses(mSeparateProcesses);
8214        pp.setOnlyCoreApps(mOnlyCore);
8215        pp.setDisplayMetrics(mMetrics);
8216        pp.setCallback(mPackageParserCallback);
8217
8218        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8219            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8220        }
8221
8222        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8223        final PackageParser.Package pkg;
8224        try {
8225            pkg = pp.parsePackage(scanFile, parseFlags);
8226        } catch (PackageParserException e) {
8227            throw PackageManagerException.from(e);
8228        } finally {
8229            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8230        }
8231
8232        // Static shared libraries have synthetic package names
8233        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8234            renameStaticSharedLibraryPackage(pkg);
8235        }
8236
8237        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8238    }
8239
8240    /**
8241     *  Scans a package and returns the newly parsed package.
8242     *  @throws PackageManagerException on a parse error.
8243     */
8244    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8245            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8246            throws PackageManagerException {
8247        // If the package has children and this is the first dive in the function
8248        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8249        // packages (parent and children) would be successfully scanned before the
8250        // actual scan since scanning mutates internal state and we want to atomically
8251        // install the package and its children.
8252        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8253            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8254                scanFlags |= SCAN_CHECK_ONLY;
8255            }
8256        } else {
8257            scanFlags &= ~SCAN_CHECK_ONLY;
8258        }
8259
8260        // Scan the parent
8261        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8262                scanFlags, currentTime, user);
8263
8264        // Scan the children
8265        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8266        for (int i = 0; i < childCount; i++) {
8267            PackageParser.Package childPackage = pkg.childPackages.get(i);
8268            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8269                    currentTime, user);
8270        }
8271
8272
8273        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8274            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8275        }
8276
8277        return scannedPkg;
8278    }
8279
8280    /**
8281     *  Scans a package and returns the newly parsed package.
8282     *  @throws PackageManagerException on a parse error.
8283     */
8284    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8285            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8286            throws PackageManagerException {
8287        PackageSetting ps = null;
8288        PackageSetting updatedPkg;
8289        // reader
8290        synchronized (mPackages) {
8291            // Look to see if we already know about this package.
8292            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8293            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8294                // This package has been renamed to its original name.  Let's
8295                // use that.
8296                ps = mSettings.getPackageLPr(oldName);
8297            }
8298            // If there was no original package, see one for the real package name.
8299            if (ps == null) {
8300                ps = mSettings.getPackageLPr(pkg.packageName);
8301            }
8302            // Check to see if this package could be hiding/updating a system
8303            // package.  Must look for it either under the original or real
8304            // package name depending on our state.
8305            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8306            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8307
8308            // If this is a package we don't know about on the system partition, we
8309            // may need to remove disabled child packages on the system partition
8310            // or may need to not add child packages if the parent apk is updated
8311            // on the data partition and no longer defines this child package.
8312            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8313                // If this is a parent package for an updated system app and this system
8314                // app got an OTA update which no longer defines some of the child packages
8315                // we have to prune them from the disabled system packages.
8316                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8317                if (disabledPs != null) {
8318                    final int scannedChildCount = (pkg.childPackages != null)
8319                            ? pkg.childPackages.size() : 0;
8320                    final int disabledChildCount = disabledPs.childPackageNames != null
8321                            ? disabledPs.childPackageNames.size() : 0;
8322                    for (int i = 0; i < disabledChildCount; i++) {
8323                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8324                        boolean disabledPackageAvailable = false;
8325                        for (int j = 0; j < scannedChildCount; j++) {
8326                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8327                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8328                                disabledPackageAvailable = true;
8329                                break;
8330                            }
8331                         }
8332                         if (!disabledPackageAvailable) {
8333                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8334                         }
8335                    }
8336                }
8337            }
8338        }
8339
8340        boolean updatedPkgBetter = false;
8341        // First check if this is a system package that may involve an update
8342        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8343            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8344            // it needs to drop FLAG_PRIVILEGED.
8345            if (locationIsPrivileged(scanFile)) {
8346                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8347            } else {
8348                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8349            }
8350
8351            if (ps != null && !ps.codePath.equals(scanFile)) {
8352                // The path has changed from what was last scanned...  check the
8353                // version of the new path against what we have stored to determine
8354                // what to do.
8355                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8356                if (pkg.mVersionCode <= ps.versionCode) {
8357                    // The system package has been updated and the code path does not match
8358                    // Ignore entry. Skip it.
8359                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8360                            + " ignored: updated version " + ps.versionCode
8361                            + " better than this " + pkg.mVersionCode);
8362                    if (!updatedPkg.codePath.equals(scanFile)) {
8363                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8364                                + ps.name + " changing from " + updatedPkg.codePathString
8365                                + " to " + scanFile);
8366                        updatedPkg.codePath = scanFile;
8367                        updatedPkg.codePathString = scanFile.toString();
8368                        updatedPkg.resourcePath = scanFile;
8369                        updatedPkg.resourcePathString = scanFile.toString();
8370                    }
8371                    updatedPkg.pkg = pkg;
8372                    updatedPkg.versionCode = pkg.mVersionCode;
8373
8374                    // Update the disabled system child packages to point to the package too.
8375                    final int childCount = updatedPkg.childPackageNames != null
8376                            ? updatedPkg.childPackageNames.size() : 0;
8377                    for (int i = 0; i < childCount; i++) {
8378                        String childPackageName = updatedPkg.childPackageNames.get(i);
8379                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8380                                childPackageName);
8381                        if (updatedChildPkg != null) {
8382                            updatedChildPkg.pkg = pkg;
8383                            updatedChildPkg.versionCode = pkg.mVersionCode;
8384                        }
8385                    }
8386
8387                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8388                            + scanFile + " ignored: updated version " + ps.versionCode
8389                            + " better than this " + pkg.mVersionCode);
8390                } else {
8391                    // The current app on the system partition is better than
8392                    // what we have updated to on the data partition; switch
8393                    // back to the system partition version.
8394                    // At this point, its safely assumed that package installation for
8395                    // apps in system partition will go through. If not there won't be a working
8396                    // version of the app
8397                    // writer
8398                    synchronized (mPackages) {
8399                        // Just remove the loaded entries from package lists.
8400                        mPackages.remove(ps.name);
8401                    }
8402
8403                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8404                            + " reverting from " + ps.codePathString
8405                            + ": new version " + pkg.mVersionCode
8406                            + " better than installed " + ps.versionCode);
8407
8408                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8409                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8410                    synchronized (mInstallLock) {
8411                        args.cleanUpResourcesLI();
8412                    }
8413                    synchronized (mPackages) {
8414                        mSettings.enableSystemPackageLPw(ps.name);
8415                    }
8416                    updatedPkgBetter = true;
8417                }
8418            }
8419        }
8420
8421        if (updatedPkg != null) {
8422            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8423            // initially
8424            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8425
8426            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8427            // flag set initially
8428            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8429                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8430            }
8431        }
8432
8433        // Verify certificates against what was last scanned
8434        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8435
8436        /*
8437         * A new system app appeared, but we already had a non-system one of the
8438         * same name installed earlier.
8439         */
8440        boolean shouldHideSystemApp = false;
8441        if (updatedPkg == null && ps != null
8442                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8443            /*
8444             * Check to make sure the signatures match first. If they don't,
8445             * wipe the installed application and its data.
8446             */
8447            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8448                    != PackageManager.SIGNATURE_MATCH) {
8449                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8450                        + " signatures don't match existing userdata copy; removing");
8451                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8452                        "scanPackageInternalLI")) {
8453                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8454                }
8455                ps = null;
8456            } else {
8457                /*
8458                 * If the newly-added system app is an older version than the
8459                 * already installed version, hide it. It will be scanned later
8460                 * and re-added like an update.
8461                 */
8462                if (pkg.mVersionCode <= ps.versionCode) {
8463                    shouldHideSystemApp = true;
8464                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8465                            + " but new version " + pkg.mVersionCode + " better than installed "
8466                            + ps.versionCode + "; hiding system");
8467                } else {
8468                    /*
8469                     * The newly found system app is a newer version that the
8470                     * one previously installed. Simply remove the
8471                     * already-installed application and replace it with our own
8472                     * while keeping the application data.
8473                     */
8474                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8475                            + " reverting from " + ps.codePathString + ": new version "
8476                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8477                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8478                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8479                    synchronized (mInstallLock) {
8480                        args.cleanUpResourcesLI();
8481                    }
8482                }
8483            }
8484        }
8485
8486        // The apk is forward locked (not public) if its code and resources
8487        // are kept in different files. (except for app in either system or
8488        // vendor path).
8489        // TODO grab this value from PackageSettings
8490        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8491            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8492                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8493            }
8494        }
8495
8496        // TODO: extend to support forward-locked splits
8497        String resourcePath = null;
8498        String baseResourcePath = null;
8499        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8500            if (ps != null && ps.resourcePathString != null) {
8501                resourcePath = ps.resourcePathString;
8502                baseResourcePath = ps.resourcePathString;
8503            } else {
8504                // Should not happen at all. Just log an error.
8505                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8506            }
8507        } else {
8508            resourcePath = pkg.codePath;
8509            baseResourcePath = pkg.baseCodePath;
8510        }
8511
8512        // Set application objects path explicitly.
8513        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8514        pkg.setApplicationInfoCodePath(pkg.codePath);
8515        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8516        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8517        pkg.setApplicationInfoResourcePath(resourcePath);
8518        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8519        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8520
8521        final int userId = ((user == null) ? 0 : user.getIdentifier());
8522        if (ps != null && ps.getInstantApp(userId)) {
8523            scanFlags |= SCAN_AS_INSTANT_APP;
8524        }
8525
8526        // Note that we invoke the following method only if we are about to unpack an application
8527        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8528                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8529
8530        /*
8531         * If the system app should be overridden by a previously installed
8532         * data, hide the system app now and let the /data/app scan pick it up
8533         * again.
8534         */
8535        if (shouldHideSystemApp) {
8536            synchronized (mPackages) {
8537                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8538            }
8539        }
8540
8541        return scannedPkg;
8542    }
8543
8544    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8545        // Derive the new package synthetic package name
8546        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8547                + pkg.staticSharedLibVersion);
8548    }
8549
8550    private static String fixProcessName(String defProcessName,
8551            String processName) {
8552        if (processName == null) {
8553            return defProcessName;
8554        }
8555        return processName;
8556    }
8557
8558    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8559            throws PackageManagerException {
8560        if (pkgSetting.signatures.mSignatures != null) {
8561            // Already existing package. Make sure signatures match
8562            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8563                    == PackageManager.SIGNATURE_MATCH;
8564            if (!match) {
8565                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8566                        == PackageManager.SIGNATURE_MATCH;
8567            }
8568            if (!match) {
8569                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8570                        == PackageManager.SIGNATURE_MATCH;
8571            }
8572            if (!match) {
8573                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8574                        + pkg.packageName + " signatures do not match the "
8575                        + "previously installed version; ignoring!");
8576            }
8577        }
8578
8579        // Check for shared user signatures
8580        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8581            // Already existing package. Make sure signatures match
8582            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8583                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8584            if (!match) {
8585                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8586                        == PackageManager.SIGNATURE_MATCH;
8587            }
8588            if (!match) {
8589                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8590                        == PackageManager.SIGNATURE_MATCH;
8591            }
8592            if (!match) {
8593                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8594                        "Package " + pkg.packageName
8595                        + " has no signatures that match those in shared user "
8596                        + pkgSetting.sharedUser.name + "; ignoring!");
8597            }
8598        }
8599    }
8600
8601    /**
8602     * Enforces that only the system UID or root's UID can call a method exposed
8603     * via Binder.
8604     *
8605     * @param message used as message if SecurityException is thrown
8606     * @throws SecurityException if the caller is not system or root
8607     */
8608    private static final void enforceSystemOrRoot(String message) {
8609        final int uid = Binder.getCallingUid();
8610        if (uid != Process.SYSTEM_UID && uid != 0) {
8611            throw new SecurityException(message);
8612        }
8613    }
8614
8615    @Override
8616    public void performFstrimIfNeeded() {
8617        enforceSystemOrRoot("Only the system can request fstrim");
8618
8619        // Before everything else, see whether we need to fstrim.
8620        try {
8621            IStorageManager sm = PackageHelper.getStorageManager();
8622            if (sm != null) {
8623                boolean doTrim = false;
8624                final long interval = android.provider.Settings.Global.getLong(
8625                        mContext.getContentResolver(),
8626                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8627                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8628                if (interval > 0) {
8629                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8630                    if (timeSinceLast > interval) {
8631                        doTrim = true;
8632                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8633                                + "; running immediately");
8634                    }
8635                }
8636                if (doTrim) {
8637                    final boolean dexOptDialogShown;
8638                    synchronized (mPackages) {
8639                        dexOptDialogShown = mDexOptDialogShown;
8640                    }
8641                    if (!isFirstBoot() && dexOptDialogShown) {
8642                        try {
8643                            ActivityManager.getService().showBootMessage(
8644                                    mContext.getResources().getString(
8645                                            R.string.android_upgrading_fstrim), true);
8646                        } catch (RemoteException e) {
8647                        }
8648                    }
8649                    sm.runMaintenance();
8650                }
8651            } else {
8652                Slog.e(TAG, "storageManager service unavailable!");
8653            }
8654        } catch (RemoteException e) {
8655            // Can't happen; StorageManagerService is local
8656        }
8657    }
8658
8659    @Override
8660    public void updatePackagesIfNeeded() {
8661        enforceSystemOrRoot("Only the system can request package update");
8662
8663        // We need to re-extract after an OTA.
8664        boolean causeUpgrade = isUpgrade();
8665
8666        // First boot or factory reset.
8667        // Note: we also handle devices that are upgrading to N right now as if it is their
8668        //       first boot, as they do not have profile data.
8669        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8670
8671        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8672        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8673
8674        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8675            return;
8676        }
8677
8678        List<PackageParser.Package> pkgs;
8679        synchronized (mPackages) {
8680            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8681        }
8682
8683        final long startTime = System.nanoTime();
8684        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8685                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8686
8687        final int elapsedTimeSeconds =
8688                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8689
8690        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8691        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8692        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8693        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8694        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8695    }
8696
8697    /**
8698     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8699     * containing statistics about the invocation. The array consists of three elements,
8700     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8701     * and {@code numberOfPackagesFailed}.
8702     */
8703    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8704            String compilerFilter) {
8705
8706        int numberOfPackagesVisited = 0;
8707        int numberOfPackagesOptimized = 0;
8708        int numberOfPackagesSkipped = 0;
8709        int numberOfPackagesFailed = 0;
8710        final int numberOfPackagesToDexopt = pkgs.size();
8711
8712        for (PackageParser.Package pkg : pkgs) {
8713            numberOfPackagesVisited++;
8714
8715            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8716                if (DEBUG_DEXOPT) {
8717                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8718                }
8719                numberOfPackagesSkipped++;
8720                continue;
8721            }
8722
8723            if (DEBUG_DEXOPT) {
8724                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8725                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8726            }
8727
8728            if (showDialog) {
8729                try {
8730                    ActivityManager.getService().showBootMessage(
8731                            mContext.getResources().getString(R.string.android_upgrading_apk,
8732                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8733                } catch (RemoteException e) {
8734                }
8735                synchronized (mPackages) {
8736                    mDexOptDialogShown = true;
8737                }
8738            }
8739
8740            // If the OTA updates a system app which was previously preopted to a non-preopted state
8741            // the app might end up being verified at runtime. That's because by default the apps
8742            // are verify-profile but for preopted apps there's no profile.
8743            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8744            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8745            // filter (by default 'quicken').
8746            // Note that at this stage unused apps are already filtered.
8747            if (isSystemApp(pkg) &&
8748                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8749                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8750                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8751            }
8752
8753            // checkProfiles is false to avoid merging profiles during boot which
8754            // might interfere with background compilation (b/28612421).
8755            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8756            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8757            // trade-off worth doing to save boot time work.
8758            int dexOptStatus = performDexOptTraced(pkg.packageName,
8759                    false /* checkProfiles */,
8760                    compilerFilter,
8761                    false /* force */);
8762            switch (dexOptStatus) {
8763                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8764                    numberOfPackagesOptimized++;
8765                    break;
8766                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8767                    numberOfPackagesSkipped++;
8768                    break;
8769                case PackageDexOptimizer.DEX_OPT_FAILED:
8770                    numberOfPackagesFailed++;
8771                    break;
8772                default:
8773                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8774                    break;
8775            }
8776        }
8777
8778        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8779                numberOfPackagesFailed };
8780    }
8781
8782    @Override
8783    public void notifyPackageUse(String packageName, int reason) {
8784        synchronized (mPackages) {
8785            PackageParser.Package p = mPackages.get(packageName);
8786            if (p == null) {
8787                return;
8788            }
8789            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8790        }
8791    }
8792
8793    @Override
8794    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8795        int userId = UserHandle.getCallingUserId();
8796        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8797        if (ai == null) {
8798            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8799                + loadingPackageName + ", user=" + userId);
8800            return;
8801        }
8802        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8803    }
8804
8805    @Override
8806    public boolean performDexOpt(String packageName,
8807            boolean checkProfiles, int compileReason, boolean force) {
8808        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8809                getCompilerFilterForReason(compileReason), force);
8810        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8811    }
8812
8813    @Override
8814    public boolean performDexOptMode(String packageName,
8815            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8816        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8817                targetCompilerFilter, force);
8818        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8819    }
8820
8821    private int performDexOptTraced(String packageName,
8822                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8823        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8824        try {
8825            return performDexOptInternal(packageName, checkProfiles,
8826                    targetCompilerFilter, force);
8827        } finally {
8828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8829        }
8830    }
8831
8832    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8833    // if the package can now be considered up to date for the given filter.
8834    private int performDexOptInternal(String packageName,
8835                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8836        PackageParser.Package p;
8837        synchronized (mPackages) {
8838            p = mPackages.get(packageName);
8839            if (p == null) {
8840                // Package could not be found. Report failure.
8841                return PackageDexOptimizer.DEX_OPT_FAILED;
8842            }
8843            mPackageUsage.maybeWriteAsync(mPackages);
8844            mCompilerStats.maybeWriteAsync();
8845        }
8846        long callingId = Binder.clearCallingIdentity();
8847        try {
8848            synchronized (mInstallLock) {
8849                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8850                        targetCompilerFilter, force);
8851            }
8852        } finally {
8853            Binder.restoreCallingIdentity(callingId);
8854        }
8855    }
8856
8857    public ArraySet<String> getOptimizablePackages() {
8858        ArraySet<String> pkgs = new ArraySet<String>();
8859        synchronized (mPackages) {
8860            for (PackageParser.Package p : mPackages.values()) {
8861                if (PackageDexOptimizer.canOptimizePackage(p)) {
8862                    pkgs.add(p.packageName);
8863                }
8864            }
8865        }
8866        return pkgs;
8867    }
8868
8869    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8870            boolean checkProfiles, String targetCompilerFilter,
8871            boolean force) {
8872        // Select the dex optimizer based on the force parameter.
8873        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8874        //       allocate an object here.
8875        PackageDexOptimizer pdo = force
8876                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8877                : mPackageDexOptimizer;
8878
8879        // Dexopt all dependencies first. Note: we ignore the return value and march on
8880        // on errors.
8881        // Note that we are going to call performDexOpt on those libraries as many times as
8882        // they are referenced in packages. When we do a batch of performDexOpt (for example
8883        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8884        // and the first package that uses the library will dexopt it. The
8885        // others will see that the compiled code for the library is up to date.
8886        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8887        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8888        if (!deps.isEmpty()) {
8889            for (PackageParser.Package depPackage : deps) {
8890                // TODO: Analyze and investigate if we (should) profile libraries.
8891                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8892                        false /* checkProfiles */,
8893                        targetCompilerFilter,
8894                        getOrCreateCompilerPackageStats(depPackage),
8895                        true /* isUsedByOtherApps */);
8896            }
8897        }
8898        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8899                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8900                mDexManager.isUsedByOtherApps(p.packageName));
8901    }
8902
8903    // Performs dexopt on the used secondary dex files belonging to the given package.
8904    // Returns true if all dex files were process successfully (which could mean either dexopt or
8905    // skip). Returns false if any of the files caused errors.
8906    @Override
8907    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8908            boolean force) {
8909        mDexManager.reconcileSecondaryDexFiles(packageName);
8910        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8911    }
8912
8913    public boolean performDexOptSecondary(String packageName, int compileReason,
8914            boolean force) {
8915        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8916    }
8917
8918    /**
8919     * Reconcile the information we have about the secondary dex files belonging to
8920     * {@code packagName} and the actual dex files. For all dex files that were
8921     * deleted, update the internal records and delete the generated oat files.
8922     */
8923    @Override
8924    public void reconcileSecondaryDexFiles(String packageName) {
8925        mDexManager.reconcileSecondaryDexFiles(packageName);
8926    }
8927
8928    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8929    // a reference there.
8930    /*package*/ DexManager getDexManager() {
8931        return mDexManager;
8932    }
8933
8934    /**
8935     * Execute the background dexopt job immediately.
8936     */
8937    @Override
8938    public boolean runBackgroundDexoptJob() {
8939        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8940    }
8941
8942    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8943        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8944                || p.usesStaticLibraries != null) {
8945            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8946            Set<String> collectedNames = new HashSet<>();
8947            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8948
8949            retValue.remove(p);
8950
8951            return retValue;
8952        } else {
8953            return Collections.emptyList();
8954        }
8955    }
8956
8957    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8958            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8959        if (!collectedNames.contains(p.packageName)) {
8960            collectedNames.add(p.packageName);
8961            collected.add(p);
8962
8963            if (p.usesLibraries != null) {
8964                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8965                        null, collected, collectedNames);
8966            }
8967            if (p.usesOptionalLibraries != null) {
8968                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8969                        null, collected, collectedNames);
8970            }
8971            if (p.usesStaticLibraries != null) {
8972                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8973                        p.usesStaticLibrariesVersions, collected, collectedNames);
8974            }
8975        }
8976    }
8977
8978    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8979            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8980        final int libNameCount = libs.size();
8981        for (int i = 0; i < libNameCount; i++) {
8982            String libName = libs.get(i);
8983            int version = (versions != null && versions.length == libNameCount)
8984                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8985            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8986            if (libPkg != null) {
8987                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8988            }
8989        }
8990    }
8991
8992    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8993        synchronized (mPackages) {
8994            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8995            if (libEntry != null) {
8996                return mPackages.get(libEntry.apk);
8997            }
8998            return null;
8999        }
9000    }
9001
9002    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9003        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9004        if (versionedLib == null) {
9005            return null;
9006        }
9007        return versionedLib.get(version);
9008    }
9009
9010    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9011        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9012                pkg.staticSharedLibName);
9013        if (versionedLib == null) {
9014            return null;
9015        }
9016        int previousLibVersion = -1;
9017        final int versionCount = versionedLib.size();
9018        for (int i = 0; i < versionCount; i++) {
9019            final int libVersion = versionedLib.keyAt(i);
9020            if (libVersion < pkg.staticSharedLibVersion) {
9021                previousLibVersion = Math.max(previousLibVersion, libVersion);
9022            }
9023        }
9024        if (previousLibVersion >= 0) {
9025            return versionedLib.get(previousLibVersion);
9026        }
9027        return null;
9028    }
9029
9030    public void shutdown() {
9031        mPackageUsage.writeNow(mPackages);
9032        mCompilerStats.writeNow();
9033    }
9034
9035    @Override
9036    public void dumpProfiles(String packageName) {
9037        PackageParser.Package pkg;
9038        synchronized (mPackages) {
9039            pkg = mPackages.get(packageName);
9040            if (pkg == null) {
9041                throw new IllegalArgumentException("Unknown package: " + packageName);
9042            }
9043        }
9044        /* Only the shell, root, or the app user should be able to dump profiles. */
9045        int callingUid = Binder.getCallingUid();
9046        if (callingUid != Process.SHELL_UID &&
9047            callingUid != Process.ROOT_UID &&
9048            callingUid != pkg.applicationInfo.uid) {
9049            throw new SecurityException("dumpProfiles");
9050        }
9051
9052        synchronized (mInstallLock) {
9053            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9054            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9055            try {
9056                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9057                String codePaths = TextUtils.join(";", allCodePaths);
9058                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9059            } catch (InstallerException e) {
9060                Slog.w(TAG, "Failed to dump profiles", e);
9061            }
9062            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9063        }
9064    }
9065
9066    @Override
9067    public void forceDexOpt(String packageName) {
9068        enforceSystemOrRoot("forceDexOpt");
9069
9070        PackageParser.Package pkg;
9071        synchronized (mPackages) {
9072            pkg = mPackages.get(packageName);
9073            if (pkg == null) {
9074                throw new IllegalArgumentException("Unknown package: " + packageName);
9075            }
9076        }
9077
9078        synchronized (mInstallLock) {
9079            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9080
9081            // Whoever is calling forceDexOpt wants a compiled package.
9082            // Don't use profiles since that may cause compilation to be skipped.
9083            final int res = performDexOptInternalWithDependenciesLI(pkg,
9084                    false /* checkProfiles */, getDefaultCompilerFilter(),
9085                    true /* force */);
9086
9087            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9088            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9089                throw new IllegalStateException("Failed to dexopt: " + res);
9090            }
9091        }
9092    }
9093
9094    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9095        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9096            Slog.w(TAG, "Unable to update from " + oldPkg.name
9097                    + " to " + newPkg.packageName
9098                    + ": old package not in system partition");
9099            return false;
9100        } else if (mPackages.get(oldPkg.name) != null) {
9101            Slog.w(TAG, "Unable to update from " + oldPkg.name
9102                    + " to " + newPkg.packageName
9103                    + ": old package still exists");
9104            return false;
9105        }
9106        return true;
9107    }
9108
9109    void removeCodePathLI(File codePath) {
9110        if (codePath.isDirectory()) {
9111            try {
9112                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9113            } catch (InstallerException e) {
9114                Slog.w(TAG, "Failed to remove code path", e);
9115            }
9116        } else {
9117            codePath.delete();
9118        }
9119    }
9120
9121    private int[] resolveUserIds(int userId) {
9122        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9123    }
9124
9125    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9126        if (pkg == null) {
9127            Slog.wtf(TAG, "Package was null!", new Throwable());
9128            return;
9129        }
9130        clearAppDataLeafLIF(pkg, userId, flags);
9131        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9132        for (int i = 0; i < childCount; i++) {
9133            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9134        }
9135    }
9136
9137    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9138        final PackageSetting ps;
9139        synchronized (mPackages) {
9140            ps = mSettings.mPackages.get(pkg.packageName);
9141        }
9142        for (int realUserId : resolveUserIds(userId)) {
9143            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9144            try {
9145                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9146                        ceDataInode);
9147            } catch (InstallerException e) {
9148                Slog.w(TAG, String.valueOf(e));
9149            }
9150        }
9151    }
9152
9153    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9154        if (pkg == null) {
9155            Slog.wtf(TAG, "Package was null!", new Throwable());
9156            return;
9157        }
9158        destroyAppDataLeafLIF(pkg, userId, flags);
9159        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9160        for (int i = 0; i < childCount; i++) {
9161            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9162        }
9163    }
9164
9165    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9166        final PackageSetting ps;
9167        synchronized (mPackages) {
9168            ps = mSettings.mPackages.get(pkg.packageName);
9169        }
9170        for (int realUserId : resolveUserIds(userId)) {
9171            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9172            try {
9173                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9174                        ceDataInode);
9175            } catch (InstallerException e) {
9176                Slog.w(TAG, String.valueOf(e));
9177            }
9178            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9179        }
9180    }
9181
9182    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9183        if (pkg == null) {
9184            Slog.wtf(TAG, "Package was null!", new Throwable());
9185            return;
9186        }
9187        destroyAppProfilesLeafLIF(pkg);
9188        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9189        for (int i = 0; i < childCount; i++) {
9190            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9191        }
9192    }
9193
9194    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9195        try {
9196            mInstaller.destroyAppProfiles(pkg.packageName);
9197        } catch (InstallerException e) {
9198            Slog.w(TAG, String.valueOf(e));
9199        }
9200    }
9201
9202    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9203        if (pkg == null) {
9204            Slog.wtf(TAG, "Package was null!", new Throwable());
9205            return;
9206        }
9207        clearAppProfilesLeafLIF(pkg);
9208        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9209        for (int i = 0; i < childCount; i++) {
9210            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9211        }
9212    }
9213
9214    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9215        try {
9216            mInstaller.clearAppProfiles(pkg.packageName);
9217        } catch (InstallerException e) {
9218            Slog.w(TAG, String.valueOf(e));
9219        }
9220    }
9221
9222    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9223            long lastUpdateTime) {
9224        // Set parent install/update time
9225        PackageSetting ps = (PackageSetting) pkg.mExtras;
9226        if (ps != null) {
9227            ps.firstInstallTime = firstInstallTime;
9228            ps.lastUpdateTime = lastUpdateTime;
9229        }
9230        // Set children install/update time
9231        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9232        for (int i = 0; i < childCount; i++) {
9233            PackageParser.Package childPkg = pkg.childPackages.get(i);
9234            ps = (PackageSetting) childPkg.mExtras;
9235            if (ps != null) {
9236                ps.firstInstallTime = firstInstallTime;
9237                ps.lastUpdateTime = lastUpdateTime;
9238            }
9239        }
9240    }
9241
9242    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9243            PackageParser.Package changingLib) {
9244        if (file.path != null) {
9245            usesLibraryFiles.add(file.path);
9246            return;
9247        }
9248        PackageParser.Package p = mPackages.get(file.apk);
9249        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9250            // If we are doing this while in the middle of updating a library apk,
9251            // then we need to make sure to use that new apk for determining the
9252            // dependencies here.  (We haven't yet finished committing the new apk
9253            // to the package manager state.)
9254            if (p == null || p.packageName.equals(changingLib.packageName)) {
9255                p = changingLib;
9256            }
9257        }
9258        if (p != null) {
9259            usesLibraryFiles.addAll(p.getAllCodePaths());
9260        }
9261    }
9262
9263    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9264            PackageParser.Package changingLib) throws PackageManagerException {
9265        if (pkg == null) {
9266            return;
9267        }
9268        ArraySet<String> usesLibraryFiles = null;
9269        if (pkg.usesLibraries != null) {
9270            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9271                    null, null, pkg.packageName, changingLib, true, null);
9272        }
9273        if (pkg.usesStaticLibraries != null) {
9274            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9275                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9276                    pkg.packageName, changingLib, true, usesLibraryFiles);
9277        }
9278        if (pkg.usesOptionalLibraries != null) {
9279            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9280                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9281        }
9282        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9283            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9284        } else {
9285            pkg.usesLibraryFiles = null;
9286        }
9287    }
9288
9289    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9290            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9291            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9292            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9293            throws PackageManagerException {
9294        final int libCount = requestedLibraries.size();
9295        for (int i = 0; i < libCount; i++) {
9296            final String libName = requestedLibraries.get(i);
9297            final int libVersion = requiredVersions != null ? requiredVersions[i]
9298                    : SharedLibraryInfo.VERSION_UNDEFINED;
9299            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9300            if (libEntry == null) {
9301                if (required) {
9302                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9303                            "Package " + packageName + " requires unavailable shared library "
9304                                    + libName + "; failing!");
9305                } else if (DEBUG_SHARED_LIBRARIES) {
9306                    Slog.i(TAG, "Package " + packageName
9307                            + " desires unavailable shared library "
9308                            + libName + "; ignoring!");
9309                }
9310            } else {
9311                if (requiredVersions != null && requiredCertDigests != null) {
9312                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9313                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9314                            "Package " + packageName + " requires unavailable static shared"
9315                                    + " library " + libName + " version "
9316                                    + libEntry.info.getVersion() + "; failing!");
9317                    }
9318
9319                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9320                    if (libPkg == null) {
9321                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9322                                "Package " + packageName + " requires unavailable static shared"
9323                                        + " library; failing!");
9324                    }
9325
9326                    String expectedCertDigest = requiredCertDigests[i];
9327                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9328                                libPkg.mSignatures[0]);
9329                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9330                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9331                                "Package " + packageName + " requires differently signed" +
9332                                        " static shared library; failing!");
9333                    }
9334                }
9335
9336                if (outUsedLibraries == null) {
9337                    outUsedLibraries = new ArraySet<>();
9338                }
9339                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9340            }
9341        }
9342        return outUsedLibraries;
9343    }
9344
9345    private static boolean hasString(List<String> list, List<String> which) {
9346        if (list == null) {
9347            return false;
9348        }
9349        for (int i=list.size()-1; i>=0; i--) {
9350            for (int j=which.size()-1; j>=0; j--) {
9351                if (which.get(j).equals(list.get(i))) {
9352                    return true;
9353                }
9354            }
9355        }
9356        return false;
9357    }
9358
9359    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9360            PackageParser.Package changingPkg) {
9361        ArrayList<PackageParser.Package> res = null;
9362        for (PackageParser.Package pkg : mPackages.values()) {
9363            if (changingPkg != null
9364                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9365                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9366                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9367                            changingPkg.staticSharedLibName)) {
9368                return null;
9369            }
9370            if (res == null) {
9371                res = new ArrayList<>();
9372            }
9373            res.add(pkg);
9374            try {
9375                updateSharedLibrariesLPr(pkg, changingPkg);
9376            } catch (PackageManagerException e) {
9377                // If a system app update or an app and a required lib missing we
9378                // delete the package and for updated system apps keep the data as
9379                // it is better for the user to reinstall than to be in an limbo
9380                // state. Also libs disappearing under an app should never happen
9381                // - just in case.
9382                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9383                    final int flags = pkg.isUpdatedSystemApp()
9384                            ? PackageManager.DELETE_KEEP_DATA : 0;
9385                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9386                            flags , null, true, null);
9387                }
9388                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9389            }
9390        }
9391        return res;
9392    }
9393
9394    /**
9395     * Derive the value of the {@code cpuAbiOverride} based on the provided
9396     * value and an optional stored value from the package settings.
9397     */
9398    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9399        String cpuAbiOverride = null;
9400
9401        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9402            cpuAbiOverride = null;
9403        } else if (abiOverride != null) {
9404            cpuAbiOverride = abiOverride;
9405        } else if (settings != null) {
9406            cpuAbiOverride = settings.cpuAbiOverrideString;
9407        }
9408
9409        return cpuAbiOverride;
9410    }
9411
9412    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9413            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9414                    throws PackageManagerException {
9415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9416        // If the package has children and this is the first dive in the function
9417        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9418        // whether all packages (parent and children) would be successfully scanned
9419        // before the actual scan since scanning mutates internal state and we want
9420        // to atomically install the package and its children.
9421        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9422            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9423                scanFlags |= SCAN_CHECK_ONLY;
9424            }
9425        } else {
9426            scanFlags &= ~SCAN_CHECK_ONLY;
9427        }
9428
9429        final PackageParser.Package scannedPkg;
9430        try {
9431            // Scan the parent
9432            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9433            // Scan the children
9434            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9435            for (int i = 0; i < childCount; i++) {
9436                PackageParser.Package childPkg = pkg.childPackages.get(i);
9437                scanPackageLI(childPkg, policyFlags,
9438                        scanFlags, currentTime, user);
9439            }
9440        } finally {
9441            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9442        }
9443
9444        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9445            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9446        }
9447
9448        return scannedPkg;
9449    }
9450
9451    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9452            int scanFlags, long currentTime, @Nullable UserHandle user)
9453                    throws PackageManagerException {
9454        boolean success = false;
9455        try {
9456            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9457                    currentTime, user);
9458            success = true;
9459            return res;
9460        } finally {
9461            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9462                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9463                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9464                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9465                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9466            }
9467        }
9468    }
9469
9470    /**
9471     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9472     */
9473    private static boolean apkHasCode(String fileName) {
9474        StrictJarFile jarFile = null;
9475        try {
9476            jarFile = new StrictJarFile(fileName,
9477                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9478            return jarFile.findEntry("classes.dex") != null;
9479        } catch (IOException ignore) {
9480        } finally {
9481            try {
9482                if (jarFile != null) {
9483                    jarFile.close();
9484                }
9485            } catch (IOException ignore) {}
9486        }
9487        return false;
9488    }
9489
9490    /**
9491     * Enforces code policy for the package. This ensures that if an APK has
9492     * declared hasCode="true" in its manifest that the APK actually contains
9493     * code.
9494     *
9495     * @throws PackageManagerException If bytecode could not be found when it should exist
9496     */
9497    private static void assertCodePolicy(PackageParser.Package pkg)
9498            throws PackageManagerException {
9499        final boolean shouldHaveCode =
9500                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9501        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9502            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9503                    "Package " + pkg.baseCodePath + " code is missing");
9504        }
9505
9506        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9507            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9508                final boolean splitShouldHaveCode =
9509                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9510                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9511                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9512                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9513                }
9514            }
9515        }
9516    }
9517
9518    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9519            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9520                    throws PackageManagerException {
9521        if (DEBUG_PACKAGE_SCANNING) {
9522            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9523                Log.d(TAG, "Scanning package " + pkg.packageName);
9524        }
9525
9526        applyPolicy(pkg, policyFlags);
9527
9528        assertPackageIsValid(pkg, policyFlags, scanFlags);
9529
9530        // Initialize package source and resource directories
9531        final File scanFile = new File(pkg.codePath);
9532        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9533        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9534
9535        SharedUserSetting suid = null;
9536        PackageSetting pkgSetting = null;
9537
9538        // Getting the package setting may have a side-effect, so if we
9539        // are only checking if scan would succeed, stash a copy of the
9540        // old setting to restore at the end.
9541        PackageSetting nonMutatedPs = null;
9542
9543        // We keep references to the derived CPU Abis from settings in oder to reuse
9544        // them in the case where we're not upgrading or booting for the first time.
9545        String primaryCpuAbiFromSettings = null;
9546        String secondaryCpuAbiFromSettings = null;
9547
9548        // writer
9549        synchronized (mPackages) {
9550            if (pkg.mSharedUserId != null) {
9551                // SIDE EFFECTS; may potentially allocate a new shared user
9552                suid = mSettings.getSharedUserLPw(
9553                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9554                if (DEBUG_PACKAGE_SCANNING) {
9555                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9556                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9557                                + "): packages=" + suid.packages);
9558                }
9559            }
9560
9561            // Check if we are renaming from an original package name.
9562            PackageSetting origPackage = null;
9563            String realName = null;
9564            if (pkg.mOriginalPackages != null) {
9565                // This package may need to be renamed to a previously
9566                // installed name.  Let's check on that...
9567                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9568                if (pkg.mOriginalPackages.contains(renamed)) {
9569                    // This package had originally been installed as the
9570                    // original name, and we have already taken care of
9571                    // transitioning to the new one.  Just update the new
9572                    // one to continue using the old name.
9573                    realName = pkg.mRealPackage;
9574                    if (!pkg.packageName.equals(renamed)) {
9575                        // Callers into this function may have already taken
9576                        // care of renaming the package; only do it here if
9577                        // it is not already done.
9578                        pkg.setPackageName(renamed);
9579                    }
9580                } else {
9581                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9582                        if ((origPackage = mSettings.getPackageLPr(
9583                                pkg.mOriginalPackages.get(i))) != null) {
9584                            // We do have the package already installed under its
9585                            // original name...  should we use it?
9586                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9587                                // New package is not compatible with original.
9588                                origPackage = null;
9589                                continue;
9590                            } else if (origPackage.sharedUser != null) {
9591                                // Make sure uid is compatible between packages.
9592                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9593                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9594                                            + " to " + pkg.packageName + ": old uid "
9595                                            + origPackage.sharedUser.name
9596                                            + " differs from " + pkg.mSharedUserId);
9597                                    origPackage = null;
9598                                    continue;
9599                                }
9600                                // TODO: Add case when shared user id is added [b/28144775]
9601                            } else {
9602                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9603                                        + pkg.packageName + " to old name " + origPackage.name);
9604                            }
9605                            break;
9606                        }
9607                    }
9608                }
9609            }
9610
9611            if (mTransferedPackages.contains(pkg.packageName)) {
9612                Slog.w(TAG, "Package " + pkg.packageName
9613                        + " was transferred to another, but its .apk remains");
9614            }
9615
9616            // See comments in nonMutatedPs declaration
9617            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9618                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9619                if (foundPs != null) {
9620                    nonMutatedPs = new PackageSetting(foundPs);
9621                }
9622            }
9623
9624            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9625                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9626                if (foundPs != null) {
9627                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9628                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9629                }
9630            }
9631
9632            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9633            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9634                PackageManagerService.reportSettingsProblem(Log.WARN,
9635                        "Package " + pkg.packageName + " shared user changed from "
9636                                + (pkgSetting.sharedUser != null
9637                                        ? pkgSetting.sharedUser.name : "<nothing>")
9638                                + " to "
9639                                + (suid != null ? suid.name : "<nothing>")
9640                                + "; replacing with new");
9641                pkgSetting = null;
9642            }
9643            final PackageSetting oldPkgSetting =
9644                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9645            final PackageSetting disabledPkgSetting =
9646                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9647
9648            String[] usesStaticLibraries = null;
9649            if (pkg.usesStaticLibraries != null) {
9650                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9651                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9652            }
9653
9654            if (pkgSetting == null) {
9655                final String parentPackageName = (pkg.parentPackage != null)
9656                        ? pkg.parentPackage.packageName : null;
9657                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9658                // REMOVE SharedUserSetting from method; update in a separate call
9659                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9660                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9661                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9662                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9663                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9664                        true /*allowInstall*/, instantApp, parentPackageName,
9665                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9666                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9667                // SIDE EFFECTS; updates system state; move elsewhere
9668                if (origPackage != null) {
9669                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9670                }
9671                mSettings.addUserToSettingLPw(pkgSetting);
9672            } else {
9673                // REMOVE SharedUserSetting from method; update in a separate call.
9674                //
9675                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9676                // secondaryCpuAbi are not known at this point so we always update them
9677                // to null here, only to reset them at a later point.
9678                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9679                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9680                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9681                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9682                        UserManagerService.getInstance(), usesStaticLibraries,
9683                        pkg.usesStaticLibrariesVersions);
9684            }
9685            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9686            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9687
9688            // SIDE EFFECTS; modifies system state; move elsewhere
9689            if (pkgSetting.origPackage != null) {
9690                // If we are first transitioning from an original package,
9691                // fix up the new package's name now.  We need to do this after
9692                // looking up the package under its new name, so getPackageLP
9693                // can take care of fiddling things correctly.
9694                pkg.setPackageName(origPackage.name);
9695
9696                // File a report about this.
9697                String msg = "New package " + pkgSetting.realName
9698                        + " renamed to replace old package " + pkgSetting.name;
9699                reportSettingsProblem(Log.WARN, msg);
9700
9701                // Make a note of it.
9702                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9703                    mTransferedPackages.add(origPackage.name);
9704                }
9705
9706                // No longer need to retain this.
9707                pkgSetting.origPackage = null;
9708            }
9709
9710            // SIDE EFFECTS; modifies system state; move elsewhere
9711            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9712                // Make a note of it.
9713                mTransferedPackages.add(pkg.packageName);
9714            }
9715
9716            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9717                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9718            }
9719
9720            if ((scanFlags & SCAN_BOOTING) == 0
9721                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9722                // Check all shared libraries and map to their actual file path.
9723                // We only do this here for apps not on a system dir, because those
9724                // are the only ones that can fail an install due to this.  We
9725                // will take care of the system apps by updating all of their
9726                // library paths after the scan is done. Also during the initial
9727                // scan don't update any libs as we do this wholesale after all
9728                // apps are scanned to avoid dependency based scanning.
9729                updateSharedLibrariesLPr(pkg, null);
9730            }
9731
9732            if (mFoundPolicyFile) {
9733                SELinuxMMAC.assignSeInfoValue(pkg);
9734            }
9735            pkg.applicationInfo.uid = pkgSetting.appId;
9736            pkg.mExtras = pkgSetting;
9737
9738
9739            // Static shared libs have same package with different versions where
9740            // we internally use a synthetic package name to allow multiple versions
9741            // of the same package, therefore we need to compare signatures against
9742            // the package setting for the latest library version.
9743            PackageSetting signatureCheckPs = pkgSetting;
9744            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9745                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9746                if (libraryEntry != null) {
9747                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9748                }
9749            }
9750
9751            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9752                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9753                    // We just determined the app is signed correctly, so bring
9754                    // over the latest parsed certs.
9755                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9756                } else {
9757                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9758                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9759                                "Package " + pkg.packageName + " upgrade keys do not match the "
9760                                + "previously installed version");
9761                    } else {
9762                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9763                        String msg = "System package " + pkg.packageName
9764                                + " signature changed; retaining data.";
9765                        reportSettingsProblem(Log.WARN, msg);
9766                    }
9767                }
9768            } else {
9769                try {
9770                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9771                    verifySignaturesLP(signatureCheckPs, pkg);
9772                    // We just determined the app is signed correctly, so bring
9773                    // over the latest parsed certs.
9774                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9775                } catch (PackageManagerException e) {
9776                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9777                        throw e;
9778                    }
9779                    // The signature has changed, but this package is in the system
9780                    // image...  let's recover!
9781                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9782                    // However...  if this package is part of a shared user, but it
9783                    // doesn't match the signature of the shared user, let's fail.
9784                    // What this means is that you can't change the signatures
9785                    // associated with an overall shared user, which doesn't seem all
9786                    // that unreasonable.
9787                    if (signatureCheckPs.sharedUser != null) {
9788                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9789                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9790                            throw new PackageManagerException(
9791                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9792                                    "Signature mismatch for shared user: "
9793                                            + pkgSetting.sharedUser);
9794                        }
9795                    }
9796                    // File a report about this.
9797                    String msg = "System package " + pkg.packageName
9798                            + " signature changed; retaining data.";
9799                    reportSettingsProblem(Log.WARN, msg);
9800                }
9801            }
9802
9803            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9804                // This package wants to adopt ownership of permissions from
9805                // another package.
9806                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9807                    final String origName = pkg.mAdoptPermissions.get(i);
9808                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9809                    if (orig != null) {
9810                        if (verifyPackageUpdateLPr(orig, pkg)) {
9811                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9812                                    + pkg.packageName);
9813                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9814                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9815                        }
9816                    }
9817                }
9818            }
9819        }
9820
9821        pkg.applicationInfo.processName = fixProcessName(
9822                pkg.applicationInfo.packageName,
9823                pkg.applicationInfo.processName);
9824
9825        if (pkg != mPlatformPackage) {
9826            // Get all of our default paths setup
9827            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9828        }
9829
9830        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9831
9832        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9833            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9834                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9835                derivePackageAbi(
9836                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9837                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9838
9839                // Some system apps still use directory structure for native libraries
9840                // in which case we might end up not detecting abi solely based on apk
9841                // structure. Try to detect abi based on directory structure.
9842                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9843                        pkg.applicationInfo.primaryCpuAbi == null) {
9844                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9845                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9846                }
9847            } else {
9848                // This is not a first boot or an upgrade, don't bother deriving the
9849                // ABI during the scan. Instead, trust the value that was stored in the
9850                // package setting.
9851                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9852                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9853
9854                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9855
9856                if (DEBUG_ABI_SELECTION) {
9857                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9858                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9859                        pkg.applicationInfo.secondaryCpuAbi);
9860                }
9861            }
9862        } else {
9863            if ((scanFlags & SCAN_MOVE) != 0) {
9864                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9865                // but we already have this packages package info in the PackageSetting. We just
9866                // use that and derive the native library path based on the new codepath.
9867                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9868                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9869            }
9870
9871            // Set native library paths again. For moves, the path will be updated based on the
9872            // ABIs we've determined above. For non-moves, the path will be updated based on the
9873            // ABIs we determined during compilation, but the path will depend on the final
9874            // package path (after the rename away from the stage path).
9875            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9876        }
9877
9878        // This is a special case for the "system" package, where the ABI is
9879        // dictated by the zygote configuration (and init.rc). We should keep track
9880        // of this ABI so that we can deal with "normal" applications that run under
9881        // the same UID correctly.
9882        if (mPlatformPackage == pkg) {
9883            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9884                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9885        }
9886
9887        // If there's a mismatch between the abi-override in the package setting
9888        // and the abiOverride specified for the install. Warn about this because we
9889        // would've already compiled the app without taking the package setting into
9890        // account.
9891        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9892            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9893                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9894                        " for package " + pkg.packageName);
9895            }
9896        }
9897
9898        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9899        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9900        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9901
9902        // Copy the derived override back to the parsed package, so that we can
9903        // update the package settings accordingly.
9904        pkg.cpuAbiOverride = cpuAbiOverride;
9905
9906        if (DEBUG_ABI_SELECTION) {
9907            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9908                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9909                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9910        }
9911
9912        // Push the derived path down into PackageSettings so we know what to
9913        // clean up at uninstall time.
9914        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9915
9916        if (DEBUG_ABI_SELECTION) {
9917            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9918                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9919                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9920        }
9921
9922        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9923        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9924            // We don't do this here during boot because we can do it all
9925            // at once after scanning all existing packages.
9926            //
9927            // We also do this *before* we perform dexopt on this package, so that
9928            // we can avoid redundant dexopts, and also to make sure we've got the
9929            // code and package path correct.
9930            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9931        }
9932
9933        if (mFactoryTest && pkg.requestedPermissions.contains(
9934                android.Manifest.permission.FACTORY_TEST)) {
9935            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9936        }
9937
9938        if (isSystemApp(pkg)) {
9939            pkgSetting.isOrphaned = true;
9940        }
9941
9942        // Take care of first install / last update times.
9943        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9944        if (currentTime != 0) {
9945            if (pkgSetting.firstInstallTime == 0) {
9946                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9947            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9948                pkgSetting.lastUpdateTime = currentTime;
9949            }
9950        } else if (pkgSetting.firstInstallTime == 0) {
9951            // We need *something*.  Take time time stamp of the file.
9952            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9953        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9954            if (scanFileTime != pkgSetting.timeStamp) {
9955                // A package on the system image has changed; consider this
9956                // to be an update.
9957                pkgSetting.lastUpdateTime = scanFileTime;
9958            }
9959        }
9960        pkgSetting.setTimeStamp(scanFileTime);
9961
9962        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9963            if (nonMutatedPs != null) {
9964                synchronized (mPackages) {
9965                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9966                }
9967            }
9968        } else {
9969            final int userId = user == null ? 0 : user.getIdentifier();
9970            // Modify state for the given package setting
9971            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9972                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9973            if (pkgSetting.getInstantApp(userId)) {
9974                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9975            }
9976        }
9977        return pkg;
9978    }
9979
9980    /**
9981     * Applies policy to the parsed package based upon the given policy flags.
9982     * Ensures the package is in a good state.
9983     * <p>
9984     * Implementation detail: This method must NOT have any side effect. It would
9985     * ideally be static, but, it requires locks to read system state.
9986     */
9987    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9988        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9989            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9990            if (pkg.applicationInfo.isDirectBootAware()) {
9991                // we're direct boot aware; set for all components
9992                for (PackageParser.Service s : pkg.services) {
9993                    s.info.encryptionAware = s.info.directBootAware = true;
9994                }
9995                for (PackageParser.Provider p : pkg.providers) {
9996                    p.info.encryptionAware = p.info.directBootAware = true;
9997                }
9998                for (PackageParser.Activity a : pkg.activities) {
9999                    a.info.encryptionAware = a.info.directBootAware = true;
10000                }
10001                for (PackageParser.Activity r : pkg.receivers) {
10002                    r.info.encryptionAware = r.info.directBootAware = true;
10003                }
10004            }
10005        } else {
10006            // Only allow system apps to be flagged as core apps.
10007            pkg.coreApp = false;
10008            // clear flags not applicable to regular apps
10009            pkg.applicationInfo.privateFlags &=
10010                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10011            pkg.applicationInfo.privateFlags &=
10012                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10013        }
10014        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10015
10016        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10017            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10018        }
10019
10020        if (!isSystemApp(pkg)) {
10021            // Only system apps can use these features.
10022            pkg.mOriginalPackages = null;
10023            pkg.mRealPackage = null;
10024            pkg.mAdoptPermissions = null;
10025        }
10026    }
10027
10028    /**
10029     * Asserts the parsed package is valid according to the given policy. If the
10030     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10031     * <p>
10032     * Implementation detail: This method must NOT have any side effects. It would
10033     * ideally be static, but, it requires locks to read system state.
10034     *
10035     * @throws PackageManagerException If the package fails any of the validation checks
10036     */
10037    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10038            throws PackageManagerException {
10039        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10040            assertCodePolicy(pkg);
10041        }
10042
10043        if (pkg.applicationInfo.getCodePath() == null ||
10044                pkg.applicationInfo.getResourcePath() == null) {
10045            // Bail out. The resource and code paths haven't been set.
10046            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10047                    "Code and resource paths haven't been set correctly");
10048        }
10049
10050        // Make sure we're not adding any bogus keyset info
10051        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10052        ksms.assertScannedPackageValid(pkg);
10053
10054        synchronized (mPackages) {
10055            // The special "android" package can only be defined once
10056            if (pkg.packageName.equals("android")) {
10057                if (mAndroidApplication != null) {
10058                    Slog.w(TAG, "*************************************************");
10059                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10060                    Slog.w(TAG, " codePath=" + pkg.codePath);
10061                    Slog.w(TAG, "*************************************************");
10062                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10063                            "Core android package being redefined.  Skipping.");
10064                }
10065            }
10066
10067            // A package name must be unique; don't allow duplicates
10068            if (mPackages.containsKey(pkg.packageName)) {
10069                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10070                        "Application package " + pkg.packageName
10071                        + " already installed.  Skipping duplicate.");
10072            }
10073
10074            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10075                // Static libs have a synthetic package name containing the version
10076                // but we still want the base name to be unique.
10077                if (mPackages.containsKey(pkg.manifestPackageName)) {
10078                    throw new PackageManagerException(
10079                            "Duplicate static shared lib provider package");
10080                }
10081
10082                // Static shared libraries should have at least O target SDK
10083                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10084                    throw new PackageManagerException(
10085                            "Packages declaring static-shared libs must target O SDK or higher");
10086                }
10087
10088                // Package declaring static a shared lib cannot be instant apps
10089                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10090                    throw new PackageManagerException(
10091                            "Packages declaring static-shared libs cannot be instant apps");
10092                }
10093
10094                // Package declaring static a shared lib cannot be renamed since the package
10095                // name is synthetic and apps can't code around package manager internals.
10096                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10097                    throw new PackageManagerException(
10098                            "Packages declaring static-shared libs cannot be renamed");
10099                }
10100
10101                // Package declaring static a shared lib cannot declare child packages
10102                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10103                    throw new PackageManagerException(
10104                            "Packages declaring static-shared libs cannot have child packages");
10105                }
10106
10107                // Package declaring static a shared lib cannot declare dynamic libs
10108                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10109                    throw new PackageManagerException(
10110                            "Packages declaring static-shared libs cannot declare dynamic libs");
10111                }
10112
10113                // Package declaring static a shared lib cannot declare shared users
10114                if (pkg.mSharedUserId != null) {
10115                    throw new PackageManagerException(
10116                            "Packages declaring static-shared libs cannot declare shared users");
10117                }
10118
10119                // Static shared libs cannot declare activities
10120                if (!pkg.activities.isEmpty()) {
10121                    throw new PackageManagerException(
10122                            "Static shared libs cannot declare activities");
10123                }
10124
10125                // Static shared libs cannot declare services
10126                if (!pkg.services.isEmpty()) {
10127                    throw new PackageManagerException(
10128                            "Static shared libs cannot declare services");
10129                }
10130
10131                // Static shared libs cannot declare providers
10132                if (!pkg.providers.isEmpty()) {
10133                    throw new PackageManagerException(
10134                            "Static shared libs cannot declare content providers");
10135                }
10136
10137                // Static shared libs cannot declare receivers
10138                if (!pkg.receivers.isEmpty()) {
10139                    throw new PackageManagerException(
10140                            "Static shared libs cannot declare broadcast receivers");
10141                }
10142
10143                // Static shared libs cannot declare permission groups
10144                if (!pkg.permissionGroups.isEmpty()) {
10145                    throw new PackageManagerException(
10146                            "Static shared libs cannot declare permission groups");
10147                }
10148
10149                // Static shared libs cannot declare permissions
10150                if (!pkg.permissions.isEmpty()) {
10151                    throw new PackageManagerException(
10152                            "Static shared libs cannot declare permissions");
10153                }
10154
10155                // Static shared libs cannot declare protected broadcasts
10156                if (pkg.protectedBroadcasts != null) {
10157                    throw new PackageManagerException(
10158                            "Static shared libs cannot declare protected broadcasts");
10159                }
10160
10161                // Static shared libs cannot be overlay targets
10162                if (pkg.mOverlayTarget != null) {
10163                    throw new PackageManagerException(
10164                            "Static shared libs cannot be overlay targets");
10165                }
10166
10167                // The version codes must be ordered as lib versions
10168                int minVersionCode = Integer.MIN_VALUE;
10169                int maxVersionCode = Integer.MAX_VALUE;
10170
10171                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10172                        pkg.staticSharedLibName);
10173                if (versionedLib != null) {
10174                    final int versionCount = versionedLib.size();
10175                    for (int i = 0; i < versionCount; i++) {
10176                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10177                        // TODO: We will change version code to long, so in the new API it is long
10178                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
10179                                .getVersionCode();
10180                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10181                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10182                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10183                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10184                        } else {
10185                            minVersionCode = maxVersionCode = libVersionCode;
10186                            break;
10187                        }
10188                    }
10189                }
10190                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10191                    throw new PackageManagerException("Static shared"
10192                            + " lib version codes must be ordered as lib versions");
10193                }
10194            }
10195
10196            // Only privileged apps and updated privileged apps can add child packages.
10197            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10198                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10199                    throw new PackageManagerException("Only privileged apps can add child "
10200                            + "packages. Ignoring package " + pkg.packageName);
10201                }
10202                final int childCount = pkg.childPackages.size();
10203                for (int i = 0; i < childCount; i++) {
10204                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10205                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10206                            childPkg.packageName)) {
10207                        throw new PackageManagerException("Can't override child of "
10208                                + "another disabled app. Ignoring package " + pkg.packageName);
10209                    }
10210                }
10211            }
10212
10213            // If we're only installing presumed-existing packages, require that the
10214            // scanned APK is both already known and at the path previously established
10215            // for it.  Previously unknown packages we pick up normally, but if we have an
10216            // a priori expectation about this package's install presence, enforce it.
10217            // With a singular exception for new system packages. When an OTA contains
10218            // a new system package, we allow the codepath to change from a system location
10219            // to the user-installed location. If we don't allow this change, any newer,
10220            // user-installed version of the application will be ignored.
10221            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10222                if (mExpectingBetter.containsKey(pkg.packageName)) {
10223                    logCriticalInfo(Log.WARN,
10224                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10225                } else {
10226                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10227                    if (known != null) {
10228                        if (DEBUG_PACKAGE_SCANNING) {
10229                            Log.d(TAG, "Examining " + pkg.codePath
10230                                    + " and requiring known paths " + known.codePathString
10231                                    + " & " + known.resourcePathString);
10232                        }
10233                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10234                                || !pkg.applicationInfo.getResourcePath().equals(
10235                                        known.resourcePathString)) {
10236                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10237                                    "Application package " + pkg.packageName
10238                                    + " found at " + pkg.applicationInfo.getCodePath()
10239                                    + " but expected at " + known.codePathString
10240                                    + "; ignoring.");
10241                        }
10242                    }
10243                }
10244            }
10245
10246            // Verify that this new package doesn't have any content providers
10247            // that conflict with existing packages.  Only do this if the
10248            // package isn't already installed, since we don't want to break
10249            // things that are installed.
10250            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10251                final int N = pkg.providers.size();
10252                int i;
10253                for (i=0; i<N; i++) {
10254                    PackageParser.Provider p = pkg.providers.get(i);
10255                    if (p.info.authority != null) {
10256                        String names[] = p.info.authority.split(";");
10257                        for (int j = 0; j < names.length; j++) {
10258                            if (mProvidersByAuthority.containsKey(names[j])) {
10259                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10260                                final String otherPackageName =
10261                                        ((other != null && other.getComponentName() != null) ?
10262                                                other.getComponentName().getPackageName() : "?");
10263                                throw new PackageManagerException(
10264                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10265                                        "Can't install because provider name " + names[j]
10266                                                + " (in package " + pkg.applicationInfo.packageName
10267                                                + ") is already used by " + otherPackageName);
10268                            }
10269                        }
10270                    }
10271                }
10272            }
10273        }
10274    }
10275
10276    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10277            int type, String declaringPackageName, int declaringVersionCode) {
10278        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10279        if (versionedLib == null) {
10280            versionedLib = new SparseArray<>();
10281            mSharedLibraries.put(name, versionedLib);
10282            if (type == SharedLibraryInfo.TYPE_STATIC) {
10283                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10284            }
10285        } else if (versionedLib.indexOfKey(version) >= 0) {
10286            return false;
10287        }
10288        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10289                version, type, declaringPackageName, declaringVersionCode);
10290        versionedLib.put(version, libEntry);
10291        return true;
10292    }
10293
10294    private boolean removeSharedLibraryLPw(String name, int version) {
10295        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10296        if (versionedLib == null) {
10297            return false;
10298        }
10299        final int libIdx = versionedLib.indexOfKey(version);
10300        if (libIdx < 0) {
10301            return false;
10302        }
10303        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10304        versionedLib.remove(version);
10305        if (versionedLib.size() <= 0) {
10306            mSharedLibraries.remove(name);
10307            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10308                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10309                        .getPackageName());
10310            }
10311        }
10312        return true;
10313    }
10314
10315    /**
10316     * Adds a scanned package to the system. When this method is finished, the package will
10317     * be available for query, resolution, etc...
10318     */
10319    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10320            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10321        final String pkgName = pkg.packageName;
10322        if (mCustomResolverComponentName != null &&
10323                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10324            setUpCustomResolverActivity(pkg);
10325        }
10326
10327        if (pkg.packageName.equals("android")) {
10328            synchronized (mPackages) {
10329                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10330                    // Set up information for our fall-back user intent resolution activity.
10331                    mPlatformPackage = pkg;
10332                    pkg.mVersionCode = mSdkVersion;
10333                    mAndroidApplication = pkg.applicationInfo;
10334                    if (!mResolverReplaced) {
10335                        mResolveActivity.applicationInfo = mAndroidApplication;
10336                        mResolveActivity.name = ResolverActivity.class.getName();
10337                        mResolveActivity.packageName = mAndroidApplication.packageName;
10338                        mResolveActivity.processName = "system:ui";
10339                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10340                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10341                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10342                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10343                        mResolveActivity.exported = true;
10344                        mResolveActivity.enabled = true;
10345                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10346                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10347                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10348                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10349                                | ActivityInfo.CONFIG_ORIENTATION
10350                                | ActivityInfo.CONFIG_KEYBOARD
10351                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10352                        mResolveInfo.activityInfo = mResolveActivity;
10353                        mResolveInfo.priority = 0;
10354                        mResolveInfo.preferredOrder = 0;
10355                        mResolveInfo.match = 0;
10356                        mResolveComponentName = new ComponentName(
10357                                mAndroidApplication.packageName, mResolveActivity.name);
10358                    }
10359                }
10360            }
10361        }
10362
10363        ArrayList<PackageParser.Package> clientLibPkgs = null;
10364        // writer
10365        synchronized (mPackages) {
10366            boolean hasStaticSharedLibs = false;
10367
10368            // Any app can add new static shared libraries
10369            if (pkg.staticSharedLibName != null) {
10370                // Static shared libs don't allow renaming as they have synthetic package
10371                // names to allow install of multiple versions, so use name from manifest.
10372                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10373                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10374                        pkg.manifestPackageName, pkg.mVersionCode)) {
10375                    hasStaticSharedLibs = true;
10376                } else {
10377                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10378                                + pkg.staticSharedLibName + " already exists; skipping");
10379                }
10380                // Static shared libs cannot be updated once installed since they
10381                // use synthetic package name which includes the version code, so
10382                // not need to update other packages's shared lib dependencies.
10383            }
10384
10385            if (!hasStaticSharedLibs
10386                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10387                // Only system apps can add new dynamic shared libraries.
10388                if (pkg.libraryNames != null) {
10389                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10390                        String name = pkg.libraryNames.get(i);
10391                        boolean allowed = false;
10392                        if (pkg.isUpdatedSystemApp()) {
10393                            // New library entries can only be added through the
10394                            // system image.  This is important to get rid of a lot
10395                            // of nasty edge cases: for example if we allowed a non-
10396                            // system update of the app to add a library, then uninstalling
10397                            // the update would make the library go away, and assumptions
10398                            // we made such as through app install filtering would now
10399                            // have allowed apps on the device which aren't compatible
10400                            // with it.  Better to just have the restriction here, be
10401                            // conservative, and create many fewer cases that can negatively
10402                            // impact the user experience.
10403                            final PackageSetting sysPs = mSettings
10404                                    .getDisabledSystemPkgLPr(pkg.packageName);
10405                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10406                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10407                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10408                                        allowed = true;
10409                                        break;
10410                                    }
10411                                }
10412                            }
10413                        } else {
10414                            allowed = true;
10415                        }
10416                        if (allowed) {
10417                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10418                                    SharedLibraryInfo.VERSION_UNDEFINED,
10419                                    SharedLibraryInfo.TYPE_DYNAMIC,
10420                                    pkg.packageName, pkg.mVersionCode)) {
10421                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10422                                        + name + " already exists; skipping");
10423                            }
10424                        } else {
10425                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10426                                    + name + " that is not declared on system image; skipping");
10427                        }
10428                    }
10429
10430                    if ((scanFlags & SCAN_BOOTING) == 0) {
10431                        // If we are not booting, we need to update any applications
10432                        // that are clients of our shared library.  If we are booting,
10433                        // this will all be done once the scan is complete.
10434                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10435                    }
10436                }
10437            }
10438        }
10439
10440        if ((scanFlags & SCAN_BOOTING) != 0) {
10441            // No apps can run during boot scan, so they don't need to be frozen
10442        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10443            // Caller asked to not kill app, so it's probably not frozen
10444        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10445            // Caller asked us to ignore frozen check for some reason; they
10446            // probably didn't know the package name
10447        } else {
10448            // We're doing major surgery on this package, so it better be frozen
10449            // right now to keep it from launching
10450            checkPackageFrozen(pkgName);
10451        }
10452
10453        // Also need to kill any apps that are dependent on the library.
10454        if (clientLibPkgs != null) {
10455            for (int i=0; i<clientLibPkgs.size(); i++) {
10456                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10457                killApplication(clientPkg.applicationInfo.packageName,
10458                        clientPkg.applicationInfo.uid, "update lib");
10459            }
10460        }
10461
10462        // writer
10463        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10464
10465        synchronized (mPackages) {
10466            // We don't expect installation to fail beyond this point
10467
10468            // Add the new setting to mSettings
10469            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10470            // Add the new setting to mPackages
10471            mPackages.put(pkg.applicationInfo.packageName, pkg);
10472            // Make sure we don't accidentally delete its data.
10473            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10474            while (iter.hasNext()) {
10475                PackageCleanItem item = iter.next();
10476                if (pkgName.equals(item.packageName)) {
10477                    iter.remove();
10478                }
10479            }
10480
10481            // Add the package's KeySets to the global KeySetManagerService
10482            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10483            ksms.addScannedPackageLPw(pkg);
10484
10485            int N = pkg.providers.size();
10486            StringBuilder r = null;
10487            int i;
10488            for (i=0; i<N; i++) {
10489                PackageParser.Provider p = pkg.providers.get(i);
10490                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10491                        p.info.processName);
10492                mProviders.addProvider(p);
10493                p.syncable = p.info.isSyncable;
10494                if (p.info.authority != null) {
10495                    String names[] = p.info.authority.split(";");
10496                    p.info.authority = null;
10497                    for (int j = 0; j < names.length; j++) {
10498                        if (j == 1 && p.syncable) {
10499                            // We only want the first authority for a provider to possibly be
10500                            // syncable, so if we already added this provider using a different
10501                            // authority clear the syncable flag. We copy the provider before
10502                            // changing it because the mProviders object contains a reference
10503                            // to a provider that we don't want to change.
10504                            // Only do this for the second authority since the resulting provider
10505                            // object can be the same for all future authorities for this provider.
10506                            p = new PackageParser.Provider(p);
10507                            p.syncable = false;
10508                        }
10509                        if (!mProvidersByAuthority.containsKey(names[j])) {
10510                            mProvidersByAuthority.put(names[j], p);
10511                            if (p.info.authority == null) {
10512                                p.info.authority = names[j];
10513                            } else {
10514                                p.info.authority = p.info.authority + ";" + names[j];
10515                            }
10516                            if (DEBUG_PACKAGE_SCANNING) {
10517                                if (chatty)
10518                                    Log.d(TAG, "Registered content provider: " + names[j]
10519                                            + ", className = " + p.info.name + ", isSyncable = "
10520                                            + p.info.isSyncable);
10521                            }
10522                        } else {
10523                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10524                            Slog.w(TAG, "Skipping provider name " + names[j] +
10525                                    " (in package " + pkg.applicationInfo.packageName +
10526                                    "): name already used by "
10527                                    + ((other != null && other.getComponentName() != null)
10528                                            ? other.getComponentName().getPackageName() : "?"));
10529                        }
10530                    }
10531                }
10532                if (chatty) {
10533                    if (r == null) {
10534                        r = new StringBuilder(256);
10535                    } else {
10536                        r.append(' ');
10537                    }
10538                    r.append(p.info.name);
10539                }
10540            }
10541            if (r != null) {
10542                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10543            }
10544
10545            N = pkg.services.size();
10546            r = null;
10547            for (i=0; i<N; i++) {
10548                PackageParser.Service s = pkg.services.get(i);
10549                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10550                        s.info.processName);
10551                mServices.addService(s);
10552                if (chatty) {
10553                    if (r == null) {
10554                        r = new StringBuilder(256);
10555                    } else {
10556                        r.append(' ');
10557                    }
10558                    r.append(s.info.name);
10559                }
10560            }
10561            if (r != null) {
10562                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10563            }
10564
10565            N = pkg.receivers.size();
10566            r = null;
10567            for (i=0; i<N; i++) {
10568                PackageParser.Activity a = pkg.receivers.get(i);
10569                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10570                        a.info.processName);
10571                mReceivers.addActivity(a, "receiver");
10572                if (chatty) {
10573                    if (r == null) {
10574                        r = new StringBuilder(256);
10575                    } else {
10576                        r.append(' ');
10577                    }
10578                    r.append(a.info.name);
10579                }
10580            }
10581            if (r != null) {
10582                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10583            }
10584
10585            N = pkg.activities.size();
10586            r = null;
10587            for (i=0; i<N; i++) {
10588                PackageParser.Activity a = pkg.activities.get(i);
10589                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10590                        a.info.processName);
10591                mActivities.addActivity(a, "activity");
10592                if (chatty) {
10593                    if (r == null) {
10594                        r = new StringBuilder(256);
10595                    } else {
10596                        r.append(' ');
10597                    }
10598                    r.append(a.info.name);
10599                }
10600            }
10601            if (r != null) {
10602                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10603            }
10604
10605            N = pkg.permissionGroups.size();
10606            r = null;
10607            for (i=0; i<N; i++) {
10608                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10609                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10610                final String curPackageName = cur == null ? null : cur.info.packageName;
10611                // Dont allow ephemeral apps to define new permission groups.
10612                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10613                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10614                            + pg.info.packageName
10615                            + " ignored: instant apps cannot define new permission groups.");
10616                    continue;
10617                }
10618                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10619                if (cur == null || isPackageUpdate) {
10620                    mPermissionGroups.put(pg.info.name, pg);
10621                    if (chatty) {
10622                        if (r == null) {
10623                            r = new StringBuilder(256);
10624                        } else {
10625                            r.append(' ');
10626                        }
10627                        if (isPackageUpdate) {
10628                            r.append("UPD:");
10629                        }
10630                        r.append(pg.info.name);
10631                    }
10632                } else {
10633                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10634                            + pg.info.packageName + " ignored: original from "
10635                            + cur.info.packageName);
10636                    if (chatty) {
10637                        if (r == null) {
10638                            r = new StringBuilder(256);
10639                        } else {
10640                            r.append(' ');
10641                        }
10642                        r.append("DUP:");
10643                        r.append(pg.info.name);
10644                    }
10645                }
10646            }
10647            if (r != null) {
10648                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10649            }
10650
10651            N = pkg.permissions.size();
10652            r = null;
10653            for (i=0; i<N; i++) {
10654                PackageParser.Permission p = pkg.permissions.get(i);
10655
10656                // Dont allow ephemeral apps to define new permissions.
10657                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10658                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10659                            + p.info.packageName
10660                            + " ignored: instant apps cannot define new permissions.");
10661                    continue;
10662                }
10663
10664                // Assume by default that we did not install this permission into the system.
10665                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10666
10667                // Now that permission groups have a special meaning, we ignore permission
10668                // groups for legacy apps to prevent unexpected behavior. In particular,
10669                // permissions for one app being granted to someone just because they happen
10670                // to be in a group defined by another app (before this had no implications).
10671                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10672                    p.group = mPermissionGroups.get(p.info.group);
10673                    // Warn for a permission in an unknown group.
10674                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
10675                        Slog.i(TAG, "Permission " + p.info.name + " from package "
10676                                + p.info.packageName + " in an unknown group " + p.info.group);
10677                    }
10678                }
10679
10680                ArrayMap<String, BasePermission> permissionMap =
10681                        p.tree ? mSettings.mPermissionTrees
10682                                : mSettings.mPermissions;
10683                BasePermission bp = permissionMap.get(p.info.name);
10684
10685                // Allow system apps to redefine non-system permissions
10686                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10687                    final boolean currentOwnerIsSystem = (bp.perm != null
10688                            && isSystemApp(bp.perm.owner));
10689                    if (isSystemApp(p.owner)) {
10690                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10691                            // It's a built-in permission and no owner, take ownership now
10692                            bp.packageSetting = pkgSetting;
10693                            bp.perm = p;
10694                            bp.uid = pkg.applicationInfo.uid;
10695                            bp.sourcePackage = p.info.packageName;
10696                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10697                        } else if (!currentOwnerIsSystem) {
10698                            String msg = "New decl " + p.owner + " of permission  "
10699                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10700                            reportSettingsProblem(Log.WARN, msg);
10701                            bp = null;
10702                        }
10703                    }
10704                }
10705
10706                if (bp == null) {
10707                    bp = new BasePermission(p.info.name, p.info.packageName,
10708                            BasePermission.TYPE_NORMAL);
10709                    permissionMap.put(p.info.name, bp);
10710                }
10711
10712                if (bp.perm == null) {
10713                    if (bp.sourcePackage == null
10714                            || bp.sourcePackage.equals(p.info.packageName)) {
10715                        BasePermission tree = findPermissionTreeLP(p.info.name);
10716                        if (tree == null
10717                                || tree.sourcePackage.equals(p.info.packageName)) {
10718                            bp.packageSetting = pkgSetting;
10719                            bp.perm = p;
10720                            bp.uid = pkg.applicationInfo.uid;
10721                            bp.sourcePackage = p.info.packageName;
10722                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10723                            if (chatty) {
10724                                if (r == null) {
10725                                    r = new StringBuilder(256);
10726                                } else {
10727                                    r.append(' ');
10728                                }
10729                                r.append(p.info.name);
10730                            }
10731                        } else {
10732                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10733                                    + p.info.packageName + " ignored: base tree "
10734                                    + tree.name + " is from package "
10735                                    + tree.sourcePackage);
10736                        }
10737                    } else {
10738                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10739                                + p.info.packageName + " ignored: original from "
10740                                + bp.sourcePackage);
10741                    }
10742                } else if (chatty) {
10743                    if (r == null) {
10744                        r = new StringBuilder(256);
10745                    } else {
10746                        r.append(' ');
10747                    }
10748                    r.append("DUP:");
10749                    r.append(p.info.name);
10750                }
10751                if (bp.perm == p) {
10752                    bp.protectionLevel = p.info.protectionLevel;
10753                }
10754            }
10755
10756            if (r != null) {
10757                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10758            }
10759
10760            N = pkg.instrumentation.size();
10761            r = null;
10762            for (i=0; i<N; i++) {
10763                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10764                a.info.packageName = pkg.applicationInfo.packageName;
10765                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10766                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10767                a.info.splitNames = pkg.splitNames;
10768                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10769                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10770                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10771                a.info.dataDir = pkg.applicationInfo.dataDir;
10772                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10773                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10774                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10775                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10776                mInstrumentation.put(a.getComponentName(), a);
10777                if (chatty) {
10778                    if (r == null) {
10779                        r = new StringBuilder(256);
10780                    } else {
10781                        r.append(' ');
10782                    }
10783                    r.append(a.info.name);
10784                }
10785            }
10786            if (r != null) {
10787                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10788            }
10789
10790            if (pkg.protectedBroadcasts != null) {
10791                N = pkg.protectedBroadcasts.size();
10792                for (i=0; i<N; i++) {
10793                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10794                }
10795            }
10796        }
10797
10798        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10799    }
10800
10801    /**
10802     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10803     * is derived purely on the basis of the contents of {@code scanFile} and
10804     * {@code cpuAbiOverride}.
10805     *
10806     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10807     */
10808    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10809                                 String cpuAbiOverride, boolean extractLibs,
10810                                 File appLib32InstallDir)
10811            throws PackageManagerException {
10812        // Give ourselves some initial paths; we'll come back for another
10813        // pass once we've determined ABI below.
10814        setNativeLibraryPaths(pkg, appLib32InstallDir);
10815
10816        // We would never need to extract libs for forward-locked and external packages,
10817        // since the container service will do it for us. We shouldn't attempt to
10818        // extract libs from system app when it was not updated.
10819        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10820                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10821            extractLibs = false;
10822        }
10823
10824        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10825        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10826
10827        NativeLibraryHelper.Handle handle = null;
10828        try {
10829            handle = NativeLibraryHelper.Handle.create(pkg);
10830            // TODO(multiArch): This can be null for apps that didn't go through the
10831            // usual installation process. We can calculate it again, like we
10832            // do during install time.
10833            //
10834            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10835            // unnecessary.
10836            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10837
10838            // Null out the abis so that they can be recalculated.
10839            pkg.applicationInfo.primaryCpuAbi = null;
10840            pkg.applicationInfo.secondaryCpuAbi = null;
10841            if (isMultiArch(pkg.applicationInfo)) {
10842                // Warn if we've set an abiOverride for multi-lib packages..
10843                // By definition, we need to copy both 32 and 64 bit libraries for
10844                // such packages.
10845                if (pkg.cpuAbiOverride != null
10846                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10847                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10848                }
10849
10850                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10851                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10852                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10853                    if (extractLibs) {
10854                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10855                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10856                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10857                                useIsaSpecificSubdirs);
10858                    } else {
10859                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10860                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10861                    }
10862                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10863                }
10864
10865                maybeThrowExceptionForMultiArchCopy(
10866                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10867
10868                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10869                    if (extractLibs) {
10870                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10871                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10872                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10873                                useIsaSpecificSubdirs);
10874                    } else {
10875                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10876                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10877                    }
10878                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10879                }
10880
10881                maybeThrowExceptionForMultiArchCopy(
10882                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10883
10884                if (abi64 >= 0) {
10885                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10886                }
10887
10888                if (abi32 >= 0) {
10889                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10890                    if (abi64 >= 0) {
10891                        if (pkg.use32bitAbi) {
10892                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10893                            pkg.applicationInfo.primaryCpuAbi = abi;
10894                        } else {
10895                            pkg.applicationInfo.secondaryCpuAbi = abi;
10896                        }
10897                    } else {
10898                        pkg.applicationInfo.primaryCpuAbi = abi;
10899                    }
10900                }
10901
10902            } else {
10903                String[] abiList = (cpuAbiOverride != null) ?
10904                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10905
10906                // Enable gross and lame hacks for apps that are built with old
10907                // SDK tools. We must scan their APKs for renderscript bitcode and
10908                // not launch them if it's present. Don't bother checking on devices
10909                // that don't have 64 bit support.
10910                boolean needsRenderScriptOverride = false;
10911                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10912                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10913                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10914                    needsRenderScriptOverride = true;
10915                }
10916
10917                final int copyRet;
10918                if (extractLibs) {
10919                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10920                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10921                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10922                } else {
10923                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10924                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10925                }
10926                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10927
10928                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10929                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10930                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10931                }
10932
10933                if (copyRet >= 0) {
10934                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10935                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10936                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10937                } else if (needsRenderScriptOverride) {
10938                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10939                }
10940            }
10941        } catch (IOException ioe) {
10942            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10943        } finally {
10944            IoUtils.closeQuietly(handle);
10945        }
10946
10947        // Now that we've calculated the ABIs and determined if it's an internal app,
10948        // we will go ahead and populate the nativeLibraryPath.
10949        setNativeLibraryPaths(pkg, appLib32InstallDir);
10950    }
10951
10952    /**
10953     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10954     * i.e, so that all packages can be run inside a single process if required.
10955     *
10956     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10957     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10958     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10959     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10960     * updating a package that belongs to a shared user.
10961     *
10962     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10963     * adds unnecessary complexity.
10964     */
10965    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10966            PackageParser.Package scannedPackage) {
10967        String requiredInstructionSet = null;
10968        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10969            requiredInstructionSet = VMRuntime.getInstructionSet(
10970                     scannedPackage.applicationInfo.primaryCpuAbi);
10971        }
10972
10973        PackageSetting requirer = null;
10974        for (PackageSetting ps : packagesForUser) {
10975            // If packagesForUser contains scannedPackage, we skip it. This will happen
10976            // when scannedPackage is an update of an existing package. Without this check,
10977            // we will never be able to change the ABI of any package belonging to a shared
10978            // user, even if it's compatible with other packages.
10979            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10980                if (ps.primaryCpuAbiString == null) {
10981                    continue;
10982                }
10983
10984                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10985                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10986                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10987                    // this but there's not much we can do.
10988                    String errorMessage = "Instruction set mismatch, "
10989                            + ((requirer == null) ? "[caller]" : requirer)
10990                            + " requires " + requiredInstructionSet + " whereas " + ps
10991                            + " requires " + instructionSet;
10992                    Slog.w(TAG, errorMessage);
10993                }
10994
10995                if (requiredInstructionSet == null) {
10996                    requiredInstructionSet = instructionSet;
10997                    requirer = ps;
10998                }
10999            }
11000        }
11001
11002        if (requiredInstructionSet != null) {
11003            String adjustedAbi;
11004            if (requirer != null) {
11005                // requirer != null implies that either scannedPackage was null or that scannedPackage
11006                // did not require an ABI, in which case we have to adjust scannedPackage to match
11007                // the ABI of the set (which is the same as requirer's ABI)
11008                adjustedAbi = requirer.primaryCpuAbiString;
11009                if (scannedPackage != null) {
11010                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11011                }
11012            } else {
11013                // requirer == null implies that we're updating all ABIs in the set to
11014                // match scannedPackage.
11015                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11016            }
11017
11018            for (PackageSetting ps : packagesForUser) {
11019                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11020                    if (ps.primaryCpuAbiString != null) {
11021                        continue;
11022                    }
11023
11024                    ps.primaryCpuAbiString = adjustedAbi;
11025                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11026                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11027                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11028                        if (DEBUG_ABI_SELECTION) {
11029                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11030                                    + " (requirer="
11031                                    + (requirer != null ? requirer.pkg : "null")
11032                                    + ", scannedPackage="
11033                                    + (scannedPackage != null ? scannedPackage : "null")
11034                                    + ")");
11035                        }
11036                        try {
11037                            mInstaller.rmdex(ps.codePathString,
11038                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11039                        } catch (InstallerException ignored) {
11040                        }
11041                    }
11042                }
11043            }
11044        }
11045    }
11046
11047    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11048        synchronized (mPackages) {
11049            mResolverReplaced = true;
11050            // Set up information for custom user intent resolution activity.
11051            mResolveActivity.applicationInfo = pkg.applicationInfo;
11052            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11053            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11054            mResolveActivity.processName = pkg.applicationInfo.packageName;
11055            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11056            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11057                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11058            mResolveActivity.theme = 0;
11059            mResolveActivity.exported = true;
11060            mResolveActivity.enabled = true;
11061            mResolveInfo.activityInfo = mResolveActivity;
11062            mResolveInfo.priority = 0;
11063            mResolveInfo.preferredOrder = 0;
11064            mResolveInfo.match = 0;
11065            mResolveComponentName = mCustomResolverComponentName;
11066            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11067                    mResolveComponentName);
11068        }
11069    }
11070
11071    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11072        if (installerActivity == null) {
11073            if (DEBUG_EPHEMERAL) {
11074                Slog.d(TAG, "Clear ephemeral installer activity");
11075            }
11076            mInstantAppInstallerActivity = null;
11077            return;
11078        }
11079
11080        if (DEBUG_EPHEMERAL) {
11081            Slog.d(TAG, "Set ephemeral installer activity: "
11082                    + installerActivity.getComponentName());
11083        }
11084        // Set up information for ephemeral installer activity
11085        mInstantAppInstallerActivity = installerActivity;
11086        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11087                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11088        mInstantAppInstallerActivity.exported = true;
11089        mInstantAppInstallerActivity.enabled = true;
11090        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11091        mInstantAppInstallerInfo.priority = 0;
11092        mInstantAppInstallerInfo.preferredOrder = 1;
11093        mInstantAppInstallerInfo.isDefault = true;
11094        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11095                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11096    }
11097
11098    private static String calculateBundledApkRoot(final String codePathString) {
11099        final File codePath = new File(codePathString);
11100        final File codeRoot;
11101        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11102            codeRoot = Environment.getRootDirectory();
11103        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11104            codeRoot = Environment.getOemDirectory();
11105        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11106            codeRoot = Environment.getVendorDirectory();
11107        } else {
11108            // Unrecognized code path; take its top real segment as the apk root:
11109            // e.g. /something/app/blah.apk => /something
11110            try {
11111                File f = codePath.getCanonicalFile();
11112                File parent = f.getParentFile();    // non-null because codePath is a file
11113                File tmp;
11114                while ((tmp = parent.getParentFile()) != null) {
11115                    f = parent;
11116                    parent = tmp;
11117                }
11118                codeRoot = f;
11119                Slog.w(TAG, "Unrecognized code path "
11120                        + codePath + " - using " + codeRoot);
11121            } catch (IOException e) {
11122                // Can't canonicalize the code path -- shenanigans?
11123                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11124                return Environment.getRootDirectory().getPath();
11125            }
11126        }
11127        return codeRoot.getPath();
11128    }
11129
11130    /**
11131     * Derive and set the location of native libraries for the given package,
11132     * which varies depending on where and how the package was installed.
11133     */
11134    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11135        final ApplicationInfo info = pkg.applicationInfo;
11136        final String codePath = pkg.codePath;
11137        final File codeFile = new File(codePath);
11138        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11139        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11140
11141        info.nativeLibraryRootDir = null;
11142        info.nativeLibraryRootRequiresIsa = false;
11143        info.nativeLibraryDir = null;
11144        info.secondaryNativeLibraryDir = null;
11145
11146        if (isApkFile(codeFile)) {
11147            // Monolithic install
11148            if (bundledApp) {
11149                // If "/system/lib64/apkname" exists, assume that is the per-package
11150                // native library directory to use; otherwise use "/system/lib/apkname".
11151                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11152                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11153                        getPrimaryInstructionSet(info));
11154
11155                // This is a bundled system app so choose the path based on the ABI.
11156                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11157                // is just the default path.
11158                final String apkName = deriveCodePathName(codePath);
11159                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11160                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11161                        apkName).getAbsolutePath();
11162
11163                if (info.secondaryCpuAbi != null) {
11164                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11165                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11166                            secondaryLibDir, apkName).getAbsolutePath();
11167                }
11168            } else if (asecApp) {
11169                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11170                        .getAbsolutePath();
11171            } else {
11172                final String apkName = deriveCodePathName(codePath);
11173                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11174                        .getAbsolutePath();
11175            }
11176
11177            info.nativeLibraryRootRequiresIsa = false;
11178            info.nativeLibraryDir = info.nativeLibraryRootDir;
11179        } else {
11180            // Cluster install
11181            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11182            info.nativeLibraryRootRequiresIsa = true;
11183
11184            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11185                    getPrimaryInstructionSet(info)).getAbsolutePath();
11186
11187            if (info.secondaryCpuAbi != null) {
11188                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11189                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11190            }
11191        }
11192    }
11193
11194    /**
11195     * Calculate the abis and roots for a bundled app. These can uniquely
11196     * be determined from the contents of the system partition, i.e whether
11197     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11198     * of this information, and instead assume that the system was built
11199     * sensibly.
11200     */
11201    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11202                                           PackageSetting pkgSetting) {
11203        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11204
11205        // If "/system/lib64/apkname" exists, assume that is the per-package
11206        // native library directory to use; otherwise use "/system/lib/apkname".
11207        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11208        setBundledAppAbi(pkg, apkRoot, apkName);
11209        // pkgSetting might be null during rescan following uninstall of updates
11210        // to a bundled app, so accommodate that possibility.  The settings in
11211        // that case will be established later from the parsed package.
11212        //
11213        // If the settings aren't null, sync them up with what we've just derived.
11214        // note that apkRoot isn't stored in the package settings.
11215        if (pkgSetting != null) {
11216            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11217            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11218        }
11219    }
11220
11221    /**
11222     * Deduces the ABI of a bundled app and sets the relevant fields on the
11223     * parsed pkg object.
11224     *
11225     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11226     *        under which system libraries are installed.
11227     * @param apkName the name of the installed package.
11228     */
11229    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11230        final File codeFile = new File(pkg.codePath);
11231
11232        final boolean has64BitLibs;
11233        final boolean has32BitLibs;
11234        if (isApkFile(codeFile)) {
11235            // Monolithic install
11236            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11237            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11238        } else {
11239            // Cluster install
11240            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11241            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11242                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11243                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11244                has64BitLibs = (new File(rootDir, isa)).exists();
11245            } else {
11246                has64BitLibs = false;
11247            }
11248            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11249                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11250                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11251                has32BitLibs = (new File(rootDir, isa)).exists();
11252            } else {
11253                has32BitLibs = false;
11254            }
11255        }
11256
11257        if (has64BitLibs && !has32BitLibs) {
11258            // The package has 64 bit libs, but not 32 bit libs. Its primary
11259            // ABI should be 64 bit. We can safely assume here that the bundled
11260            // native libraries correspond to the most preferred ABI in the list.
11261
11262            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11263            pkg.applicationInfo.secondaryCpuAbi = null;
11264        } else if (has32BitLibs && !has64BitLibs) {
11265            // The package has 32 bit libs but not 64 bit libs. Its primary
11266            // ABI should be 32 bit.
11267
11268            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11269            pkg.applicationInfo.secondaryCpuAbi = null;
11270        } else if (has32BitLibs && has64BitLibs) {
11271            // The application has both 64 and 32 bit bundled libraries. We check
11272            // here that the app declares multiArch support, and warn if it doesn't.
11273            //
11274            // We will be lenient here and record both ABIs. The primary will be the
11275            // ABI that's higher on the list, i.e, a device that's configured to prefer
11276            // 64 bit apps will see a 64 bit primary ABI,
11277
11278            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11279                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11280            }
11281
11282            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11283                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11284                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11285            } else {
11286                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11287                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11288            }
11289        } else {
11290            pkg.applicationInfo.primaryCpuAbi = null;
11291            pkg.applicationInfo.secondaryCpuAbi = null;
11292        }
11293    }
11294
11295    private void killApplication(String pkgName, int appId, String reason) {
11296        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11297    }
11298
11299    private void killApplication(String pkgName, int appId, int userId, String reason) {
11300        // Request the ActivityManager to kill the process(only for existing packages)
11301        // so that we do not end up in a confused state while the user is still using the older
11302        // version of the application while the new one gets installed.
11303        final long token = Binder.clearCallingIdentity();
11304        try {
11305            IActivityManager am = ActivityManager.getService();
11306            if (am != null) {
11307                try {
11308                    am.killApplication(pkgName, appId, userId, reason);
11309                } catch (RemoteException e) {
11310                }
11311            }
11312        } finally {
11313            Binder.restoreCallingIdentity(token);
11314        }
11315    }
11316
11317    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11318        // Remove the parent package setting
11319        PackageSetting ps = (PackageSetting) pkg.mExtras;
11320        if (ps != null) {
11321            removePackageLI(ps, chatty);
11322        }
11323        // Remove the child package setting
11324        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11325        for (int i = 0; i < childCount; i++) {
11326            PackageParser.Package childPkg = pkg.childPackages.get(i);
11327            ps = (PackageSetting) childPkg.mExtras;
11328            if (ps != null) {
11329                removePackageLI(ps, chatty);
11330            }
11331        }
11332    }
11333
11334    void removePackageLI(PackageSetting ps, boolean chatty) {
11335        if (DEBUG_INSTALL) {
11336            if (chatty)
11337                Log.d(TAG, "Removing package " + ps.name);
11338        }
11339
11340        // writer
11341        synchronized (mPackages) {
11342            mPackages.remove(ps.name);
11343            final PackageParser.Package pkg = ps.pkg;
11344            if (pkg != null) {
11345                cleanPackageDataStructuresLILPw(pkg, chatty);
11346            }
11347        }
11348    }
11349
11350    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11351        if (DEBUG_INSTALL) {
11352            if (chatty)
11353                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11354        }
11355
11356        // writer
11357        synchronized (mPackages) {
11358            // Remove the parent package
11359            mPackages.remove(pkg.applicationInfo.packageName);
11360            cleanPackageDataStructuresLILPw(pkg, chatty);
11361
11362            // Remove the child packages
11363            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11364            for (int i = 0; i < childCount; i++) {
11365                PackageParser.Package childPkg = pkg.childPackages.get(i);
11366                mPackages.remove(childPkg.applicationInfo.packageName);
11367                cleanPackageDataStructuresLILPw(childPkg, chatty);
11368            }
11369        }
11370    }
11371
11372    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11373        int N = pkg.providers.size();
11374        StringBuilder r = null;
11375        int i;
11376        for (i=0; i<N; i++) {
11377            PackageParser.Provider p = pkg.providers.get(i);
11378            mProviders.removeProvider(p);
11379            if (p.info.authority == null) {
11380
11381                /* There was another ContentProvider with this authority when
11382                 * this app was installed so this authority is null,
11383                 * Ignore it as we don't have to unregister the provider.
11384                 */
11385                continue;
11386            }
11387            String names[] = p.info.authority.split(";");
11388            for (int j = 0; j < names.length; j++) {
11389                if (mProvidersByAuthority.get(names[j]) == p) {
11390                    mProvidersByAuthority.remove(names[j]);
11391                    if (DEBUG_REMOVE) {
11392                        if (chatty)
11393                            Log.d(TAG, "Unregistered content provider: " + names[j]
11394                                    + ", className = " + p.info.name + ", isSyncable = "
11395                                    + p.info.isSyncable);
11396                    }
11397                }
11398            }
11399            if (DEBUG_REMOVE && chatty) {
11400                if (r == null) {
11401                    r = new StringBuilder(256);
11402                } else {
11403                    r.append(' ');
11404                }
11405                r.append(p.info.name);
11406            }
11407        }
11408        if (r != null) {
11409            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11410        }
11411
11412        N = pkg.services.size();
11413        r = null;
11414        for (i=0; i<N; i++) {
11415            PackageParser.Service s = pkg.services.get(i);
11416            mServices.removeService(s);
11417            if (chatty) {
11418                if (r == null) {
11419                    r = new StringBuilder(256);
11420                } else {
11421                    r.append(' ');
11422                }
11423                r.append(s.info.name);
11424            }
11425        }
11426        if (r != null) {
11427            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11428        }
11429
11430        N = pkg.receivers.size();
11431        r = null;
11432        for (i=0; i<N; i++) {
11433            PackageParser.Activity a = pkg.receivers.get(i);
11434            mReceivers.removeActivity(a, "receiver");
11435            if (DEBUG_REMOVE && chatty) {
11436                if (r == null) {
11437                    r = new StringBuilder(256);
11438                } else {
11439                    r.append(' ');
11440                }
11441                r.append(a.info.name);
11442            }
11443        }
11444        if (r != null) {
11445            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11446        }
11447
11448        N = pkg.activities.size();
11449        r = null;
11450        for (i=0; i<N; i++) {
11451            PackageParser.Activity a = pkg.activities.get(i);
11452            mActivities.removeActivity(a, "activity");
11453            if (DEBUG_REMOVE && chatty) {
11454                if (r == null) {
11455                    r = new StringBuilder(256);
11456                } else {
11457                    r.append(' ');
11458                }
11459                r.append(a.info.name);
11460            }
11461        }
11462        if (r != null) {
11463            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11464        }
11465
11466        N = pkg.permissions.size();
11467        r = null;
11468        for (i=0; i<N; i++) {
11469            PackageParser.Permission p = pkg.permissions.get(i);
11470            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11471            if (bp == null) {
11472                bp = mSettings.mPermissionTrees.get(p.info.name);
11473            }
11474            if (bp != null && bp.perm == p) {
11475                bp.perm = null;
11476                if (DEBUG_REMOVE && chatty) {
11477                    if (r == null) {
11478                        r = new StringBuilder(256);
11479                    } else {
11480                        r.append(' ');
11481                    }
11482                    r.append(p.info.name);
11483                }
11484            }
11485            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11486                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11487                if (appOpPkgs != null) {
11488                    appOpPkgs.remove(pkg.packageName);
11489                }
11490            }
11491        }
11492        if (r != null) {
11493            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11494        }
11495
11496        N = pkg.requestedPermissions.size();
11497        r = null;
11498        for (i=0; i<N; i++) {
11499            String perm = pkg.requestedPermissions.get(i);
11500            BasePermission bp = mSettings.mPermissions.get(perm);
11501            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11502                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11503                if (appOpPkgs != null) {
11504                    appOpPkgs.remove(pkg.packageName);
11505                    if (appOpPkgs.isEmpty()) {
11506                        mAppOpPermissionPackages.remove(perm);
11507                    }
11508                }
11509            }
11510        }
11511        if (r != null) {
11512            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11513        }
11514
11515        N = pkg.instrumentation.size();
11516        r = null;
11517        for (i=0; i<N; i++) {
11518            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11519            mInstrumentation.remove(a.getComponentName());
11520            if (DEBUG_REMOVE && chatty) {
11521                if (r == null) {
11522                    r = new StringBuilder(256);
11523                } else {
11524                    r.append(' ');
11525                }
11526                r.append(a.info.name);
11527            }
11528        }
11529        if (r != null) {
11530            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11531        }
11532
11533        r = null;
11534        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11535            // Only system apps can hold shared libraries.
11536            if (pkg.libraryNames != null) {
11537                for (i = 0; i < pkg.libraryNames.size(); i++) {
11538                    String name = pkg.libraryNames.get(i);
11539                    if (removeSharedLibraryLPw(name, 0)) {
11540                        if (DEBUG_REMOVE && chatty) {
11541                            if (r == null) {
11542                                r = new StringBuilder(256);
11543                            } else {
11544                                r.append(' ');
11545                            }
11546                            r.append(name);
11547                        }
11548                    }
11549                }
11550            }
11551        }
11552
11553        r = null;
11554
11555        // Any package can hold static shared libraries.
11556        if (pkg.staticSharedLibName != null) {
11557            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11558                if (DEBUG_REMOVE && chatty) {
11559                    if (r == null) {
11560                        r = new StringBuilder(256);
11561                    } else {
11562                        r.append(' ');
11563                    }
11564                    r.append(pkg.staticSharedLibName);
11565                }
11566            }
11567        }
11568
11569        if (r != null) {
11570            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11571        }
11572    }
11573
11574    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11575        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11576            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11577                return true;
11578            }
11579        }
11580        return false;
11581    }
11582
11583    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11584    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11585    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11586
11587    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11588        // Update the parent permissions
11589        updatePermissionsLPw(pkg.packageName, pkg, flags);
11590        // Update the child permissions
11591        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11592        for (int i = 0; i < childCount; i++) {
11593            PackageParser.Package childPkg = pkg.childPackages.get(i);
11594            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11595        }
11596    }
11597
11598    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11599            int flags) {
11600        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11601        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11602    }
11603
11604    private void updatePermissionsLPw(String changingPkg,
11605            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11606        // Make sure there are no dangling permission trees.
11607        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11608        while (it.hasNext()) {
11609            final BasePermission bp = it.next();
11610            if (bp.packageSetting == null) {
11611                // We may not yet have parsed the package, so just see if
11612                // we still know about its settings.
11613                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11614            }
11615            if (bp.packageSetting == null) {
11616                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11617                        + " from package " + bp.sourcePackage);
11618                it.remove();
11619            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11620                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11621                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11622                            + " from package " + bp.sourcePackage);
11623                    flags |= UPDATE_PERMISSIONS_ALL;
11624                    it.remove();
11625                }
11626            }
11627        }
11628
11629        // Make sure all dynamic permissions have been assigned to a package,
11630        // and make sure there are no dangling permissions.
11631        it = mSettings.mPermissions.values().iterator();
11632        while (it.hasNext()) {
11633            final BasePermission bp = it.next();
11634            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11635                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11636                        + bp.name + " pkg=" + bp.sourcePackage
11637                        + " info=" + bp.pendingInfo);
11638                if (bp.packageSetting == null && bp.pendingInfo != null) {
11639                    final BasePermission tree = findPermissionTreeLP(bp.name);
11640                    if (tree != null && tree.perm != null) {
11641                        bp.packageSetting = tree.packageSetting;
11642                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11643                                new PermissionInfo(bp.pendingInfo));
11644                        bp.perm.info.packageName = tree.perm.info.packageName;
11645                        bp.perm.info.name = bp.name;
11646                        bp.uid = tree.uid;
11647                    }
11648                }
11649            }
11650            if (bp.packageSetting == null) {
11651                // We may not yet have parsed the package, so just see if
11652                // we still know about its settings.
11653                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11654            }
11655            if (bp.packageSetting == null) {
11656                Slog.w(TAG, "Removing dangling permission: " + bp.name
11657                        + " from package " + bp.sourcePackage);
11658                it.remove();
11659            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11660                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11661                    Slog.i(TAG, "Removing old permission: " + bp.name
11662                            + " from package " + bp.sourcePackage);
11663                    flags |= UPDATE_PERMISSIONS_ALL;
11664                    it.remove();
11665                }
11666            }
11667        }
11668
11669        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11670        // Now update the permissions for all packages, in particular
11671        // replace the granted permissions of the system packages.
11672        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11673            for (PackageParser.Package pkg : mPackages.values()) {
11674                if (pkg != pkgInfo) {
11675                    // Only replace for packages on requested volume
11676                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11677                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11678                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11679                    grantPermissionsLPw(pkg, replace, changingPkg);
11680                }
11681            }
11682        }
11683
11684        if (pkgInfo != null) {
11685            // Only replace for packages on requested volume
11686            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11687            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11688                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11689            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11690        }
11691        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11692    }
11693
11694    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11695            String packageOfInterest) {
11696        // IMPORTANT: There are two types of permissions: install and runtime.
11697        // Install time permissions are granted when the app is installed to
11698        // all device users and users added in the future. Runtime permissions
11699        // are granted at runtime explicitly to specific users. Normal and signature
11700        // protected permissions are install time permissions. Dangerous permissions
11701        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11702        // otherwise they are runtime permissions. This function does not manage
11703        // runtime permissions except for the case an app targeting Lollipop MR1
11704        // being upgraded to target a newer SDK, in which case dangerous permissions
11705        // are transformed from install time to runtime ones.
11706
11707        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11708        if (ps == null) {
11709            return;
11710        }
11711
11712        PermissionsState permissionsState = ps.getPermissionsState();
11713        PermissionsState origPermissions = permissionsState;
11714
11715        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11716
11717        boolean runtimePermissionsRevoked = false;
11718        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11719
11720        boolean changedInstallPermission = false;
11721
11722        if (replace) {
11723            ps.installPermissionsFixed = false;
11724            if (!ps.isSharedUser()) {
11725                origPermissions = new PermissionsState(permissionsState);
11726                permissionsState.reset();
11727            } else {
11728                // We need to know only about runtime permission changes since the
11729                // calling code always writes the install permissions state but
11730                // the runtime ones are written only if changed. The only cases of
11731                // changed runtime permissions here are promotion of an install to
11732                // runtime and revocation of a runtime from a shared user.
11733                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11734                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11735                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11736                    runtimePermissionsRevoked = true;
11737                }
11738            }
11739        }
11740
11741        permissionsState.setGlobalGids(mGlobalGids);
11742
11743        final int N = pkg.requestedPermissions.size();
11744        for (int i=0; i<N; i++) {
11745            final String name = pkg.requestedPermissions.get(i);
11746            final BasePermission bp = mSettings.mPermissions.get(name);
11747            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11748                    >= Build.VERSION_CODES.M;
11749
11750            if (DEBUG_INSTALL) {
11751                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11752            }
11753
11754            if (bp == null || bp.packageSetting == null) {
11755                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11756                    if (DEBUG_PERMISSIONS) {
11757                        Slog.i(TAG, "Unknown permission " + name
11758                                + " in package " + pkg.packageName);
11759                    }
11760                }
11761                continue;
11762            }
11763
11764
11765            // Limit ephemeral apps to ephemeral allowed permissions.
11766            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11767                if (DEBUG_PERMISSIONS) {
11768                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11769                            + pkg.packageName);
11770                }
11771                continue;
11772            }
11773
11774            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11775                if (DEBUG_PERMISSIONS) {
11776                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11777                            + pkg.packageName);
11778                }
11779                continue;
11780            }
11781
11782            final String perm = bp.name;
11783            boolean allowedSig = false;
11784            int grant = GRANT_DENIED;
11785
11786            // Keep track of app op permissions.
11787            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11788                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11789                if (pkgs == null) {
11790                    pkgs = new ArraySet<>();
11791                    mAppOpPermissionPackages.put(bp.name, pkgs);
11792                }
11793                pkgs.add(pkg.packageName);
11794            }
11795
11796            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11797            switch (level) {
11798                case PermissionInfo.PROTECTION_NORMAL: {
11799                    // For all apps normal permissions are install time ones.
11800                    grant = GRANT_INSTALL;
11801                } break;
11802
11803                case PermissionInfo.PROTECTION_DANGEROUS: {
11804                    // If a permission review is required for legacy apps we represent
11805                    // their permissions as always granted runtime ones since we need
11806                    // to keep the review required permission flag per user while an
11807                    // install permission's state is shared across all users.
11808                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11809                        // For legacy apps dangerous permissions are install time ones.
11810                        grant = GRANT_INSTALL;
11811                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11812                        // For legacy apps that became modern, install becomes runtime.
11813                        grant = GRANT_UPGRADE;
11814                    } else if (mPromoteSystemApps
11815                            && isSystemApp(ps)
11816                            && mExistingSystemPackages.contains(ps.name)) {
11817                        // For legacy system apps, install becomes runtime.
11818                        // We cannot check hasInstallPermission() for system apps since those
11819                        // permissions were granted implicitly and not persisted pre-M.
11820                        grant = GRANT_UPGRADE;
11821                    } else {
11822                        // For modern apps keep runtime permissions unchanged.
11823                        grant = GRANT_RUNTIME;
11824                    }
11825                } break;
11826
11827                case PermissionInfo.PROTECTION_SIGNATURE: {
11828                    // For all apps signature permissions are install time ones.
11829                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11830                    if (allowedSig) {
11831                        grant = GRANT_INSTALL;
11832                    }
11833                } break;
11834            }
11835
11836            if (DEBUG_PERMISSIONS) {
11837                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
11838            }
11839
11840            if (grant != GRANT_DENIED) {
11841                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11842                    // If this is an existing, non-system package, then
11843                    // we can't add any new permissions to it.
11844                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11845                        // Except...  if this is a permission that was added
11846                        // to the platform (note: need to only do this when
11847                        // updating the platform).
11848                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11849                            grant = GRANT_DENIED;
11850                        }
11851                    }
11852                }
11853
11854                switch (grant) {
11855                    case GRANT_INSTALL: {
11856                        // Revoke this as runtime permission to handle the case of
11857                        // a runtime permission being downgraded to an install one.
11858                        // Also in permission review mode we keep dangerous permissions
11859                        // for legacy apps
11860                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11861                            if (origPermissions.getRuntimePermissionState(
11862                                    bp.name, userId) != null) {
11863                                // Revoke the runtime permission and clear the flags.
11864                                origPermissions.revokeRuntimePermission(bp, userId);
11865                                origPermissions.updatePermissionFlags(bp, userId,
11866                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11867                                // If we revoked a permission permission, we have to write.
11868                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11869                                        changedRuntimePermissionUserIds, userId);
11870                            }
11871                        }
11872                        // Grant an install permission.
11873                        if (permissionsState.grantInstallPermission(bp) !=
11874                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11875                            changedInstallPermission = true;
11876                        }
11877                    } break;
11878
11879                    case GRANT_RUNTIME: {
11880                        // Grant previously granted runtime permissions.
11881                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11882                            PermissionState permissionState = origPermissions
11883                                    .getRuntimePermissionState(bp.name, userId);
11884                            int flags = permissionState != null
11885                                    ? permissionState.getFlags() : 0;
11886                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11887                                // Don't propagate the permission in a permission review mode if
11888                                // the former was revoked, i.e. marked to not propagate on upgrade.
11889                                // Note that in a permission review mode install permissions are
11890                                // represented as constantly granted runtime ones since we need to
11891                                // keep a per user state associated with the permission. Also the
11892                                // revoke on upgrade flag is no longer applicable and is reset.
11893                                final boolean revokeOnUpgrade = (flags & PackageManager
11894                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11895                                if (revokeOnUpgrade) {
11896                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11897                                    // Since we changed the flags, we have to write.
11898                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11899                                            changedRuntimePermissionUserIds, userId);
11900                                }
11901                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11902                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11903                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11904                                        // If we cannot put the permission as it was,
11905                                        // we have to write.
11906                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11907                                                changedRuntimePermissionUserIds, userId);
11908                                    }
11909                                }
11910
11911                                // If the app supports runtime permissions no need for a review.
11912                                if (mPermissionReviewRequired
11913                                        && appSupportsRuntimePermissions
11914                                        && (flags & PackageManager
11915                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11916                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11917                                    // Since we changed the flags, we have to write.
11918                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11919                                            changedRuntimePermissionUserIds, userId);
11920                                }
11921                            } else if (mPermissionReviewRequired
11922                                    && !appSupportsRuntimePermissions) {
11923                                // For legacy apps that need a permission review, every new
11924                                // runtime permission is granted but it is pending a review.
11925                                // We also need to review only platform defined runtime
11926                                // permissions as these are the only ones the platform knows
11927                                // how to disable the API to simulate revocation as legacy
11928                                // apps don't expect to run with revoked permissions.
11929                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11930                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11931                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11932                                        // We changed the flags, hence have to write.
11933                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11934                                                changedRuntimePermissionUserIds, userId);
11935                                    }
11936                                }
11937                                if (permissionsState.grantRuntimePermission(bp, userId)
11938                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11939                                    // We changed the permission, hence have to write.
11940                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11941                                            changedRuntimePermissionUserIds, userId);
11942                                }
11943                            }
11944                            // Propagate the permission flags.
11945                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11946                        }
11947                    } break;
11948
11949                    case GRANT_UPGRADE: {
11950                        // Grant runtime permissions for a previously held install permission.
11951                        PermissionState permissionState = origPermissions
11952                                .getInstallPermissionState(bp.name);
11953                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11954
11955                        if (origPermissions.revokeInstallPermission(bp)
11956                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11957                            // We will be transferring the permission flags, so clear them.
11958                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11959                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11960                            changedInstallPermission = true;
11961                        }
11962
11963                        // If the permission is not to be promoted to runtime we ignore it and
11964                        // also its other flags as they are not applicable to install permissions.
11965                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11966                            for (int userId : currentUserIds) {
11967                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11968                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11969                                    // Transfer the permission flags.
11970                                    permissionsState.updatePermissionFlags(bp, userId,
11971                                            flags, flags);
11972                                    // If we granted the permission, we have to write.
11973                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11974                                            changedRuntimePermissionUserIds, userId);
11975                                }
11976                            }
11977                        }
11978                    } break;
11979
11980                    default: {
11981                        if (packageOfInterest == null
11982                                || packageOfInterest.equals(pkg.packageName)) {
11983                            if (DEBUG_PERMISSIONS) {
11984                                Slog.i(TAG, "Not granting permission " + perm
11985                                        + " to package " + pkg.packageName
11986                                        + " because it was previously installed without");
11987                            }
11988                        }
11989                    } break;
11990                }
11991            } else {
11992                if (permissionsState.revokeInstallPermission(bp) !=
11993                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11994                    // Also drop the permission flags.
11995                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11996                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11997                    changedInstallPermission = true;
11998                    Slog.i(TAG, "Un-granting permission " + perm
11999                            + " from package " + pkg.packageName
12000                            + " (protectionLevel=" + bp.protectionLevel
12001                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12002                            + ")");
12003                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12004                    // Don't print warning for app op permissions, since it is fine for them
12005                    // not to be granted, there is a UI for the user to decide.
12006                    if (DEBUG_PERMISSIONS
12007                            && (packageOfInterest == null
12008                                    || packageOfInterest.equals(pkg.packageName))) {
12009                        Slog.i(TAG, "Not granting permission " + perm
12010                                + " to package " + pkg.packageName
12011                                + " (protectionLevel=" + bp.protectionLevel
12012                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12013                                + ")");
12014                    }
12015                }
12016            }
12017        }
12018
12019        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12020                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12021            // This is the first that we have heard about this package, so the
12022            // permissions we have now selected are fixed until explicitly
12023            // changed.
12024            ps.installPermissionsFixed = true;
12025        }
12026
12027        // Persist the runtime permissions state for users with changes. If permissions
12028        // were revoked because no app in the shared user declares them we have to
12029        // write synchronously to avoid losing runtime permissions state.
12030        for (int userId : changedRuntimePermissionUserIds) {
12031            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12032        }
12033    }
12034
12035    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12036        boolean allowed = false;
12037        final int NP = PackageParser.NEW_PERMISSIONS.length;
12038        for (int ip=0; ip<NP; ip++) {
12039            final PackageParser.NewPermissionInfo npi
12040                    = PackageParser.NEW_PERMISSIONS[ip];
12041            if (npi.name.equals(perm)
12042                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12043                allowed = true;
12044                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12045                        + pkg.packageName);
12046                break;
12047            }
12048        }
12049        return allowed;
12050    }
12051
12052    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12053            BasePermission bp, PermissionsState origPermissions) {
12054        boolean privilegedPermission = (bp.protectionLevel
12055                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12056        boolean privappPermissionsDisable =
12057                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12058        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12059        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12060        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12061                && !platformPackage && platformPermission) {
12062            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12063                    .getPrivAppPermissions(pkg.packageName);
12064            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12065            if (!whitelisted) {
12066                Slog.w(TAG, "Privileged permission " + perm + " for package "
12067                        + pkg.packageName + " - not in privapp-permissions whitelist");
12068                // Only report violations for apps on system image
12069                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12070                    if (mPrivappPermissionsViolations == null) {
12071                        mPrivappPermissionsViolations = new ArraySet<>();
12072                    }
12073                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12074                }
12075                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12076                    return false;
12077                }
12078            }
12079        }
12080        boolean allowed = (compareSignatures(
12081                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12082                        == PackageManager.SIGNATURE_MATCH)
12083                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12084                        == PackageManager.SIGNATURE_MATCH);
12085        if (!allowed && privilegedPermission) {
12086            if (isSystemApp(pkg)) {
12087                // For updated system applications, a system permission
12088                // is granted only if it had been defined by the original application.
12089                if (pkg.isUpdatedSystemApp()) {
12090                    final PackageSetting sysPs = mSettings
12091                            .getDisabledSystemPkgLPr(pkg.packageName);
12092                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12093                        // If the original was granted this permission, we take
12094                        // that grant decision as read and propagate it to the
12095                        // update.
12096                        if (sysPs.isPrivileged()) {
12097                            allowed = true;
12098                        }
12099                    } else {
12100                        // The system apk may have been updated with an older
12101                        // version of the one on the data partition, but which
12102                        // granted a new system permission that it didn't have
12103                        // before.  In this case we do want to allow the app to
12104                        // now get the new permission if the ancestral apk is
12105                        // privileged to get it.
12106                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12107                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12108                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12109                                    allowed = true;
12110                                    break;
12111                                }
12112                            }
12113                        }
12114                        // Also if a privileged parent package on the system image or any of
12115                        // its children requested a privileged permission, the updated child
12116                        // packages can also get the permission.
12117                        if (pkg.parentPackage != null) {
12118                            final PackageSetting disabledSysParentPs = mSettings
12119                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12120                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12121                                    && disabledSysParentPs.isPrivileged()) {
12122                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12123                                    allowed = true;
12124                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12125                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12126                                    for (int i = 0; i < count; i++) {
12127                                        PackageParser.Package disabledSysChildPkg =
12128                                                disabledSysParentPs.pkg.childPackages.get(i);
12129                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12130                                                perm)) {
12131                                            allowed = true;
12132                                            break;
12133                                        }
12134                                    }
12135                                }
12136                            }
12137                        }
12138                    }
12139                } else {
12140                    allowed = isPrivilegedApp(pkg);
12141                }
12142            }
12143        }
12144        if (!allowed) {
12145            if (!allowed && (bp.protectionLevel
12146                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12147                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12148                // If this was a previously normal/dangerous permission that got moved
12149                // to a system permission as part of the runtime permission redesign, then
12150                // we still want to blindly grant it to old apps.
12151                allowed = true;
12152            }
12153            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12154                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12155                // If this permission is to be granted to the system installer and
12156                // this app is an installer, then it gets the permission.
12157                allowed = true;
12158            }
12159            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12160                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12161                // If this permission is to be granted to the system verifier and
12162                // this app is a verifier, then it gets the permission.
12163                allowed = true;
12164            }
12165            if (!allowed && (bp.protectionLevel
12166                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12167                    && isSystemApp(pkg)) {
12168                // Any pre-installed system app is allowed to get this permission.
12169                allowed = true;
12170            }
12171            if (!allowed && (bp.protectionLevel
12172                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12173                // For development permissions, a development permission
12174                // is granted only if it was already granted.
12175                allowed = origPermissions.hasInstallPermission(perm);
12176            }
12177            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12178                    && pkg.packageName.equals(mSetupWizardPackage)) {
12179                // If this permission is to be granted to the system setup wizard and
12180                // this app is a setup wizard, then it gets the permission.
12181                allowed = true;
12182            }
12183        }
12184        return allowed;
12185    }
12186
12187    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12188        final int permCount = pkg.requestedPermissions.size();
12189        for (int j = 0; j < permCount; j++) {
12190            String requestedPermission = pkg.requestedPermissions.get(j);
12191            if (permission.equals(requestedPermission)) {
12192                return true;
12193            }
12194        }
12195        return false;
12196    }
12197
12198    final class ActivityIntentResolver
12199            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12200        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12201                boolean defaultOnly, int userId) {
12202            if (!sUserManager.exists(userId)) return null;
12203            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12204            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12205        }
12206
12207        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12208                int userId) {
12209            if (!sUserManager.exists(userId)) return null;
12210            mFlags = flags;
12211            return super.queryIntent(intent, resolvedType,
12212                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12213                    userId);
12214        }
12215
12216        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12217                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12218            if (!sUserManager.exists(userId)) return null;
12219            if (packageActivities == null) {
12220                return null;
12221            }
12222            mFlags = flags;
12223            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12224            final int N = packageActivities.size();
12225            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12226                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12227
12228            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12229            for (int i = 0; i < N; ++i) {
12230                intentFilters = packageActivities.get(i).intents;
12231                if (intentFilters != null && intentFilters.size() > 0) {
12232                    PackageParser.ActivityIntentInfo[] array =
12233                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12234                    intentFilters.toArray(array);
12235                    listCut.add(array);
12236                }
12237            }
12238            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12239        }
12240
12241        /**
12242         * Finds a privileged activity that matches the specified activity names.
12243         */
12244        private PackageParser.Activity findMatchingActivity(
12245                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12246            for (PackageParser.Activity sysActivity : activityList) {
12247                if (sysActivity.info.name.equals(activityInfo.name)) {
12248                    return sysActivity;
12249                }
12250                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12251                    return sysActivity;
12252                }
12253                if (sysActivity.info.targetActivity != null) {
12254                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12255                        return sysActivity;
12256                    }
12257                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12258                        return sysActivity;
12259                    }
12260                }
12261            }
12262            return null;
12263        }
12264
12265        public class IterGenerator<E> {
12266            public Iterator<E> generate(ActivityIntentInfo info) {
12267                return null;
12268            }
12269        }
12270
12271        public class ActionIterGenerator extends IterGenerator<String> {
12272            @Override
12273            public Iterator<String> generate(ActivityIntentInfo info) {
12274                return info.actionsIterator();
12275            }
12276        }
12277
12278        public class CategoriesIterGenerator extends IterGenerator<String> {
12279            @Override
12280            public Iterator<String> generate(ActivityIntentInfo info) {
12281                return info.categoriesIterator();
12282            }
12283        }
12284
12285        public class SchemesIterGenerator extends IterGenerator<String> {
12286            @Override
12287            public Iterator<String> generate(ActivityIntentInfo info) {
12288                return info.schemesIterator();
12289            }
12290        }
12291
12292        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12293            @Override
12294            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12295                return info.authoritiesIterator();
12296            }
12297        }
12298
12299        /**
12300         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12301         * MODIFIED. Do not pass in a list that should not be changed.
12302         */
12303        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12304                IterGenerator<T> generator, Iterator<T> searchIterator) {
12305            // loop through the set of actions; every one must be found in the intent filter
12306            while (searchIterator.hasNext()) {
12307                // we must have at least one filter in the list to consider a match
12308                if (intentList.size() == 0) {
12309                    break;
12310                }
12311
12312                final T searchAction = searchIterator.next();
12313
12314                // loop through the set of intent filters
12315                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12316                while (intentIter.hasNext()) {
12317                    final ActivityIntentInfo intentInfo = intentIter.next();
12318                    boolean selectionFound = false;
12319
12320                    // loop through the intent filter's selection criteria; at least one
12321                    // of them must match the searched criteria
12322                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12323                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12324                        final T intentSelection = intentSelectionIter.next();
12325                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12326                            selectionFound = true;
12327                            break;
12328                        }
12329                    }
12330
12331                    // the selection criteria wasn't found in this filter's set; this filter
12332                    // is not a potential match
12333                    if (!selectionFound) {
12334                        intentIter.remove();
12335                    }
12336                }
12337            }
12338        }
12339
12340        private boolean isProtectedAction(ActivityIntentInfo filter) {
12341            final Iterator<String> actionsIter = filter.actionsIterator();
12342            while (actionsIter != null && actionsIter.hasNext()) {
12343                final String filterAction = actionsIter.next();
12344                if (PROTECTED_ACTIONS.contains(filterAction)) {
12345                    return true;
12346                }
12347            }
12348            return false;
12349        }
12350
12351        /**
12352         * Adjusts the priority of the given intent filter according to policy.
12353         * <p>
12354         * <ul>
12355         * <li>The priority for non privileged applications is capped to '0'</li>
12356         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12357         * <li>The priority for unbundled updates to privileged applications is capped to the
12358         *      priority defined on the system partition</li>
12359         * </ul>
12360         * <p>
12361         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12362         * allowed to obtain any priority on any action.
12363         */
12364        private void adjustPriority(
12365                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12366            // nothing to do; priority is fine as-is
12367            if (intent.getPriority() <= 0) {
12368                return;
12369            }
12370
12371            final ActivityInfo activityInfo = intent.activity.info;
12372            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12373
12374            final boolean privilegedApp =
12375                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12376            if (!privilegedApp) {
12377                // non-privileged applications can never define a priority >0
12378                if (DEBUG_FILTERS) {
12379                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12380                            + " package: " + applicationInfo.packageName
12381                            + " activity: " + intent.activity.className
12382                            + " origPrio: " + intent.getPriority());
12383                }
12384                intent.setPriority(0);
12385                return;
12386            }
12387
12388            if (systemActivities == null) {
12389                // the system package is not disabled; we're parsing the system partition
12390                if (isProtectedAction(intent)) {
12391                    if (mDeferProtectedFilters) {
12392                        // We can't deal with these just yet. No component should ever obtain a
12393                        // >0 priority for a protected actions, with ONE exception -- the setup
12394                        // wizard. The setup wizard, however, cannot be known until we're able to
12395                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12396                        // until all intent filters have been processed. Chicken, meet egg.
12397                        // Let the filter temporarily have a high priority and rectify the
12398                        // priorities after all system packages have been scanned.
12399                        mProtectedFilters.add(intent);
12400                        if (DEBUG_FILTERS) {
12401                            Slog.i(TAG, "Protected action; save for later;"
12402                                    + " package: " + applicationInfo.packageName
12403                                    + " activity: " + intent.activity.className
12404                                    + " origPrio: " + intent.getPriority());
12405                        }
12406                        return;
12407                    } else {
12408                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12409                            Slog.i(TAG, "No setup wizard;"
12410                                + " All protected intents capped to priority 0");
12411                        }
12412                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12413                            if (DEBUG_FILTERS) {
12414                                Slog.i(TAG, "Found setup wizard;"
12415                                    + " allow priority " + intent.getPriority() + ";"
12416                                    + " package: " + intent.activity.info.packageName
12417                                    + " activity: " + intent.activity.className
12418                                    + " priority: " + intent.getPriority());
12419                            }
12420                            // setup wizard gets whatever it wants
12421                            return;
12422                        }
12423                        if (DEBUG_FILTERS) {
12424                            Slog.i(TAG, "Protected action; cap priority to 0;"
12425                                    + " package: " + intent.activity.info.packageName
12426                                    + " activity: " + intent.activity.className
12427                                    + " origPrio: " + intent.getPriority());
12428                        }
12429                        intent.setPriority(0);
12430                        return;
12431                    }
12432                }
12433                // privileged apps on the system image get whatever priority they request
12434                return;
12435            }
12436
12437            // privileged app unbundled update ... try to find the same activity
12438            final PackageParser.Activity foundActivity =
12439                    findMatchingActivity(systemActivities, activityInfo);
12440            if (foundActivity == null) {
12441                // this is a new activity; it cannot obtain >0 priority
12442                if (DEBUG_FILTERS) {
12443                    Slog.i(TAG, "New activity; cap priority to 0;"
12444                            + " package: " + applicationInfo.packageName
12445                            + " activity: " + intent.activity.className
12446                            + " origPrio: " + intent.getPriority());
12447                }
12448                intent.setPriority(0);
12449                return;
12450            }
12451
12452            // found activity, now check for filter equivalence
12453
12454            // a shallow copy is enough; we modify the list, not its contents
12455            final List<ActivityIntentInfo> intentListCopy =
12456                    new ArrayList<>(foundActivity.intents);
12457            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12458
12459            // find matching action subsets
12460            final Iterator<String> actionsIterator = intent.actionsIterator();
12461            if (actionsIterator != null) {
12462                getIntentListSubset(
12463                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12464                if (intentListCopy.size() == 0) {
12465                    // no more intents to match; we're not equivalent
12466                    if (DEBUG_FILTERS) {
12467                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12468                                + " package: " + applicationInfo.packageName
12469                                + " activity: " + intent.activity.className
12470                                + " origPrio: " + intent.getPriority());
12471                    }
12472                    intent.setPriority(0);
12473                    return;
12474                }
12475            }
12476
12477            // find matching category subsets
12478            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12479            if (categoriesIterator != null) {
12480                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12481                        categoriesIterator);
12482                if (intentListCopy.size() == 0) {
12483                    // no more intents to match; we're not equivalent
12484                    if (DEBUG_FILTERS) {
12485                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12486                                + " package: " + applicationInfo.packageName
12487                                + " activity: " + intent.activity.className
12488                                + " origPrio: " + intent.getPriority());
12489                    }
12490                    intent.setPriority(0);
12491                    return;
12492                }
12493            }
12494
12495            // find matching schemes subsets
12496            final Iterator<String> schemesIterator = intent.schemesIterator();
12497            if (schemesIterator != null) {
12498                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12499                        schemesIterator);
12500                if (intentListCopy.size() == 0) {
12501                    // no more intents to match; we're not equivalent
12502                    if (DEBUG_FILTERS) {
12503                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12504                                + " package: " + applicationInfo.packageName
12505                                + " activity: " + intent.activity.className
12506                                + " origPrio: " + intent.getPriority());
12507                    }
12508                    intent.setPriority(0);
12509                    return;
12510                }
12511            }
12512
12513            // find matching authorities subsets
12514            final Iterator<IntentFilter.AuthorityEntry>
12515                    authoritiesIterator = intent.authoritiesIterator();
12516            if (authoritiesIterator != null) {
12517                getIntentListSubset(intentListCopy,
12518                        new AuthoritiesIterGenerator(),
12519                        authoritiesIterator);
12520                if (intentListCopy.size() == 0) {
12521                    // no more intents to match; we're not equivalent
12522                    if (DEBUG_FILTERS) {
12523                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12524                                + " package: " + applicationInfo.packageName
12525                                + " activity: " + intent.activity.className
12526                                + " origPrio: " + intent.getPriority());
12527                    }
12528                    intent.setPriority(0);
12529                    return;
12530                }
12531            }
12532
12533            // we found matching filter(s); app gets the max priority of all intents
12534            int cappedPriority = 0;
12535            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12536                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12537            }
12538            if (intent.getPriority() > cappedPriority) {
12539                if (DEBUG_FILTERS) {
12540                    Slog.i(TAG, "Found matching filter(s);"
12541                            + " cap priority to " + cappedPriority + ";"
12542                            + " package: " + applicationInfo.packageName
12543                            + " activity: " + intent.activity.className
12544                            + " origPrio: " + intent.getPriority());
12545                }
12546                intent.setPriority(cappedPriority);
12547                return;
12548            }
12549            // all this for nothing; the requested priority was <= what was on the system
12550        }
12551
12552        public final void addActivity(PackageParser.Activity a, String type) {
12553            mActivities.put(a.getComponentName(), a);
12554            if (DEBUG_SHOW_INFO)
12555                Log.v(
12556                TAG, "  " + type + " " +
12557                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12558            if (DEBUG_SHOW_INFO)
12559                Log.v(TAG, "    Class=" + a.info.name);
12560            final int NI = a.intents.size();
12561            for (int j=0; j<NI; j++) {
12562                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12563                if ("activity".equals(type)) {
12564                    final PackageSetting ps =
12565                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12566                    final List<PackageParser.Activity> systemActivities =
12567                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12568                    adjustPriority(systemActivities, intent);
12569                }
12570                if (DEBUG_SHOW_INFO) {
12571                    Log.v(TAG, "    IntentFilter:");
12572                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12573                }
12574                if (!intent.debugCheck()) {
12575                    Log.w(TAG, "==> For Activity " + a.info.name);
12576                }
12577                addFilter(intent);
12578            }
12579        }
12580
12581        public final void removeActivity(PackageParser.Activity a, String type) {
12582            mActivities.remove(a.getComponentName());
12583            if (DEBUG_SHOW_INFO) {
12584                Log.v(TAG, "  " + type + " "
12585                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12586                                : a.info.name) + ":");
12587                Log.v(TAG, "    Class=" + a.info.name);
12588            }
12589            final int NI = a.intents.size();
12590            for (int j=0; j<NI; j++) {
12591                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12592                if (DEBUG_SHOW_INFO) {
12593                    Log.v(TAG, "    IntentFilter:");
12594                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12595                }
12596                removeFilter(intent);
12597            }
12598        }
12599
12600        @Override
12601        protected boolean allowFilterResult(
12602                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12603            ActivityInfo filterAi = filter.activity.info;
12604            for (int i=dest.size()-1; i>=0; i--) {
12605                ActivityInfo destAi = dest.get(i).activityInfo;
12606                if (destAi.name == filterAi.name
12607                        && destAi.packageName == filterAi.packageName) {
12608                    return false;
12609                }
12610            }
12611            return true;
12612        }
12613
12614        @Override
12615        protected ActivityIntentInfo[] newArray(int size) {
12616            return new ActivityIntentInfo[size];
12617        }
12618
12619        @Override
12620        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12621            if (!sUserManager.exists(userId)) return true;
12622            PackageParser.Package p = filter.activity.owner;
12623            if (p != null) {
12624                PackageSetting ps = (PackageSetting)p.mExtras;
12625                if (ps != null) {
12626                    // System apps are never considered stopped for purposes of
12627                    // filtering, because there may be no way for the user to
12628                    // actually re-launch them.
12629                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12630                            && ps.getStopped(userId);
12631                }
12632            }
12633            return false;
12634        }
12635
12636        @Override
12637        protected boolean isPackageForFilter(String packageName,
12638                PackageParser.ActivityIntentInfo info) {
12639            return packageName.equals(info.activity.owner.packageName);
12640        }
12641
12642        @Override
12643        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12644                int match, int userId) {
12645            if (!sUserManager.exists(userId)) return null;
12646            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12647                return null;
12648            }
12649            final PackageParser.Activity activity = info.activity;
12650            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12651            if (ps == null) {
12652                return null;
12653            }
12654            final PackageUserState userState = ps.readUserState(userId);
12655            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12656            if (ai == null) {
12657                return null;
12658            }
12659            final boolean matchExplicitlyVisibleOnly =
12660                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12661            final boolean matchVisibleToInstantApp =
12662                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12663            final boolean componentVisible =
12664                    matchVisibleToInstantApp
12665                    && info.isVisibleToInstantApp()
12666                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12667            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12668            // throw out filters that aren't visible to ephemeral apps
12669            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12670                return null;
12671            }
12672            // throw out instant app filters if we're not explicitly requesting them
12673            if (!matchInstantApp && userState.instantApp) {
12674                return null;
12675            }
12676            // throw out instant app filters if updates are available; will trigger
12677            // instant app resolution
12678            if (userState.instantApp && ps.isUpdateAvailable()) {
12679                return null;
12680            }
12681            final ResolveInfo res = new ResolveInfo();
12682            res.activityInfo = ai;
12683            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12684                res.filter = info;
12685            }
12686            if (info != null) {
12687                res.handleAllWebDataURI = info.handleAllWebDataURI();
12688            }
12689            res.priority = info.getPriority();
12690            res.preferredOrder = activity.owner.mPreferredOrder;
12691            //System.out.println("Result: " + res.activityInfo.className +
12692            //                   " = " + res.priority);
12693            res.match = match;
12694            res.isDefault = info.hasDefault;
12695            res.labelRes = info.labelRes;
12696            res.nonLocalizedLabel = info.nonLocalizedLabel;
12697            if (userNeedsBadging(userId)) {
12698                res.noResourceId = true;
12699            } else {
12700                res.icon = info.icon;
12701            }
12702            res.iconResourceId = info.icon;
12703            res.system = res.activityInfo.applicationInfo.isSystemApp();
12704            res.isInstantAppAvailable = userState.instantApp;
12705            return res;
12706        }
12707
12708        @Override
12709        protected void sortResults(List<ResolveInfo> results) {
12710            Collections.sort(results, mResolvePrioritySorter);
12711        }
12712
12713        @Override
12714        protected void dumpFilter(PrintWriter out, String prefix,
12715                PackageParser.ActivityIntentInfo filter) {
12716            out.print(prefix); out.print(
12717                    Integer.toHexString(System.identityHashCode(filter.activity)));
12718                    out.print(' ');
12719                    filter.activity.printComponentShortName(out);
12720                    out.print(" filter ");
12721                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12722        }
12723
12724        @Override
12725        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12726            return filter.activity;
12727        }
12728
12729        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12730            PackageParser.Activity activity = (PackageParser.Activity)label;
12731            out.print(prefix); out.print(
12732                    Integer.toHexString(System.identityHashCode(activity)));
12733                    out.print(' ');
12734                    activity.printComponentShortName(out);
12735            if (count > 1) {
12736                out.print(" ("); out.print(count); out.print(" filters)");
12737            }
12738            out.println();
12739        }
12740
12741        // Keys are String (activity class name), values are Activity.
12742        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12743                = new ArrayMap<ComponentName, PackageParser.Activity>();
12744        private int mFlags;
12745    }
12746
12747    private final class ServiceIntentResolver
12748            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12749        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12750                boolean defaultOnly, int userId) {
12751            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12752            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12753        }
12754
12755        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12756                int userId) {
12757            if (!sUserManager.exists(userId)) return null;
12758            mFlags = flags;
12759            return super.queryIntent(intent, resolvedType,
12760                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12761                    userId);
12762        }
12763
12764        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12765                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12766            if (!sUserManager.exists(userId)) return null;
12767            if (packageServices == null) {
12768                return null;
12769            }
12770            mFlags = flags;
12771            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12772            final int N = packageServices.size();
12773            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12774                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12775
12776            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12777            for (int i = 0; i < N; ++i) {
12778                intentFilters = packageServices.get(i).intents;
12779                if (intentFilters != null && intentFilters.size() > 0) {
12780                    PackageParser.ServiceIntentInfo[] array =
12781                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12782                    intentFilters.toArray(array);
12783                    listCut.add(array);
12784                }
12785            }
12786            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12787        }
12788
12789        public final void addService(PackageParser.Service s) {
12790            mServices.put(s.getComponentName(), s);
12791            if (DEBUG_SHOW_INFO) {
12792                Log.v(TAG, "  "
12793                        + (s.info.nonLocalizedLabel != null
12794                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12795                Log.v(TAG, "    Class=" + s.info.name);
12796            }
12797            final int NI = s.intents.size();
12798            int j;
12799            for (j=0; j<NI; j++) {
12800                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12801                if (DEBUG_SHOW_INFO) {
12802                    Log.v(TAG, "    IntentFilter:");
12803                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12804                }
12805                if (!intent.debugCheck()) {
12806                    Log.w(TAG, "==> For Service " + s.info.name);
12807                }
12808                addFilter(intent);
12809            }
12810        }
12811
12812        public final void removeService(PackageParser.Service s) {
12813            mServices.remove(s.getComponentName());
12814            if (DEBUG_SHOW_INFO) {
12815                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12816                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12817                Log.v(TAG, "    Class=" + s.info.name);
12818            }
12819            final int NI = s.intents.size();
12820            int j;
12821            for (j=0; j<NI; j++) {
12822                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12823                if (DEBUG_SHOW_INFO) {
12824                    Log.v(TAG, "    IntentFilter:");
12825                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12826                }
12827                removeFilter(intent);
12828            }
12829        }
12830
12831        @Override
12832        protected boolean allowFilterResult(
12833                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12834            ServiceInfo filterSi = filter.service.info;
12835            for (int i=dest.size()-1; i>=0; i--) {
12836                ServiceInfo destAi = dest.get(i).serviceInfo;
12837                if (destAi.name == filterSi.name
12838                        && destAi.packageName == filterSi.packageName) {
12839                    return false;
12840                }
12841            }
12842            return true;
12843        }
12844
12845        @Override
12846        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12847            return new PackageParser.ServiceIntentInfo[size];
12848        }
12849
12850        @Override
12851        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12852            if (!sUserManager.exists(userId)) return true;
12853            PackageParser.Package p = filter.service.owner;
12854            if (p != null) {
12855                PackageSetting ps = (PackageSetting)p.mExtras;
12856                if (ps != null) {
12857                    // System apps are never considered stopped for purposes of
12858                    // filtering, because there may be no way for the user to
12859                    // actually re-launch them.
12860                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12861                            && ps.getStopped(userId);
12862                }
12863            }
12864            return false;
12865        }
12866
12867        @Override
12868        protected boolean isPackageForFilter(String packageName,
12869                PackageParser.ServiceIntentInfo info) {
12870            return packageName.equals(info.service.owner.packageName);
12871        }
12872
12873        @Override
12874        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12875                int match, int userId) {
12876            if (!sUserManager.exists(userId)) return null;
12877            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12878            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12879                return null;
12880            }
12881            final PackageParser.Service service = info.service;
12882            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12883            if (ps == null) {
12884                return null;
12885            }
12886            final PackageUserState userState = ps.readUserState(userId);
12887            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12888                    userState, userId);
12889            if (si == null) {
12890                return null;
12891            }
12892            final boolean matchVisibleToInstantApp =
12893                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12894            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12895            // throw out filters that aren't visible to ephemeral apps
12896            if (matchVisibleToInstantApp
12897                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12898                return null;
12899            }
12900            // throw out ephemeral filters if we're not explicitly requesting them
12901            if (!isInstantApp && userState.instantApp) {
12902                return null;
12903            }
12904            // throw out instant app filters if updates are available; will trigger
12905            // instant app resolution
12906            if (userState.instantApp && ps.isUpdateAvailable()) {
12907                return null;
12908            }
12909            final ResolveInfo res = new ResolveInfo();
12910            res.serviceInfo = si;
12911            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12912                res.filter = filter;
12913            }
12914            res.priority = info.getPriority();
12915            res.preferredOrder = service.owner.mPreferredOrder;
12916            res.match = match;
12917            res.isDefault = info.hasDefault;
12918            res.labelRes = info.labelRes;
12919            res.nonLocalizedLabel = info.nonLocalizedLabel;
12920            res.icon = info.icon;
12921            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12922            return res;
12923        }
12924
12925        @Override
12926        protected void sortResults(List<ResolveInfo> results) {
12927            Collections.sort(results, mResolvePrioritySorter);
12928        }
12929
12930        @Override
12931        protected void dumpFilter(PrintWriter out, String prefix,
12932                PackageParser.ServiceIntentInfo filter) {
12933            out.print(prefix); out.print(
12934                    Integer.toHexString(System.identityHashCode(filter.service)));
12935                    out.print(' ');
12936                    filter.service.printComponentShortName(out);
12937                    out.print(" filter ");
12938                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12939        }
12940
12941        @Override
12942        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12943            return filter.service;
12944        }
12945
12946        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12947            PackageParser.Service service = (PackageParser.Service)label;
12948            out.print(prefix); out.print(
12949                    Integer.toHexString(System.identityHashCode(service)));
12950                    out.print(' ');
12951                    service.printComponentShortName(out);
12952            if (count > 1) {
12953                out.print(" ("); out.print(count); out.print(" filters)");
12954            }
12955            out.println();
12956        }
12957
12958//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12959//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12960//            final List<ResolveInfo> retList = Lists.newArrayList();
12961//            while (i.hasNext()) {
12962//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12963//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12964//                    retList.add(resolveInfo);
12965//                }
12966//            }
12967//            return retList;
12968//        }
12969
12970        // Keys are String (activity class name), values are Activity.
12971        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12972                = new ArrayMap<ComponentName, PackageParser.Service>();
12973        private int mFlags;
12974    }
12975
12976    private final class ProviderIntentResolver
12977            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12978        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12979                boolean defaultOnly, int userId) {
12980            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12981            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12982        }
12983
12984        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12985                int userId) {
12986            if (!sUserManager.exists(userId))
12987                return null;
12988            mFlags = flags;
12989            return super.queryIntent(intent, resolvedType,
12990                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12991                    userId);
12992        }
12993
12994        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12995                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12996            if (!sUserManager.exists(userId))
12997                return null;
12998            if (packageProviders == null) {
12999                return null;
13000            }
13001            mFlags = flags;
13002            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13003            final int N = packageProviders.size();
13004            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13005                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13006
13007            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13008            for (int i = 0; i < N; ++i) {
13009                intentFilters = packageProviders.get(i).intents;
13010                if (intentFilters != null && intentFilters.size() > 0) {
13011                    PackageParser.ProviderIntentInfo[] array =
13012                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13013                    intentFilters.toArray(array);
13014                    listCut.add(array);
13015                }
13016            }
13017            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13018        }
13019
13020        public final void addProvider(PackageParser.Provider p) {
13021            if (mProviders.containsKey(p.getComponentName())) {
13022                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13023                return;
13024            }
13025
13026            mProviders.put(p.getComponentName(), p);
13027            if (DEBUG_SHOW_INFO) {
13028                Log.v(TAG, "  "
13029                        + (p.info.nonLocalizedLabel != null
13030                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13031                Log.v(TAG, "    Class=" + p.info.name);
13032            }
13033            final int NI = p.intents.size();
13034            int j;
13035            for (j = 0; j < NI; j++) {
13036                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13037                if (DEBUG_SHOW_INFO) {
13038                    Log.v(TAG, "    IntentFilter:");
13039                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13040                }
13041                if (!intent.debugCheck()) {
13042                    Log.w(TAG, "==> For Provider " + p.info.name);
13043                }
13044                addFilter(intent);
13045            }
13046        }
13047
13048        public final void removeProvider(PackageParser.Provider p) {
13049            mProviders.remove(p.getComponentName());
13050            if (DEBUG_SHOW_INFO) {
13051                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13052                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13053                Log.v(TAG, "    Class=" + p.info.name);
13054            }
13055            final int NI = p.intents.size();
13056            int j;
13057            for (j = 0; j < NI; j++) {
13058                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13059                if (DEBUG_SHOW_INFO) {
13060                    Log.v(TAG, "    IntentFilter:");
13061                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13062                }
13063                removeFilter(intent);
13064            }
13065        }
13066
13067        @Override
13068        protected boolean allowFilterResult(
13069                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13070            ProviderInfo filterPi = filter.provider.info;
13071            for (int i = dest.size() - 1; i >= 0; i--) {
13072                ProviderInfo destPi = dest.get(i).providerInfo;
13073                if (destPi.name == filterPi.name
13074                        && destPi.packageName == filterPi.packageName) {
13075                    return false;
13076                }
13077            }
13078            return true;
13079        }
13080
13081        @Override
13082        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13083            return new PackageParser.ProviderIntentInfo[size];
13084        }
13085
13086        @Override
13087        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13088            if (!sUserManager.exists(userId))
13089                return true;
13090            PackageParser.Package p = filter.provider.owner;
13091            if (p != null) {
13092                PackageSetting ps = (PackageSetting) p.mExtras;
13093                if (ps != null) {
13094                    // System apps are never considered stopped for purposes of
13095                    // filtering, because there may be no way for the user to
13096                    // actually re-launch them.
13097                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13098                            && ps.getStopped(userId);
13099                }
13100            }
13101            return false;
13102        }
13103
13104        @Override
13105        protected boolean isPackageForFilter(String packageName,
13106                PackageParser.ProviderIntentInfo info) {
13107            return packageName.equals(info.provider.owner.packageName);
13108        }
13109
13110        @Override
13111        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13112                int match, int userId) {
13113            if (!sUserManager.exists(userId))
13114                return null;
13115            final PackageParser.ProviderIntentInfo info = filter;
13116            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13117                return null;
13118            }
13119            final PackageParser.Provider provider = info.provider;
13120            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13121            if (ps == null) {
13122                return null;
13123            }
13124            final PackageUserState userState = ps.readUserState(userId);
13125            final boolean matchVisibleToInstantApp =
13126                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13127            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13128            // throw out filters that aren't visible to instant applications
13129            if (matchVisibleToInstantApp
13130                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13131                return null;
13132            }
13133            // throw out instant application filters if we're not explicitly requesting them
13134            if (!isInstantApp && userState.instantApp) {
13135                return null;
13136            }
13137            // throw out instant application filters if updates are available; will trigger
13138            // instant application resolution
13139            if (userState.instantApp && ps.isUpdateAvailable()) {
13140                return null;
13141            }
13142            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13143                    userState, userId);
13144            if (pi == null) {
13145                return null;
13146            }
13147            final ResolveInfo res = new ResolveInfo();
13148            res.providerInfo = pi;
13149            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13150                res.filter = filter;
13151            }
13152            res.priority = info.getPriority();
13153            res.preferredOrder = provider.owner.mPreferredOrder;
13154            res.match = match;
13155            res.isDefault = info.hasDefault;
13156            res.labelRes = info.labelRes;
13157            res.nonLocalizedLabel = info.nonLocalizedLabel;
13158            res.icon = info.icon;
13159            res.system = res.providerInfo.applicationInfo.isSystemApp();
13160            return res;
13161        }
13162
13163        @Override
13164        protected void sortResults(List<ResolveInfo> results) {
13165            Collections.sort(results, mResolvePrioritySorter);
13166        }
13167
13168        @Override
13169        protected void dumpFilter(PrintWriter out, String prefix,
13170                PackageParser.ProviderIntentInfo filter) {
13171            out.print(prefix);
13172            out.print(
13173                    Integer.toHexString(System.identityHashCode(filter.provider)));
13174            out.print(' ');
13175            filter.provider.printComponentShortName(out);
13176            out.print(" filter ");
13177            out.println(Integer.toHexString(System.identityHashCode(filter)));
13178        }
13179
13180        @Override
13181        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13182            return filter.provider;
13183        }
13184
13185        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13186            PackageParser.Provider provider = (PackageParser.Provider)label;
13187            out.print(prefix); out.print(
13188                    Integer.toHexString(System.identityHashCode(provider)));
13189                    out.print(' ');
13190                    provider.printComponentShortName(out);
13191            if (count > 1) {
13192                out.print(" ("); out.print(count); out.print(" filters)");
13193            }
13194            out.println();
13195        }
13196
13197        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13198                = new ArrayMap<ComponentName, PackageParser.Provider>();
13199        private int mFlags;
13200    }
13201
13202    static final class EphemeralIntentResolver
13203            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13204        /**
13205         * The result that has the highest defined order. Ordering applies on a
13206         * per-package basis. Mapping is from package name to Pair of order and
13207         * EphemeralResolveInfo.
13208         * <p>
13209         * NOTE: This is implemented as a field variable for convenience and efficiency.
13210         * By having a field variable, we're able to track filter ordering as soon as
13211         * a non-zero order is defined. Otherwise, multiple loops across the result set
13212         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13213         * this needs to be contained entirely within {@link #filterResults}.
13214         */
13215        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13216
13217        @Override
13218        protected AuxiliaryResolveInfo[] newArray(int size) {
13219            return new AuxiliaryResolveInfo[size];
13220        }
13221
13222        @Override
13223        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13224            return true;
13225        }
13226
13227        @Override
13228        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13229                int userId) {
13230            if (!sUserManager.exists(userId)) {
13231                return null;
13232            }
13233            final String packageName = responseObj.resolveInfo.getPackageName();
13234            final Integer order = responseObj.getOrder();
13235            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13236                    mOrderResult.get(packageName);
13237            // ordering is enabled and this item's order isn't high enough
13238            if (lastOrderResult != null && lastOrderResult.first >= order) {
13239                return null;
13240            }
13241            final InstantAppResolveInfo res = responseObj.resolveInfo;
13242            if (order > 0) {
13243                // non-zero order, enable ordering
13244                mOrderResult.put(packageName, new Pair<>(order, res));
13245            }
13246            return responseObj;
13247        }
13248
13249        @Override
13250        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13251            // only do work if ordering is enabled [most of the time it won't be]
13252            if (mOrderResult.size() == 0) {
13253                return;
13254            }
13255            int resultSize = results.size();
13256            for (int i = 0; i < resultSize; i++) {
13257                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13258                final String packageName = info.getPackageName();
13259                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13260                if (savedInfo == null) {
13261                    // package doesn't having ordering
13262                    continue;
13263                }
13264                if (savedInfo.second == info) {
13265                    // circled back to the highest ordered item; remove from order list
13266                    mOrderResult.remove(savedInfo);
13267                    if (mOrderResult.size() == 0) {
13268                        // no more ordered items
13269                        break;
13270                    }
13271                    continue;
13272                }
13273                // item has a worse order, remove it from the result list
13274                results.remove(i);
13275                resultSize--;
13276                i--;
13277            }
13278        }
13279    }
13280
13281    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13282            new Comparator<ResolveInfo>() {
13283        public int compare(ResolveInfo r1, ResolveInfo r2) {
13284            int v1 = r1.priority;
13285            int v2 = r2.priority;
13286            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13287            if (v1 != v2) {
13288                return (v1 > v2) ? -1 : 1;
13289            }
13290            v1 = r1.preferredOrder;
13291            v2 = r2.preferredOrder;
13292            if (v1 != v2) {
13293                return (v1 > v2) ? -1 : 1;
13294            }
13295            if (r1.isDefault != r2.isDefault) {
13296                return r1.isDefault ? -1 : 1;
13297            }
13298            v1 = r1.match;
13299            v2 = r2.match;
13300            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13301            if (v1 != v2) {
13302                return (v1 > v2) ? -1 : 1;
13303            }
13304            if (r1.system != r2.system) {
13305                return r1.system ? -1 : 1;
13306            }
13307            if (r1.activityInfo != null) {
13308                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13309            }
13310            if (r1.serviceInfo != null) {
13311                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13312            }
13313            if (r1.providerInfo != null) {
13314                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13315            }
13316            return 0;
13317        }
13318    };
13319
13320    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13321            new Comparator<ProviderInfo>() {
13322        public int compare(ProviderInfo p1, ProviderInfo p2) {
13323            final int v1 = p1.initOrder;
13324            final int v2 = p2.initOrder;
13325            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13326        }
13327    };
13328
13329    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13330            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13331            final int[] userIds) {
13332        mHandler.post(new Runnable() {
13333            @Override
13334            public void run() {
13335                try {
13336                    final IActivityManager am = ActivityManager.getService();
13337                    if (am == null) return;
13338                    final int[] resolvedUserIds;
13339                    if (userIds == null) {
13340                        resolvedUserIds = am.getRunningUserIds();
13341                    } else {
13342                        resolvedUserIds = userIds;
13343                    }
13344                    for (int id : resolvedUserIds) {
13345                        final Intent intent = new Intent(action,
13346                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13347                        if (extras != null) {
13348                            intent.putExtras(extras);
13349                        }
13350                        if (targetPkg != null) {
13351                            intent.setPackage(targetPkg);
13352                        }
13353                        // Modify the UID when posting to other users
13354                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13355                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13356                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13357                            intent.putExtra(Intent.EXTRA_UID, uid);
13358                        }
13359                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13360                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13361                        if (DEBUG_BROADCASTS) {
13362                            RuntimeException here = new RuntimeException("here");
13363                            here.fillInStackTrace();
13364                            Slog.d(TAG, "Sending to user " + id + ": "
13365                                    + intent.toShortString(false, true, false, false)
13366                                    + " " + intent.getExtras(), here);
13367                        }
13368                        am.broadcastIntent(null, intent, null, finishedReceiver,
13369                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13370                                null, finishedReceiver != null, false, id);
13371                    }
13372                } catch (RemoteException ex) {
13373                }
13374            }
13375        });
13376    }
13377
13378    /**
13379     * Check if the external storage media is available. This is true if there
13380     * is a mounted external storage medium or if the external storage is
13381     * emulated.
13382     */
13383    private boolean isExternalMediaAvailable() {
13384        return mMediaMounted || Environment.isExternalStorageEmulated();
13385    }
13386
13387    @Override
13388    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13389        // writer
13390        synchronized (mPackages) {
13391            if (!isExternalMediaAvailable()) {
13392                // If the external storage is no longer mounted at this point,
13393                // the caller may not have been able to delete all of this
13394                // packages files and can not delete any more.  Bail.
13395                return null;
13396            }
13397            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13398            if (lastPackage != null) {
13399                pkgs.remove(lastPackage);
13400            }
13401            if (pkgs.size() > 0) {
13402                return pkgs.get(0);
13403            }
13404        }
13405        return null;
13406    }
13407
13408    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13409        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13410                userId, andCode ? 1 : 0, packageName);
13411        if (mSystemReady) {
13412            msg.sendToTarget();
13413        } else {
13414            if (mPostSystemReadyMessages == null) {
13415                mPostSystemReadyMessages = new ArrayList<>();
13416            }
13417            mPostSystemReadyMessages.add(msg);
13418        }
13419    }
13420
13421    void startCleaningPackages() {
13422        // reader
13423        if (!isExternalMediaAvailable()) {
13424            return;
13425        }
13426        synchronized (mPackages) {
13427            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13428                return;
13429            }
13430        }
13431        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13432        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13433        IActivityManager am = ActivityManager.getService();
13434        if (am != null) {
13435            int dcsUid = -1;
13436            synchronized (mPackages) {
13437                if (!mDefaultContainerWhitelisted) {
13438                    mDefaultContainerWhitelisted = true;
13439                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13440                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13441                }
13442            }
13443            try {
13444                if (dcsUid > 0) {
13445                    am.backgroundWhitelistUid(dcsUid);
13446                }
13447                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13448                        UserHandle.USER_SYSTEM);
13449            } catch (RemoteException e) {
13450            }
13451        }
13452    }
13453
13454    @Override
13455    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13456            int installFlags, String installerPackageName, int userId) {
13457        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13458
13459        final int callingUid = Binder.getCallingUid();
13460        enforceCrossUserPermission(callingUid, userId,
13461                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13462
13463        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13464            try {
13465                if (observer != null) {
13466                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13467                }
13468            } catch (RemoteException re) {
13469            }
13470            return;
13471        }
13472
13473        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13474            installFlags |= PackageManager.INSTALL_FROM_ADB;
13475
13476        } else {
13477            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13478            // about installerPackageName.
13479
13480            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13481            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13482        }
13483
13484        UserHandle user;
13485        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13486            user = UserHandle.ALL;
13487        } else {
13488            user = new UserHandle(userId);
13489        }
13490
13491        // Only system components can circumvent runtime permissions when installing.
13492        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13493                && mContext.checkCallingOrSelfPermission(Manifest.permission
13494                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13495            throw new SecurityException("You need the "
13496                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13497                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13498        }
13499
13500        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13501                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13502            throw new IllegalArgumentException(
13503                    "New installs into ASEC containers no longer supported");
13504        }
13505
13506        final File originFile = new File(originPath);
13507        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13508
13509        final Message msg = mHandler.obtainMessage(INIT_COPY);
13510        final VerificationInfo verificationInfo = new VerificationInfo(
13511                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13512        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13513                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13514                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13515                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13516        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13517        msg.obj = params;
13518
13519        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13520                System.identityHashCode(msg.obj));
13521        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13522                System.identityHashCode(msg.obj));
13523
13524        mHandler.sendMessage(msg);
13525    }
13526
13527
13528    /**
13529     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13530     * it is acting on behalf on an enterprise or the user).
13531     *
13532     * Note that the ordering of the conditionals in this method is important. The checks we perform
13533     * are as follows, in this order:
13534     *
13535     * 1) If the install is being performed by a system app, we can trust the app to have set the
13536     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13537     *    what it is.
13538     * 2) If the install is being performed by a device or profile owner app, the install reason
13539     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13540     *    set the install reason correctly. If the app targets an older SDK version where install
13541     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13542     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13543     * 3) In all other cases, the install is being performed by a regular app that is neither part
13544     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13545     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13546     *    set to enterprise policy and if so, change it to unknown instead.
13547     */
13548    private int fixUpInstallReason(String installerPackageName, int installerUid,
13549            int installReason) {
13550        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13551                == PERMISSION_GRANTED) {
13552            // If the install is being performed by a system app, we trust that app to have set the
13553            // install reason correctly.
13554            return installReason;
13555        }
13556
13557        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13558            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13559        if (dpm != null) {
13560            ComponentName owner = null;
13561            try {
13562                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13563                if (owner == null) {
13564                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13565                }
13566            } catch (RemoteException e) {
13567            }
13568            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13569                // If the install is being performed by a device or profile owner, the install
13570                // reason should be enterprise policy.
13571                return PackageManager.INSTALL_REASON_POLICY;
13572            }
13573        }
13574
13575        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13576            // If the install is being performed by a regular app (i.e. neither system app nor
13577            // device or profile owner), we have no reason to believe that the app is acting on
13578            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13579            // change it to unknown instead.
13580            return PackageManager.INSTALL_REASON_UNKNOWN;
13581        }
13582
13583        // If the install is being performed by a regular app and the install reason was set to any
13584        // value but enterprise policy, leave the install reason unchanged.
13585        return installReason;
13586    }
13587
13588    void installStage(String packageName, File stagedDir, String stagedCid,
13589            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13590            String installerPackageName, int installerUid, UserHandle user,
13591            Certificate[][] certificates) {
13592        if (DEBUG_EPHEMERAL) {
13593            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13594                Slog.d(TAG, "Ephemeral install of " + packageName);
13595            }
13596        }
13597        final VerificationInfo verificationInfo = new VerificationInfo(
13598                sessionParams.originatingUri, sessionParams.referrerUri,
13599                sessionParams.originatingUid, installerUid);
13600
13601        final OriginInfo origin;
13602        if (stagedDir != null) {
13603            origin = OriginInfo.fromStagedFile(stagedDir);
13604        } else {
13605            origin = OriginInfo.fromStagedContainer(stagedCid);
13606        }
13607
13608        final Message msg = mHandler.obtainMessage(INIT_COPY);
13609        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13610                sessionParams.installReason);
13611        final InstallParams params = new InstallParams(origin, null, observer,
13612                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13613                verificationInfo, user, sessionParams.abiOverride,
13614                sessionParams.grantedRuntimePermissions, certificates, installReason);
13615        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13616        msg.obj = params;
13617
13618        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13619                System.identityHashCode(msg.obj));
13620        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13621                System.identityHashCode(msg.obj));
13622
13623        mHandler.sendMessage(msg);
13624    }
13625
13626    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13627            int userId) {
13628        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13629        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13630    }
13631
13632    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13633        if (ArrayUtils.isEmpty(userIds)) {
13634            return;
13635        }
13636        Bundle extras = new Bundle(1);
13637        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13638        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13639
13640        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13641                packageName, extras, 0, null, null, userIds);
13642        if (isSystem) {
13643            mHandler.post(() -> {
13644                        for (int userId : userIds) {
13645                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13646                        }
13647                    }
13648            );
13649        }
13650    }
13651
13652    /**
13653     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13654     * automatically without needing an explicit launch.
13655     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13656     */
13657    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13658        // If user is not running, the app didn't miss any broadcast
13659        if (!mUserManagerInternal.isUserRunning(userId)) {
13660            return;
13661        }
13662        final IActivityManager am = ActivityManager.getService();
13663        try {
13664            // Deliver LOCKED_BOOT_COMPLETED first
13665            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13666                    .setPackage(packageName);
13667            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13668            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13669                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13670
13671            // Deliver BOOT_COMPLETED only if user is unlocked
13672            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13673                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13674                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13675                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13676            }
13677        } catch (RemoteException e) {
13678            throw e.rethrowFromSystemServer();
13679        }
13680    }
13681
13682    @Override
13683    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13684            int userId) {
13685        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13686        PackageSetting pkgSetting;
13687        final int uid = Binder.getCallingUid();
13688        enforceCrossUserPermission(uid, userId,
13689                true /* requireFullPermission */, true /* checkShell */,
13690                "setApplicationHiddenSetting for user " + userId);
13691
13692        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13693            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13694            return false;
13695        }
13696
13697        long callingId = Binder.clearCallingIdentity();
13698        try {
13699            boolean sendAdded = false;
13700            boolean sendRemoved = false;
13701            // writer
13702            synchronized (mPackages) {
13703                pkgSetting = mSettings.mPackages.get(packageName);
13704                if (pkgSetting == null) {
13705                    return false;
13706                }
13707                // Do not allow "android" is being disabled
13708                if ("android".equals(packageName)) {
13709                    Slog.w(TAG, "Cannot hide package: android");
13710                    return false;
13711                }
13712                // Cannot hide static shared libs as they are considered
13713                // a part of the using app (emulating static linking). Also
13714                // static libs are installed always on internal storage.
13715                PackageParser.Package pkg = mPackages.get(packageName);
13716                if (pkg != null && pkg.staticSharedLibName != null) {
13717                    Slog.w(TAG, "Cannot hide package: " + packageName
13718                            + " providing static shared library: "
13719                            + pkg.staticSharedLibName);
13720                    return false;
13721                }
13722                // Only allow protected packages to hide themselves.
13723                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13724                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13725                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13726                    return false;
13727                }
13728
13729                if (pkgSetting.getHidden(userId) != hidden) {
13730                    pkgSetting.setHidden(hidden, userId);
13731                    mSettings.writePackageRestrictionsLPr(userId);
13732                    if (hidden) {
13733                        sendRemoved = true;
13734                    } else {
13735                        sendAdded = true;
13736                    }
13737                }
13738            }
13739            if (sendAdded) {
13740                sendPackageAddedForUser(packageName, pkgSetting, userId);
13741                return true;
13742            }
13743            if (sendRemoved) {
13744                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13745                        "hiding pkg");
13746                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13747                return true;
13748            }
13749        } finally {
13750            Binder.restoreCallingIdentity(callingId);
13751        }
13752        return false;
13753    }
13754
13755    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13756            int userId) {
13757        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13758        info.removedPackage = packageName;
13759        info.installerPackageName = pkgSetting.installerPackageName;
13760        info.removedUsers = new int[] {userId};
13761        info.broadcastUsers = new int[] {userId};
13762        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13763        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13764    }
13765
13766    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13767        if (pkgList.length > 0) {
13768            Bundle extras = new Bundle(1);
13769            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13770
13771            sendPackageBroadcast(
13772                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13773                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13774                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13775                    new int[] {userId});
13776        }
13777    }
13778
13779    /**
13780     * Returns true if application is not found or there was an error. Otherwise it returns
13781     * the hidden state of the package for the given user.
13782     */
13783    @Override
13784    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13785        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13786        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13787                true /* requireFullPermission */, false /* checkShell */,
13788                "getApplicationHidden for user " + userId);
13789        PackageSetting pkgSetting;
13790        long callingId = Binder.clearCallingIdentity();
13791        try {
13792            // writer
13793            synchronized (mPackages) {
13794                pkgSetting = mSettings.mPackages.get(packageName);
13795                if (pkgSetting == null) {
13796                    return true;
13797                }
13798                return pkgSetting.getHidden(userId);
13799            }
13800        } finally {
13801            Binder.restoreCallingIdentity(callingId);
13802        }
13803    }
13804
13805    /**
13806     * @hide
13807     */
13808    @Override
13809    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13810            int installReason) {
13811        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13812                null);
13813        PackageSetting pkgSetting;
13814        final int uid = Binder.getCallingUid();
13815        enforceCrossUserPermission(uid, userId,
13816                true /* requireFullPermission */, true /* checkShell */,
13817                "installExistingPackage for user " + userId);
13818        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13819            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13820        }
13821
13822        long callingId = Binder.clearCallingIdentity();
13823        try {
13824            boolean installed = false;
13825            final boolean instantApp =
13826                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13827            final boolean fullApp =
13828                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13829
13830            // writer
13831            synchronized (mPackages) {
13832                pkgSetting = mSettings.mPackages.get(packageName);
13833                if (pkgSetting == null) {
13834                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13835                }
13836                if (!pkgSetting.getInstalled(userId)) {
13837                    pkgSetting.setInstalled(true, userId);
13838                    pkgSetting.setHidden(false, userId);
13839                    pkgSetting.setInstallReason(installReason, userId);
13840                    mSettings.writePackageRestrictionsLPr(userId);
13841                    mSettings.writeKernelMappingLPr(pkgSetting);
13842                    installed = true;
13843                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13844                    // upgrade app from instant to full; we don't allow app downgrade
13845                    installed = true;
13846                }
13847                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13848            }
13849
13850            if (installed) {
13851                if (pkgSetting.pkg != null) {
13852                    synchronized (mInstallLock) {
13853                        // We don't need to freeze for a brand new install
13854                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13855                    }
13856                }
13857                sendPackageAddedForUser(packageName, pkgSetting, userId);
13858                synchronized (mPackages) {
13859                    updateSequenceNumberLP(packageName, new int[]{ userId });
13860                }
13861            }
13862        } finally {
13863            Binder.restoreCallingIdentity(callingId);
13864        }
13865
13866        return PackageManager.INSTALL_SUCCEEDED;
13867    }
13868
13869    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13870            boolean instantApp, boolean fullApp) {
13871        // no state specified; do nothing
13872        if (!instantApp && !fullApp) {
13873            return;
13874        }
13875        if (userId != UserHandle.USER_ALL) {
13876            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13877                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13878            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13879                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13880            }
13881        } else {
13882            for (int currentUserId : sUserManager.getUserIds()) {
13883                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13884                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13885                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13886                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13887                }
13888            }
13889        }
13890    }
13891
13892    boolean isUserRestricted(int userId, String restrictionKey) {
13893        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13894        if (restrictions.getBoolean(restrictionKey, false)) {
13895            Log.w(TAG, "User is restricted: " + restrictionKey);
13896            return true;
13897        }
13898        return false;
13899    }
13900
13901    @Override
13902    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13903            int userId) {
13904        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13905        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13906                true /* requireFullPermission */, true /* checkShell */,
13907                "setPackagesSuspended for user " + userId);
13908
13909        if (ArrayUtils.isEmpty(packageNames)) {
13910            return packageNames;
13911        }
13912
13913        // List of package names for whom the suspended state has changed.
13914        List<String> changedPackages = new ArrayList<>(packageNames.length);
13915        // List of package names for whom the suspended state is not set as requested in this
13916        // method.
13917        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13918        long callingId = Binder.clearCallingIdentity();
13919        try {
13920            for (int i = 0; i < packageNames.length; i++) {
13921                String packageName = packageNames[i];
13922                boolean changed = false;
13923                final int appId;
13924                synchronized (mPackages) {
13925                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13926                    if (pkgSetting == null) {
13927                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13928                                + "\". Skipping suspending/un-suspending.");
13929                        unactionedPackages.add(packageName);
13930                        continue;
13931                    }
13932                    appId = pkgSetting.appId;
13933                    if (pkgSetting.getSuspended(userId) != suspended) {
13934                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13935                            unactionedPackages.add(packageName);
13936                            continue;
13937                        }
13938                        pkgSetting.setSuspended(suspended, userId);
13939                        mSettings.writePackageRestrictionsLPr(userId);
13940                        changed = true;
13941                        changedPackages.add(packageName);
13942                    }
13943                }
13944
13945                if (changed && suspended) {
13946                    killApplication(packageName, UserHandle.getUid(userId, appId),
13947                            "suspending package");
13948                }
13949            }
13950        } finally {
13951            Binder.restoreCallingIdentity(callingId);
13952        }
13953
13954        if (!changedPackages.isEmpty()) {
13955            sendPackagesSuspendedForUser(changedPackages.toArray(
13956                    new String[changedPackages.size()]), userId, suspended);
13957        }
13958
13959        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13960    }
13961
13962    @Override
13963    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13964        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13965                true /* requireFullPermission */, false /* checkShell */,
13966                "isPackageSuspendedForUser for user " + userId);
13967        synchronized (mPackages) {
13968            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13969            if (pkgSetting == null) {
13970                throw new IllegalArgumentException("Unknown target package: " + packageName);
13971            }
13972            return pkgSetting.getSuspended(userId);
13973        }
13974    }
13975
13976    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13977        if (isPackageDeviceAdmin(packageName, userId)) {
13978            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13979                    + "\": has an active device admin");
13980            return false;
13981        }
13982
13983        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13984        if (packageName.equals(activeLauncherPackageName)) {
13985            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13986                    + "\": contains the active launcher");
13987            return false;
13988        }
13989
13990        if (packageName.equals(mRequiredInstallerPackage)) {
13991            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13992                    + "\": required for package installation");
13993            return false;
13994        }
13995
13996        if (packageName.equals(mRequiredUninstallerPackage)) {
13997            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13998                    + "\": required for package uninstallation");
13999            return false;
14000        }
14001
14002        if (packageName.equals(mRequiredVerifierPackage)) {
14003            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14004                    + "\": required for package verification");
14005            return false;
14006        }
14007
14008        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14009            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14010                    + "\": is the default dialer");
14011            return false;
14012        }
14013
14014        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14015            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14016                    + "\": protected package");
14017            return false;
14018        }
14019
14020        // Cannot suspend static shared libs as they are considered
14021        // a part of the using app (emulating static linking). Also
14022        // static libs are installed always on internal storage.
14023        PackageParser.Package pkg = mPackages.get(packageName);
14024        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14025            Slog.w(TAG, "Cannot suspend package: " + packageName
14026                    + " providing static shared library: "
14027                    + pkg.staticSharedLibName);
14028            return false;
14029        }
14030
14031        return true;
14032    }
14033
14034    private String getActiveLauncherPackageName(int userId) {
14035        Intent intent = new Intent(Intent.ACTION_MAIN);
14036        intent.addCategory(Intent.CATEGORY_HOME);
14037        ResolveInfo resolveInfo = resolveIntent(
14038                intent,
14039                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14040                PackageManager.MATCH_DEFAULT_ONLY,
14041                userId);
14042
14043        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14044    }
14045
14046    private String getDefaultDialerPackageName(int userId) {
14047        synchronized (mPackages) {
14048            return mSettings.getDefaultDialerPackageNameLPw(userId);
14049        }
14050    }
14051
14052    @Override
14053    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14054        mContext.enforceCallingOrSelfPermission(
14055                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14056                "Only package verification agents can verify applications");
14057
14058        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14059        final PackageVerificationResponse response = new PackageVerificationResponse(
14060                verificationCode, Binder.getCallingUid());
14061        msg.arg1 = id;
14062        msg.obj = response;
14063        mHandler.sendMessage(msg);
14064    }
14065
14066    @Override
14067    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14068            long millisecondsToDelay) {
14069        mContext.enforceCallingOrSelfPermission(
14070                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14071                "Only package verification agents can extend verification timeouts");
14072
14073        final PackageVerificationState state = mPendingVerification.get(id);
14074        final PackageVerificationResponse response = new PackageVerificationResponse(
14075                verificationCodeAtTimeout, Binder.getCallingUid());
14076
14077        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14078            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14079        }
14080        if (millisecondsToDelay < 0) {
14081            millisecondsToDelay = 0;
14082        }
14083        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14084                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14085            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14086        }
14087
14088        if ((state != null) && !state.timeoutExtended()) {
14089            state.extendTimeout();
14090
14091            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14092            msg.arg1 = id;
14093            msg.obj = response;
14094            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14095        }
14096    }
14097
14098    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14099            int verificationCode, UserHandle user) {
14100        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14101        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14102        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14103        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14104        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14105
14106        mContext.sendBroadcastAsUser(intent, user,
14107                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14108    }
14109
14110    private ComponentName matchComponentForVerifier(String packageName,
14111            List<ResolveInfo> receivers) {
14112        ActivityInfo targetReceiver = null;
14113
14114        final int NR = receivers.size();
14115        for (int i = 0; i < NR; i++) {
14116            final ResolveInfo info = receivers.get(i);
14117            if (info.activityInfo == null) {
14118                continue;
14119            }
14120
14121            if (packageName.equals(info.activityInfo.packageName)) {
14122                targetReceiver = info.activityInfo;
14123                break;
14124            }
14125        }
14126
14127        if (targetReceiver == null) {
14128            return null;
14129        }
14130
14131        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14132    }
14133
14134    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14135            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14136        if (pkgInfo.verifiers.length == 0) {
14137            return null;
14138        }
14139
14140        final int N = pkgInfo.verifiers.length;
14141        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14142        for (int i = 0; i < N; i++) {
14143            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14144
14145            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14146                    receivers);
14147            if (comp == null) {
14148                continue;
14149            }
14150
14151            final int verifierUid = getUidForVerifier(verifierInfo);
14152            if (verifierUid == -1) {
14153                continue;
14154            }
14155
14156            if (DEBUG_VERIFY) {
14157                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14158                        + " with the correct signature");
14159            }
14160            sufficientVerifiers.add(comp);
14161            verificationState.addSufficientVerifier(verifierUid);
14162        }
14163
14164        return sufficientVerifiers;
14165    }
14166
14167    private int getUidForVerifier(VerifierInfo verifierInfo) {
14168        synchronized (mPackages) {
14169            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14170            if (pkg == null) {
14171                return -1;
14172            } else if (pkg.mSignatures.length != 1) {
14173                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14174                        + " has more than one signature; ignoring");
14175                return -1;
14176            }
14177
14178            /*
14179             * If the public key of the package's signature does not match
14180             * our expected public key, then this is a different package and
14181             * we should skip.
14182             */
14183
14184            final byte[] expectedPublicKey;
14185            try {
14186                final Signature verifierSig = pkg.mSignatures[0];
14187                final PublicKey publicKey = verifierSig.getPublicKey();
14188                expectedPublicKey = publicKey.getEncoded();
14189            } catch (CertificateException e) {
14190                return -1;
14191            }
14192
14193            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14194
14195            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14196                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14197                        + " does not have the expected public key; ignoring");
14198                return -1;
14199            }
14200
14201            return pkg.applicationInfo.uid;
14202        }
14203    }
14204
14205    @Override
14206    public void finishPackageInstall(int token, boolean didLaunch) {
14207        enforceSystemOrRoot("Only the system is allowed to finish installs");
14208
14209        if (DEBUG_INSTALL) {
14210            Slog.v(TAG, "BM finishing package install for " + token);
14211        }
14212        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14213
14214        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14215        mHandler.sendMessage(msg);
14216    }
14217
14218    /**
14219     * Get the verification agent timeout.  Used for both the APK verifier and the
14220     * intent filter verifier.
14221     *
14222     * @return verification timeout in milliseconds
14223     */
14224    private long getVerificationTimeout() {
14225        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14226                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14227                DEFAULT_VERIFICATION_TIMEOUT);
14228    }
14229
14230    /**
14231     * Get the default verification agent response code.
14232     *
14233     * @return default verification response code
14234     */
14235    private int getDefaultVerificationResponse(UserHandle user) {
14236        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14237            return PackageManager.VERIFICATION_REJECT;
14238        }
14239        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14240                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14241                DEFAULT_VERIFICATION_RESPONSE);
14242    }
14243
14244    /**
14245     * Check whether or not package verification has been enabled.
14246     *
14247     * @return true if verification should be performed
14248     */
14249    private boolean isVerificationEnabled(int userId, int installFlags) {
14250        if (!DEFAULT_VERIFY_ENABLE) {
14251            return false;
14252        }
14253
14254        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14255
14256        // Check if installing from ADB
14257        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14258            // Do not run verification in a test harness environment
14259            if (ActivityManager.isRunningInTestHarness()) {
14260                return false;
14261            }
14262            if (ensureVerifyAppsEnabled) {
14263                return true;
14264            }
14265            // Check if the developer does not want package verification for ADB installs
14266            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14267                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14268                return false;
14269            }
14270        }
14271
14272        if (ensureVerifyAppsEnabled) {
14273            return true;
14274        }
14275
14276        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14277                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14278    }
14279
14280    @Override
14281    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14282            throws RemoteException {
14283        mContext.enforceCallingOrSelfPermission(
14284                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14285                "Only intentfilter verification agents can verify applications");
14286
14287        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14288        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14289                Binder.getCallingUid(), verificationCode, failedDomains);
14290        msg.arg1 = id;
14291        msg.obj = response;
14292        mHandler.sendMessage(msg);
14293    }
14294
14295    @Override
14296    public int getIntentVerificationStatus(String packageName, int userId) {
14297        synchronized (mPackages) {
14298            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14299        }
14300    }
14301
14302    @Override
14303    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14304        mContext.enforceCallingOrSelfPermission(
14305                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14306
14307        boolean result = false;
14308        synchronized (mPackages) {
14309            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14310        }
14311        if (result) {
14312            scheduleWritePackageRestrictionsLocked(userId);
14313        }
14314        return result;
14315    }
14316
14317    @Override
14318    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14319            String packageName) {
14320        synchronized (mPackages) {
14321            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14322        }
14323    }
14324
14325    @Override
14326    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14327        if (TextUtils.isEmpty(packageName)) {
14328            return ParceledListSlice.emptyList();
14329        }
14330        synchronized (mPackages) {
14331            PackageParser.Package pkg = mPackages.get(packageName);
14332            if (pkg == null || pkg.activities == null) {
14333                return ParceledListSlice.emptyList();
14334            }
14335            final int count = pkg.activities.size();
14336            ArrayList<IntentFilter> result = new ArrayList<>();
14337            for (int n=0; n<count; n++) {
14338                PackageParser.Activity activity = pkg.activities.get(n);
14339                if (activity.intents != null && activity.intents.size() > 0) {
14340                    result.addAll(activity.intents);
14341                }
14342            }
14343            return new ParceledListSlice<>(result);
14344        }
14345    }
14346
14347    @Override
14348    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14349        mContext.enforceCallingOrSelfPermission(
14350                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14351
14352        synchronized (mPackages) {
14353            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14354            if (packageName != null) {
14355                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14356                        packageName, userId);
14357            }
14358            return result;
14359        }
14360    }
14361
14362    @Override
14363    public String getDefaultBrowserPackageName(int userId) {
14364        synchronized (mPackages) {
14365            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14366        }
14367    }
14368
14369    /**
14370     * Get the "allow unknown sources" setting.
14371     *
14372     * @return the current "allow unknown sources" setting
14373     */
14374    private int getUnknownSourcesSettings() {
14375        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14376                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14377                -1);
14378    }
14379
14380    @Override
14381    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14382        final int uid = Binder.getCallingUid();
14383        // writer
14384        synchronized (mPackages) {
14385            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14386            if (targetPackageSetting == null) {
14387                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14388            }
14389
14390            PackageSetting installerPackageSetting;
14391            if (installerPackageName != null) {
14392                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14393                if (installerPackageSetting == null) {
14394                    throw new IllegalArgumentException("Unknown installer package: "
14395                            + installerPackageName);
14396                }
14397            } else {
14398                installerPackageSetting = null;
14399            }
14400
14401            Signature[] callerSignature;
14402            Object obj = mSettings.getUserIdLPr(uid);
14403            if (obj != null) {
14404                if (obj instanceof SharedUserSetting) {
14405                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14406                } else if (obj instanceof PackageSetting) {
14407                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14408                } else {
14409                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14410                }
14411            } else {
14412                throw new SecurityException("Unknown calling UID: " + uid);
14413            }
14414
14415            // Verify: can't set installerPackageName to a package that is
14416            // not signed with the same cert as the caller.
14417            if (installerPackageSetting != null) {
14418                if (compareSignatures(callerSignature,
14419                        installerPackageSetting.signatures.mSignatures)
14420                        != PackageManager.SIGNATURE_MATCH) {
14421                    throw new SecurityException(
14422                            "Caller does not have same cert as new installer package "
14423                            + installerPackageName);
14424                }
14425            }
14426
14427            // Verify: if target already has an installer package, it must
14428            // be signed with the same cert as the caller.
14429            if (targetPackageSetting.installerPackageName != null) {
14430                PackageSetting setting = mSettings.mPackages.get(
14431                        targetPackageSetting.installerPackageName);
14432                // If the currently set package isn't valid, then it's always
14433                // okay to change it.
14434                if (setting != null) {
14435                    if (compareSignatures(callerSignature,
14436                            setting.signatures.mSignatures)
14437                            != PackageManager.SIGNATURE_MATCH) {
14438                        throw new SecurityException(
14439                                "Caller does not have same cert as old installer package "
14440                                + targetPackageSetting.installerPackageName);
14441                    }
14442                }
14443            }
14444
14445            // Okay!
14446            targetPackageSetting.installerPackageName = installerPackageName;
14447            if (installerPackageName != null) {
14448                mSettings.mInstallerPackages.add(installerPackageName);
14449            }
14450            scheduleWriteSettingsLocked();
14451        }
14452    }
14453
14454    @Override
14455    public void setApplicationCategoryHint(String packageName, int categoryHint,
14456            String callerPackageName) {
14457        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14458                callerPackageName);
14459        synchronized (mPackages) {
14460            PackageSetting ps = mSettings.mPackages.get(packageName);
14461            if (ps == null) {
14462                throw new IllegalArgumentException("Unknown target package " + packageName);
14463            }
14464
14465            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14466                throw new IllegalArgumentException("Calling package " + callerPackageName
14467                        + " is not installer for " + packageName);
14468            }
14469
14470            if (ps.categoryHint != categoryHint) {
14471                ps.categoryHint = categoryHint;
14472                scheduleWriteSettingsLocked();
14473            }
14474        }
14475    }
14476
14477    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14478        // Queue up an async operation since the package installation may take a little while.
14479        mHandler.post(new Runnable() {
14480            public void run() {
14481                mHandler.removeCallbacks(this);
14482                 // Result object to be returned
14483                PackageInstalledInfo res = new PackageInstalledInfo();
14484                res.setReturnCode(currentStatus);
14485                res.uid = -1;
14486                res.pkg = null;
14487                res.removedInfo = null;
14488                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14489                    args.doPreInstall(res.returnCode);
14490                    synchronized (mInstallLock) {
14491                        installPackageTracedLI(args, res);
14492                    }
14493                    args.doPostInstall(res.returnCode, res.uid);
14494                }
14495
14496                // A restore should be performed at this point if (a) the install
14497                // succeeded, (b) the operation is not an update, and (c) the new
14498                // package has not opted out of backup participation.
14499                final boolean update = res.removedInfo != null
14500                        && res.removedInfo.removedPackage != null;
14501                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14502                boolean doRestore = !update
14503                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14504
14505                // Set up the post-install work request bookkeeping.  This will be used
14506                // and cleaned up by the post-install event handling regardless of whether
14507                // there's a restore pass performed.  Token values are >= 1.
14508                int token;
14509                if (mNextInstallToken < 0) mNextInstallToken = 1;
14510                token = mNextInstallToken++;
14511
14512                PostInstallData data = new PostInstallData(args, res);
14513                mRunningInstalls.put(token, data);
14514                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14515
14516                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14517                    // Pass responsibility to the Backup Manager.  It will perform a
14518                    // restore if appropriate, then pass responsibility back to the
14519                    // Package Manager to run the post-install observer callbacks
14520                    // and broadcasts.
14521                    IBackupManager bm = IBackupManager.Stub.asInterface(
14522                            ServiceManager.getService(Context.BACKUP_SERVICE));
14523                    if (bm != null) {
14524                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14525                                + " to BM for possible restore");
14526                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14527                        try {
14528                            // TODO: http://b/22388012
14529                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14530                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14531                            } else {
14532                                doRestore = false;
14533                            }
14534                        } catch (RemoteException e) {
14535                            // can't happen; the backup manager is local
14536                        } catch (Exception e) {
14537                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14538                            doRestore = false;
14539                        }
14540                    } else {
14541                        Slog.e(TAG, "Backup Manager not found!");
14542                        doRestore = false;
14543                    }
14544                }
14545
14546                if (!doRestore) {
14547                    // No restore possible, or the Backup Manager was mysteriously not
14548                    // available -- just fire the post-install work request directly.
14549                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14550
14551                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14552
14553                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14554                    mHandler.sendMessage(msg);
14555                }
14556            }
14557        });
14558    }
14559
14560    /**
14561     * Callback from PackageSettings whenever an app is first transitioned out of the
14562     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14563     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14564     * here whether the app is the target of an ongoing install, and only send the
14565     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14566     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14567     * handling.
14568     */
14569    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14570        // Serialize this with the rest of the install-process message chain.  In the
14571        // restore-at-install case, this Runnable will necessarily run before the
14572        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14573        // are coherent.  In the non-restore case, the app has already completed install
14574        // and been launched through some other means, so it is not in a problematic
14575        // state for observers to see the FIRST_LAUNCH signal.
14576        mHandler.post(new Runnable() {
14577            @Override
14578            public void run() {
14579                for (int i = 0; i < mRunningInstalls.size(); i++) {
14580                    final PostInstallData data = mRunningInstalls.valueAt(i);
14581                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14582                        continue;
14583                    }
14584                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14585                        // right package; but is it for the right user?
14586                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14587                            if (userId == data.res.newUsers[uIndex]) {
14588                                if (DEBUG_BACKUP) {
14589                                    Slog.i(TAG, "Package " + pkgName
14590                                            + " being restored so deferring FIRST_LAUNCH");
14591                                }
14592                                return;
14593                            }
14594                        }
14595                    }
14596                }
14597                // didn't find it, so not being restored
14598                if (DEBUG_BACKUP) {
14599                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14600                }
14601                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14602            }
14603        });
14604    }
14605
14606    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14607        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14608                installerPkg, null, userIds);
14609    }
14610
14611    private abstract class HandlerParams {
14612        private static final int MAX_RETRIES = 4;
14613
14614        /**
14615         * Number of times startCopy() has been attempted and had a non-fatal
14616         * error.
14617         */
14618        private int mRetries = 0;
14619
14620        /** User handle for the user requesting the information or installation. */
14621        private final UserHandle mUser;
14622        String traceMethod;
14623        int traceCookie;
14624
14625        HandlerParams(UserHandle user) {
14626            mUser = user;
14627        }
14628
14629        UserHandle getUser() {
14630            return mUser;
14631        }
14632
14633        HandlerParams setTraceMethod(String traceMethod) {
14634            this.traceMethod = traceMethod;
14635            return this;
14636        }
14637
14638        HandlerParams setTraceCookie(int traceCookie) {
14639            this.traceCookie = traceCookie;
14640            return this;
14641        }
14642
14643        final boolean startCopy() {
14644            boolean res;
14645            try {
14646                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14647
14648                if (++mRetries > MAX_RETRIES) {
14649                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14650                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14651                    handleServiceError();
14652                    return false;
14653                } else {
14654                    handleStartCopy();
14655                    res = true;
14656                }
14657            } catch (RemoteException e) {
14658                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14659                mHandler.sendEmptyMessage(MCS_RECONNECT);
14660                res = false;
14661            }
14662            handleReturnCode();
14663            return res;
14664        }
14665
14666        final void serviceError() {
14667            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14668            handleServiceError();
14669            handleReturnCode();
14670        }
14671
14672        abstract void handleStartCopy() throws RemoteException;
14673        abstract void handleServiceError();
14674        abstract void handleReturnCode();
14675    }
14676
14677    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14678        for (File path : paths) {
14679            try {
14680                mcs.clearDirectory(path.getAbsolutePath());
14681            } catch (RemoteException e) {
14682            }
14683        }
14684    }
14685
14686    static class OriginInfo {
14687        /**
14688         * Location where install is coming from, before it has been
14689         * copied/renamed into place. This could be a single monolithic APK
14690         * file, or a cluster directory. This location may be untrusted.
14691         */
14692        final File file;
14693        final String cid;
14694
14695        /**
14696         * Flag indicating that {@link #file} or {@link #cid} has already been
14697         * staged, meaning downstream users don't need to defensively copy the
14698         * contents.
14699         */
14700        final boolean staged;
14701
14702        /**
14703         * Flag indicating that {@link #file} or {@link #cid} is an already
14704         * installed app that is being moved.
14705         */
14706        final boolean existing;
14707
14708        final String resolvedPath;
14709        final File resolvedFile;
14710
14711        static OriginInfo fromNothing() {
14712            return new OriginInfo(null, null, false, false);
14713        }
14714
14715        static OriginInfo fromUntrustedFile(File file) {
14716            return new OriginInfo(file, null, false, false);
14717        }
14718
14719        static OriginInfo fromExistingFile(File file) {
14720            return new OriginInfo(file, null, false, true);
14721        }
14722
14723        static OriginInfo fromStagedFile(File file) {
14724            return new OriginInfo(file, null, true, false);
14725        }
14726
14727        static OriginInfo fromStagedContainer(String cid) {
14728            return new OriginInfo(null, cid, true, false);
14729        }
14730
14731        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14732            this.file = file;
14733            this.cid = cid;
14734            this.staged = staged;
14735            this.existing = existing;
14736
14737            if (cid != null) {
14738                resolvedPath = PackageHelper.getSdDir(cid);
14739                resolvedFile = new File(resolvedPath);
14740            } else if (file != null) {
14741                resolvedPath = file.getAbsolutePath();
14742                resolvedFile = file;
14743            } else {
14744                resolvedPath = null;
14745                resolvedFile = null;
14746            }
14747        }
14748    }
14749
14750    static class MoveInfo {
14751        final int moveId;
14752        final String fromUuid;
14753        final String toUuid;
14754        final String packageName;
14755        final String dataAppName;
14756        final int appId;
14757        final String seinfo;
14758        final int targetSdkVersion;
14759
14760        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14761                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14762            this.moveId = moveId;
14763            this.fromUuid = fromUuid;
14764            this.toUuid = toUuid;
14765            this.packageName = packageName;
14766            this.dataAppName = dataAppName;
14767            this.appId = appId;
14768            this.seinfo = seinfo;
14769            this.targetSdkVersion = targetSdkVersion;
14770        }
14771    }
14772
14773    static class VerificationInfo {
14774        /** A constant used to indicate that a uid value is not present. */
14775        public static final int NO_UID = -1;
14776
14777        /** URI referencing where the package was downloaded from. */
14778        final Uri originatingUri;
14779
14780        /** HTTP referrer URI associated with the originatingURI. */
14781        final Uri referrer;
14782
14783        /** UID of the application that the install request originated from. */
14784        final int originatingUid;
14785
14786        /** UID of application requesting the install */
14787        final int installerUid;
14788
14789        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14790            this.originatingUri = originatingUri;
14791            this.referrer = referrer;
14792            this.originatingUid = originatingUid;
14793            this.installerUid = installerUid;
14794        }
14795    }
14796
14797    class InstallParams extends HandlerParams {
14798        final OriginInfo origin;
14799        final MoveInfo move;
14800        final IPackageInstallObserver2 observer;
14801        int installFlags;
14802        final String installerPackageName;
14803        final String volumeUuid;
14804        private InstallArgs mArgs;
14805        private int mRet;
14806        final String packageAbiOverride;
14807        final String[] grantedRuntimePermissions;
14808        final VerificationInfo verificationInfo;
14809        final Certificate[][] certificates;
14810        final int installReason;
14811
14812        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14813                int installFlags, String installerPackageName, String volumeUuid,
14814                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14815                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14816            super(user);
14817            this.origin = origin;
14818            this.move = move;
14819            this.observer = observer;
14820            this.installFlags = installFlags;
14821            this.installerPackageName = installerPackageName;
14822            this.volumeUuid = volumeUuid;
14823            this.verificationInfo = verificationInfo;
14824            this.packageAbiOverride = packageAbiOverride;
14825            this.grantedRuntimePermissions = grantedPermissions;
14826            this.certificates = certificates;
14827            this.installReason = installReason;
14828        }
14829
14830        @Override
14831        public String toString() {
14832            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14833                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14834        }
14835
14836        private int installLocationPolicy(PackageInfoLite pkgLite) {
14837            String packageName = pkgLite.packageName;
14838            int installLocation = pkgLite.installLocation;
14839            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14840            // reader
14841            synchronized (mPackages) {
14842                // Currently installed package which the new package is attempting to replace or
14843                // null if no such package is installed.
14844                PackageParser.Package installedPkg = mPackages.get(packageName);
14845                // Package which currently owns the data which the new package will own if installed.
14846                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14847                // will be null whereas dataOwnerPkg will contain information about the package
14848                // which was uninstalled while keeping its data.
14849                PackageParser.Package dataOwnerPkg = installedPkg;
14850                if (dataOwnerPkg  == null) {
14851                    PackageSetting ps = mSettings.mPackages.get(packageName);
14852                    if (ps != null) {
14853                        dataOwnerPkg = ps.pkg;
14854                    }
14855                }
14856
14857                if (dataOwnerPkg != null) {
14858                    // If installed, the package will get access to data left on the device by its
14859                    // predecessor. As a security measure, this is permited only if this is not a
14860                    // version downgrade or if the predecessor package is marked as debuggable and
14861                    // a downgrade is explicitly requested.
14862                    //
14863                    // On debuggable platform builds, downgrades are permitted even for
14864                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14865                    // not offer security guarantees and thus it's OK to disable some security
14866                    // mechanisms to make debugging/testing easier on those builds. However, even on
14867                    // debuggable builds downgrades of packages are permitted only if requested via
14868                    // installFlags. This is because we aim to keep the behavior of debuggable
14869                    // platform builds as close as possible to the behavior of non-debuggable
14870                    // platform builds.
14871                    final boolean downgradeRequested =
14872                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14873                    final boolean packageDebuggable =
14874                                (dataOwnerPkg.applicationInfo.flags
14875                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14876                    final boolean downgradePermitted =
14877                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14878                    if (!downgradePermitted) {
14879                        try {
14880                            checkDowngrade(dataOwnerPkg, pkgLite);
14881                        } catch (PackageManagerException e) {
14882                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14883                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14884                        }
14885                    }
14886                }
14887
14888                if (installedPkg != null) {
14889                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14890                        // Check for updated system application.
14891                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14892                            if (onSd) {
14893                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14894                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14895                            }
14896                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14897                        } else {
14898                            if (onSd) {
14899                                // Install flag overrides everything.
14900                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14901                            }
14902                            // If current upgrade specifies particular preference
14903                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14904                                // Application explicitly specified internal.
14905                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14906                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14907                                // App explictly prefers external. Let policy decide
14908                            } else {
14909                                // Prefer previous location
14910                                if (isExternal(installedPkg)) {
14911                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14912                                }
14913                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14914                            }
14915                        }
14916                    } else {
14917                        // Invalid install. Return error code
14918                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14919                    }
14920                }
14921            }
14922            // All the special cases have been taken care of.
14923            // Return result based on recommended install location.
14924            if (onSd) {
14925                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14926            }
14927            return pkgLite.recommendedInstallLocation;
14928        }
14929
14930        /*
14931         * Invoke remote method to get package information and install
14932         * location values. Override install location based on default
14933         * policy if needed and then create install arguments based
14934         * on the install location.
14935         */
14936        public void handleStartCopy() throws RemoteException {
14937            int ret = PackageManager.INSTALL_SUCCEEDED;
14938
14939            // If we're already staged, we've firmly committed to an install location
14940            if (origin.staged) {
14941                if (origin.file != null) {
14942                    installFlags |= PackageManager.INSTALL_INTERNAL;
14943                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14944                } else if (origin.cid != null) {
14945                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14946                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14947                } else {
14948                    throw new IllegalStateException("Invalid stage location");
14949                }
14950            }
14951
14952            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14953            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14954            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14955            PackageInfoLite pkgLite = null;
14956
14957            if (onInt && onSd) {
14958                // Check if both bits are set.
14959                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14960                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14961            } else if (onSd && ephemeral) {
14962                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14963                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14964            } else {
14965                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14966                        packageAbiOverride);
14967
14968                if (DEBUG_EPHEMERAL && ephemeral) {
14969                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14970                }
14971
14972                /*
14973                 * If we have too little free space, try to free cache
14974                 * before giving up.
14975                 */
14976                if (!origin.staged && pkgLite.recommendedInstallLocation
14977                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14978                    // TODO: focus freeing disk space on the target device
14979                    final StorageManager storage = StorageManager.from(mContext);
14980                    final long lowThreshold = storage.getStorageLowBytes(
14981                            Environment.getDataDirectory());
14982
14983                    final long sizeBytes = mContainerService.calculateInstalledSize(
14984                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14985
14986                    try {
14987                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14988                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14989                                installFlags, packageAbiOverride);
14990                    } catch (InstallerException e) {
14991                        Slog.w(TAG, "Failed to free cache", e);
14992                    }
14993
14994                    /*
14995                     * The cache free must have deleted the file we
14996                     * downloaded to install.
14997                     *
14998                     * TODO: fix the "freeCache" call to not delete
14999                     *       the file we care about.
15000                     */
15001                    if (pkgLite.recommendedInstallLocation
15002                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15003                        pkgLite.recommendedInstallLocation
15004                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15005                    }
15006                }
15007            }
15008
15009            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15010                int loc = pkgLite.recommendedInstallLocation;
15011                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15012                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15013                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15014                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15015                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15016                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15017                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15018                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15019                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15020                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15021                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15022                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15023                } else {
15024                    // Override with defaults if needed.
15025                    loc = installLocationPolicy(pkgLite);
15026                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15027                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15028                    } else if (!onSd && !onInt) {
15029                        // Override install location with flags
15030                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15031                            // Set the flag to install on external media.
15032                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15033                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15034                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15035                            if (DEBUG_EPHEMERAL) {
15036                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15037                            }
15038                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15039                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15040                                    |PackageManager.INSTALL_INTERNAL);
15041                        } else {
15042                            // Make sure the flag for installing on external
15043                            // media is unset
15044                            installFlags |= PackageManager.INSTALL_INTERNAL;
15045                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15046                        }
15047                    }
15048                }
15049            }
15050
15051            final InstallArgs args = createInstallArgs(this);
15052            mArgs = args;
15053
15054            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15055                // TODO: http://b/22976637
15056                // Apps installed for "all" users use the device owner to verify the app
15057                UserHandle verifierUser = getUser();
15058                if (verifierUser == UserHandle.ALL) {
15059                    verifierUser = UserHandle.SYSTEM;
15060                }
15061
15062                /*
15063                 * Determine if we have any installed package verifiers. If we
15064                 * do, then we'll defer to them to verify the packages.
15065                 */
15066                final int requiredUid = mRequiredVerifierPackage == null ? -1
15067                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15068                                verifierUser.getIdentifier());
15069                if (!origin.existing && requiredUid != -1
15070                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15071                    final Intent verification = new Intent(
15072                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15073                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15074                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15075                            PACKAGE_MIME_TYPE);
15076                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15077
15078                    // Query all live verifiers based on current user state
15079                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15080                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15081
15082                    if (DEBUG_VERIFY) {
15083                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15084                                + verification.toString() + " with " + pkgLite.verifiers.length
15085                                + " optional verifiers");
15086                    }
15087
15088                    final int verificationId = mPendingVerificationToken++;
15089
15090                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15091
15092                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15093                            installerPackageName);
15094
15095                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15096                            installFlags);
15097
15098                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15099                            pkgLite.packageName);
15100
15101                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15102                            pkgLite.versionCode);
15103
15104                    if (verificationInfo != null) {
15105                        if (verificationInfo.originatingUri != null) {
15106                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15107                                    verificationInfo.originatingUri);
15108                        }
15109                        if (verificationInfo.referrer != null) {
15110                            verification.putExtra(Intent.EXTRA_REFERRER,
15111                                    verificationInfo.referrer);
15112                        }
15113                        if (verificationInfo.originatingUid >= 0) {
15114                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15115                                    verificationInfo.originatingUid);
15116                        }
15117                        if (verificationInfo.installerUid >= 0) {
15118                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15119                                    verificationInfo.installerUid);
15120                        }
15121                    }
15122
15123                    final PackageVerificationState verificationState = new PackageVerificationState(
15124                            requiredUid, args);
15125
15126                    mPendingVerification.append(verificationId, verificationState);
15127
15128                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15129                            receivers, verificationState);
15130
15131                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15132                    final long idleDuration = getVerificationTimeout();
15133
15134                    /*
15135                     * If any sufficient verifiers were listed in the package
15136                     * manifest, attempt to ask them.
15137                     */
15138                    if (sufficientVerifiers != null) {
15139                        final int N = sufficientVerifiers.size();
15140                        if (N == 0) {
15141                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15142                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15143                        } else {
15144                            for (int i = 0; i < N; i++) {
15145                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15146                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15147                                        verifierComponent.getPackageName(), idleDuration,
15148                                        verifierUser.getIdentifier(), false, "package verifier");
15149
15150                                final Intent sufficientIntent = new Intent(verification);
15151                                sufficientIntent.setComponent(verifierComponent);
15152                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15153                            }
15154                        }
15155                    }
15156
15157                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15158                            mRequiredVerifierPackage, receivers);
15159                    if (ret == PackageManager.INSTALL_SUCCEEDED
15160                            && mRequiredVerifierPackage != null) {
15161                        Trace.asyncTraceBegin(
15162                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15163                        /*
15164                         * Send the intent to the required verification agent,
15165                         * but only start the verification timeout after the
15166                         * target BroadcastReceivers have run.
15167                         */
15168                        verification.setComponent(requiredVerifierComponent);
15169                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15170                                mRequiredVerifierPackage, idleDuration,
15171                                verifierUser.getIdentifier(), false, "package verifier");
15172                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15173                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15174                                new BroadcastReceiver() {
15175                                    @Override
15176                                    public void onReceive(Context context, Intent intent) {
15177                                        final Message msg = mHandler
15178                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15179                                        msg.arg1 = verificationId;
15180                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15181                                    }
15182                                }, null, 0, null, null);
15183
15184                        /*
15185                         * We don't want the copy to proceed until verification
15186                         * succeeds, so null out this field.
15187                         */
15188                        mArgs = null;
15189                    }
15190                } else {
15191                    /*
15192                     * No package verification is enabled, so immediately start
15193                     * the remote call to initiate copy using temporary file.
15194                     */
15195                    ret = args.copyApk(mContainerService, true);
15196                }
15197            }
15198
15199            mRet = ret;
15200        }
15201
15202        @Override
15203        void handleReturnCode() {
15204            // If mArgs is null, then MCS couldn't be reached. When it
15205            // reconnects, it will try again to install. At that point, this
15206            // will succeed.
15207            if (mArgs != null) {
15208                processPendingInstall(mArgs, mRet);
15209            }
15210        }
15211
15212        @Override
15213        void handleServiceError() {
15214            mArgs = createInstallArgs(this);
15215            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15216        }
15217
15218        public boolean isForwardLocked() {
15219            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15220        }
15221    }
15222
15223    /**
15224     * Used during creation of InstallArgs
15225     *
15226     * @param installFlags package installation flags
15227     * @return true if should be installed on external storage
15228     */
15229    private static boolean installOnExternalAsec(int installFlags) {
15230        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15231            return false;
15232        }
15233        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15234            return true;
15235        }
15236        return false;
15237    }
15238
15239    /**
15240     * Used during creation of InstallArgs
15241     *
15242     * @param installFlags package installation flags
15243     * @return true if should be installed as forward locked
15244     */
15245    private static boolean installForwardLocked(int installFlags) {
15246        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15247    }
15248
15249    private InstallArgs createInstallArgs(InstallParams params) {
15250        if (params.move != null) {
15251            return new MoveInstallArgs(params);
15252        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15253            return new AsecInstallArgs(params);
15254        } else {
15255            return new FileInstallArgs(params);
15256        }
15257    }
15258
15259    /**
15260     * Create args that describe an existing installed package. Typically used
15261     * when cleaning up old installs, or used as a move source.
15262     */
15263    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15264            String resourcePath, String[] instructionSets) {
15265        final boolean isInAsec;
15266        if (installOnExternalAsec(installFlags)) {
15267            /* Apps on SD card are always in ASEC containers. */
15268            isInAsec = true;
15269        } else if (installForwardLocked(installFlags)
15270                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15271            /*
15272             * Forward-locked apps are only in ASEC containers if they're the
15273             * new style
15274             */
15275            isInAsec = true;
15276        } else {
15277            isInAsec = false;
15278        }
15279
15280        if (isInAsec) {
15281            return new AsecInstallArgs(codePath, instructionSets,
15282                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15283        } else {
15284            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15285        }
15286    }
15287
15288    static abstract class InstallArgs {
15289        /** @see InstallParams#origin */
15290        final OriginInfo origin;
15291        /** @see InstallParams#move */
15292        final MoveInfo move;
15293
15294        final IPackageInstallObserver2 observer;
15295        // Always refers to PackageManager flags only
15296        final int installFlags;
15297        final String installerPackageName;
15298        final String volumeUuid;
15299        final UserHandle user;
15300        final String abiOverride;
15301        final String[] installGrantPermissions;
15302        /** If non-null, drop an async trace when the install completes */
15303        final String traceMethod;
15304        final int traceCookie;
15305        final Certificate[][] certificates;
15306        final int installReason;
15307
15308        // The list of instruction sets supported by this app. This is currently
15309        // only used during the rmdex() phase to clean up resources. We can get rid of this
15310        // if we move dex files under the common app path.
15311        /* nullable */ String[] instructionSets;
15312
15313        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15314                int installFlags, String installerPackageName, String volumeUuid,
15315                UserHandle user, String[] instructionSets,
15316                String abiOverride, String[] installGrantPermissions,
15317                String traceMethod, int traceCookie, Certificate[][] certificates,
15318                int installReason) {
15319            this.origin = origin;
15320            this.move = move;
15321            this.installFlags = installFlags;
15322            this.observer = observer;
15323            this.installerPackageName = installerPackageName;
15324            this.volumeUuid = volumeUuid;
15325            this.user = user;
15326            this.instructionSets = instructionSets;
15327            this.abiOverride = abiOverride;
15328            this.installGrantPermissions = installGrantPermissions;
15329            this.traceMethod = traceMethod;
15330            this.traceCookie = traceCookie;
15331            this.certificates = certificates;
15332            this.installReason = installReason;
15333        }
15334
15335        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15336        abstract int doPreInstall(int status);
15337
15338        /**
15339         * Rename package into final resting place. All paths on the given
15340         * scanned package should be updated to reflect the rename.
15341         */
15342        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15343        abstract int doPostInstall(int status, int uid);
15344
15345        /** @see PackageSettingBase#codePathString */
15346        abstract String getCodePath();
15347        /** @see PackageSettingBase#resourcePathString */
15348        abstract String getResourcePath();
15349
15350        // Need installer lock especially for dex file removal.
15351        abstract void cleanUpResourcesLI();
15352        abstract boolean doPostDeleteLI(boolean delete);
15353
15354        /**
15355         * Called before the source arguments are copied. This is used mostly
15356         * for MoveParams when it needs to read the source file to put it in the
15357         * destination.
15358         */
15359        int doPreCopy() {
15360            return PackageManager.INSTALL_SUCCEEDED;
15361        }
15362
15363        /**
15364         * Called after the source arguments are copied. This is used mostly for
15365         * MoveParams when it needs to read the source file to put it in the
15366         * destination.
15367         */
15368        int doPostCopy(int uid) {
15369            return PackageManager.INSTALL_SUCCEEDED;
15370        }
15371
15372        protected boolean isFwdLocked() {
15373            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15374        }
15375
15376        protected boolean isExternalAsec() {
15377            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15378        }
15379
15380        protected boolean isEphemeral() {
15381            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15382        }
15383
15384        UserHandle getUser() {
15385            return user;
15386        }
15387    }
15388
15389    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15390        if (!allCodePaths.isEmpty()) {
15391            if (instructionSets == null) {
15392                throw new IllegalStateException("instructionSet == null");
15393            }
15394            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15395            for (String codePath : allCodePaths) {
15396                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15397                    try {
15398                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15399                    } catch (InstallerException ignored) {
15400                    }
15401                }
15402            }
15403        }
15404    }
15405
15406    /**
15407     * Logic to handle installation of non-ASEC applications, including copying
15408     * and renaming logic.
15409     */
15410    class FileInstallArgs extends InstallArgs {
15411        private File codeFile;
15412        private File resourceFile;
15413
15414        // Example topology:
15415        // /data/app/com.example/base.apk
15416        // /data/app/com.example/split_foo.apk
15417        // /data/app/com.example/lib/arm/libfoo.so
15418        // /data/app/com.example/lib/arm64/libfoo.so
15419        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15420
15421        /** New install */
15422        FileInstallArgs(InstallParams params) {
15423            super(params.origin, params.move, params.observer, params.installFlags,
15424                    params.installerPackageName, params.volumeUuid,
15425                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15426                    params.grantedRuntimePermissions,
15427                    params.traceMethod, params.traceCookie, params.certificates,
15428                    params.installReason);
15429            if (isFwdLocked()) {
15430                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15431            }
15432        }
15433
15434        /** Existing install */
15435        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15436            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15437                    null, null, null, 0, null /*certificates*/,
15438                    PackageManager.INSTALL_REASON_UNKNOWN);
15439            this.codeFile = (codePath != null) ? new File(codePath) : null;
15440            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15441        }
15442
15443        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15444            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15445            try {
15446                return doCopyApk(imcs, temp);
15447            } finally {
15448                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15449            }
15450        }
15451
15452        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15453            if (origin.staged) {
15454                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15455                codeFile = origin.file;
15456                resourceFile = origin.file;
15457                return PackageManager.INSTALL_SUCCEEDED;
15458            }
15459
15460            try {
15461                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15462                final File tempDir =
15463                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15464                codeFile = tempDir;
15465                resourceFile = tempDir;
15466            } catch (IOException e) {
15467                Slog.w(TAG, "Failed to create copy file: " + e);
15468                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15469            }
15470
15471            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15472                @Override
15473                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15474                    if (!FileUtils.isValidExtFilename(name)) {
15475                        throw new IllegalArgumentException("Invalid filename: " + name);
15476                    }
15477                    try {
15478                        final File file = new File(codeFile, name);
15479                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15480                                O_RDWR | O_CREAT, 0644);
15481                        Os.chmod(file.getAbsolutePath(), 0644);
15482                        return new ParcelFileDescriptor(fd);
15483                    } catch (ErrnoException e) {
15484                        throw new RemoteException("Failed to open: " + e.getMessage());
15485                    }
15486                }
15487            };
15488
15489            int ret = PackageManager.INSTALL_SUCCEEDED;
15490            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15491            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15492                Slog.e(TAG, "Failed to copy package");
15493                return ret;
15494            }
15495
15496            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15497            NativeLibraryHelper.Handle handle = null;
15498            try {
15499                handle = NativeLibraryHelper.Handle.create(codeFile);
15500                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15501                        abiOverride);
15502            } catch (IOException e) {
15503                Slog.e(TAG, "Copying native libraries failed", e);
15504                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15505            } finally {
15506                IoUtils.closeQuietly(handle);
15507            }
15508
15509            return ret;
15510        }
15511
15512        int doPreInstall(int status) {
15513            if (status != PackageManager.INSTALL_SUCCEEDED) {
15514                cleanUp();
15515            }
15516            return status;
15517        }
15518
15519        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15520            if (status != PackageManager.INSTALL_SUCCEEDED) {
15521                cleanUp();
15522                return false;
15523            }
15524
15525            final File targetDir = codeFile.getParentFile();
15526            final File beforeCodeFile = codeFile;
15527            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15528
15529            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15530            try {
15531                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15532            } catch (ErrnoException e) {
15533                Slog.w(TAG, "Failed to rename", e);
15534                return false;
15535            }
15536
15537            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15538                Slog.w(TAG, "Failed to restorecon");
15539                return false;
15540            }
15541
15542            // Reflect the rename internally
15543            codeFile = afterCodeFile;
15544            resourceFile = afterCodeFile;
15545
15546            // Reflect the rename in scanned details
15547            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15548            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15549                    afterCodeFile, pkg.baseCodePath));
15550            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15551                    afterCodeFile, pkg.splitCodePaths));
15552
15553            // Reflect the rename in app info
15554            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15555            pkg.setApplicationInfoCodePath(pkg.codePath);
15556            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15557            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15558            pkg.setApplicationInfoResourcePath(pkg.codePath);
15559            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15560            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15561
15562            return true;
15563        }
15564
15565        int doPostInstall(int status, int uid) {
15566            if (status != PackageManager.INSTALL_SUCCEEDED) {
15567                cleanUp();
15568            }
15569            return status;
15570        }
15571
15572        @Override
15573        String getCodePath() {
15574            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15575        }
15576
15577        @Override
15578        String getResourcePath() {
15579            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15580        }
15581
15582        private boolean cleanUp() {
15583            if (codeFile == null || !codeFile.exists()) {
15584                return false;
15585            }
15586
15587            removeCodePathLI(codeFile);
15588
15589            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15590                resourceFile.delete();
15591            }
15592
15593            return true;
15594        }
15595
15596        void cleanUpResourcesLI() {
15597            // Try enumerating all code paths before deleting
15598            List<String> allCodePaths = Collections.EMPTY_LIST;
15599            if (codeFile != null && codeFile.exists()) {
15600                try {
15601                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15602                    allCodePaths = pkg.getAllCodePaths();
15603                } catch (PackageParserException e) {
15604                    // Ignored; we tried our best
15605                }
15606            }
15607
15608            cleanUp();
15609            removeDexFiles(allCodePaths, instructionSets);
15610        }
15611
15612        boolean doPostDeleteLI(boolean delete) {
15613            // XXX err, shouldn't we respect the delete flag?
15614            cleanUpResourcesLI();
15615            return true;
15616        }
15617    }
15618
15619    private boolean isAsecExternal(String cid) {
15620        final String asecPath = PackageHelper.getSdFilesystem(cid);
15621        return !asecPath.startsWith(mAsecInternalPath);
15622    }
15623
15624    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15625            PackageManagerException {
15626        if (copyRet < 0) {
15627            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15628                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15629                throw new PackageManagerException(copyRet, message);
15630            }
15631        }
15632    }
15633
15634    /**
15635     * Extract the StorageManagerService "container ID" from the full code path of an
15636     * .apk.
15637     */
15638    static String cidFromCodePath(String fullCodePath) {
15639        int eidx = fullCodePath.lastIndexOf("/");
15640        String subStr1 = fullCodePath.substring(0, eidx);
15641        int sidx = subStr1.lastIndexOf("/");
15642        return subStr1.substring(sidx+1, eidx);
15643    }
15644
15645    /**
15646     * Logic to handle installation of ASEC applications, including copying and
15647     * renaming logic.
15648     */
15649    class AsecInstallArgs extends InstallArgs {
15650        static final String RES_FILE_NAME = "pkg.apk";
15651        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15652
15653        String cid;
15654        String packagePath;
15655        String resourcePath;
15656
15657        /** New install */
15658        AsecInstallArgs(InstallParams params) {
15659            super(params.origin, params.move, params.observer, params.installFlags,
15660                    params.installerPackageName, params.volumeUuid,
15661                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15662                    params.grantedRuntimePermissions,
15663                    params.traceMethod, params.traceCookie, params.certificates,
15664                    params.installReason);
15665        }
15666
15667        /** Existing install */
15668        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15669                        boolean isExternal, boolean isForwardLocked) {
15670            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15671                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15672                    instructionSets, null, null, null, 0, null /*certificates*/,
15673                    PackageManager.INSTALL_REASON_UNKNOWN);
15674            // Hackily pretend we're still looking at a full code path
15675            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15676                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15677            }
15678
15679            // Extract cid from fullCodePath
15680            int eidx = fullCodePath.lastIndexOf("/");
15681            String subStr1 = fullCodePath.substring(0, eidx);
15682            int sidx = subStr1.lastIndexOf("/");
15683            cid = subStr1.substring(sidx+1, eidx);
15684            setMountPath(subStr1);
15685        }
15686
15687        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15688            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15689                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15690                    instructionSets, null, null, null, 0, null /*certificates*/,
15691                    PackageManager.INSTALL_REASON_UNKNOWN);
15692            this.cid = cid;
15693            setMountPath(PackageHelper.getSdDir(cid));
15694        }
15695
15696        void createCopyFile() {
15697            cid = mInstallerService.allocateExternalStageCidLegacy();
15698        }
15699
15700        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15701            if (origin.staged && origin.cid != null) {
15702                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15703                cid = origin.cid;
15704                setMountPath(PackageHelper.getSdDir(cid));
15705                return PackageManager.INSTALL_SUCCEEDED;
15706            }
15707
15708            if (temp) {
15709                createCopyFile();
15710            } else {
15711                /*
15712                 * Pre-emptively destroy the container since it's destroyed if
15713                 * copying fails due to it existing anyway.
15714                 */
15715                PackageHelper.destroySdDir(cid);
15716            }
15717
15718            final String newMountPath = imcs.copyPackageToContainer(
15719                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15720                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15721
15722            if (newMountPath != null) {
15723                setMountPath(newMountPath);
15724                return PackageManager.INSTALL_SUCCEEDED;
15725            } else {
15726                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15727            }
15728        }
15729
15730        @Override
15731        String getCodePath() {
15732            return packagePath;
15733        }
15734
15735        @Override
15736        String getResourcePath() {
15737            return resourcePath;
15738        }
15739
15740        int doPreInstall(int status) {
15741            if (status != PackageManager.INSTALL_SUCCEEDED) {
15742                // Destroy container
15743                PackageHelper.destroySdDir(cid);
15744            } else {
15745                boolean mounted = PackageHelper.isContainerMounted(cid);
15746                if (!mounted) {
15747                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15748                            Process.SYSTEM_UID);
15749                    if (newMountPath != null) {
15750                        setMountPath(newMountPath);
15751                    } else {
15752                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15753                    }
15754                }
15755            }
15756            return status;
15757        }
15758
15759        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15760            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15761            String newMountPath = null;
15762            if (PackageHelper.isContainerMounted(cid)) {
15763                // Unmount the container
15764                if (!PackageHelper.unMountSdDir(cid)) {
15765                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15766                    return false;
15767                }
15768            }
15769            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15770                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15771                        " which might be stale. Will try to clean up.");
15772                // Clean up the stale container and proceed to recreate.
15773                if (!PackageHelper.destroySdDir(newCacheId)) {
15774                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15775                    return false;
15776                }
15777                // Successfully cleaned up stale container. Try to rename again.
15778                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15779                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15780                            + " inspite of cleaning it up.");
15781                    return false;
15782                }
15783            }
15784            if (!PackageHelper.isContainerMounted(newCacheId)) {
15785                Slog.w(TAG, "Mounting container " + newCacheId);
15786                newMountPath = PackageHelper.mountSdDir(newCacheId,
15787                        getEncryptKey(), Process.SYSTEM_UID);
15788            } else {
15789                newMountPath = PackageHelper.getSdDir(newCacheId);
15790            }
15791            if (newMountPath == null) {
15792                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15793                return false;
15794            }
15795            Log.i(TAG, "Succesfully renamed " + cid +
15796                    " to " + newCacheId +
15797                    " at new path: " + newMountPath);
15798            cid = newCacheId;
15799
15800            final File beforeCodeFile = new File(packagePath);
15801            setMountPath(newMountPath);
15802            final File afterCodeFile = new File(packagePath);
15803
15804            // Reflect the rename in scanned details
15805            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15806            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15807                    afterCodeFile, pkg.baseCodePath));
15808            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15809                    afterCodeFile, pkg.splitCodePaths));
15810
15811            // Reflect the rename in app info
15812            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15813            pkg.setApplicationInfoCodePath(pkg.codePath);
15814            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15815            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15816            pkg.setApplicationInfoResourcePath(pkg.codePath);
15817            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15818            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15819
15820            return true;
15821        }
15822
15823        private void setMountPath(String mountPath) {
15824            final File mountFile = new File(mountPath);
15825
15826            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15827            if (monolithicFile.exists()) {
15828                packagePath = monolithicFile.getAbsolutePath();
15829                if (isFwdLocked()) {
15830                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15831                } else {
15832                    resourcePath = packagePath;
15833                }
15834            } else {
15835                packagePath = mountFile.getAbsolutePath();
15836                resourcePath = packagePath;
15837            }
15838        }
15839
15840        int doPostInstall(int status, int uid) {
15841            if (status != PackageManager.INSTALL_SUCCEEDED) {
15842                cleanUp();
15843            } else {
15844                final int groupOwner;
15845                final String protectedFile;
15846                if (isFwdLocked()) {
15847                    groupOwner = UserHandle.getSharedAppGid(uid);
15848                    protectedFile = RES_FILE_NAME;
15849                } else {
15850                    groupOwner = -1;
15851                    protectedFile = null;
15852                }
15853
15854                if (uid < Process.FIRST_APPLICATION_UID
15855                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15856                    Slog.e(TAG, "Failed to finalize " + cid);
15857                    PackageHelper.destroySdDir(cid);
15858                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15859                }
15860
15861                boolean mounted = PackageHelper.isContainerMounted(cid);
15862                if (!mounted) {
15863                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15864                }
15865            }
15866            return status;
15867        }
15868
15869        private void cleanUp() {
15870            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15871
15872            // Destroy secure container
15873            PackageHelper.destroySdDir(cid);
15874        }
15875
15876        private List<String> getAllCodePaths() {
15877            final File codeFile = new File(getCodePath());
15878            if (codeFile != null && codeFile.exists()) {
15879                try {
15880                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15881                    return pkg.getAllCodePaths();
15882                } catch (PackageParserException e) {
15883                    // Ignored; we tried our best
15884                }
15885            }
15886            return Collections.EMPTY_LIST;
15887        }
15888
15889        void cleanUpResourcesLI() {
15890            // Enumerate all code paths before deleting
15891            cleanUpResourcesLI(getAllCodePaths());
15892        }
15893
15894        private void cleanUpResourcesLI(List<String> allCodePaths) {
15895            cleanUp();
15896            removeDexFiles(allCodePaths, instructionSets);
15897        }
15898
15899        String getPackageName() {
15900            return getAsecPackageName(cid);
15901        }
15902
15903        boolean doPostDeleteLI(boolean delete) {
15904            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15905            final List<String> allCodePaths = getAllCodePaths();
15906            boolean mounted = PackageHelper.isContainerMounted(cid);
15907            if (mounted) {
15908                // Unmount first
15909                if (PackageHelper.unMountSdDir(cid)) {
15910                    mounted = false;
15911                }
15912            }
15913            if (!mounted && delete) {
15914                cleanUpResourcesLI(allCodePaths);
15915            }
15916            return !mounted;
15917        }
15918
15919        @Override
15920        int doPreCopy() {
15921            if (isFwdLocked()) {
15922                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15923                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15924                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15925                }
15926            }
15927
15928            return PackageManager.INSTALL_SUCCEEDED;
15929        }
15930
15931        @Override
15932        int doPostCopy(int uid) {
15933            if (isFwdLocked()) {
15934                if (uid < Process.FIRST_APPLICATION_UID
15935                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15936                                RES_FILE_NAME)) {
15937                    Slog.e(TAG, "Failed to finalize " + cid);
15938                    PackageHelper.destroySdDir(cid);
15939                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15940                }
15941            }
15942
15943            return PackageManager.INSTALL_SUCCEEDED;
15944        }
15945    }
15946
15947    /**
15948     * Logic to handle movement of existing installed applications.
15949     */
15950    class MoveInstallArgs extends InstallArgs {
15951        private File codeFile;
15952        private File resourceFile;
15953
15954        /** New install */
15955        MoveInstallArgs(InstallParams params) {
15956            super(params.origin, params.move, params.observer, params.installFlags,
15957                    params.installerPackageName, params.volumeUuid,
15958                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15959                    params.grantedRuntimePermissions,
15960                    params.traceMethod, params.traceCookie, params.certificates,
15961                    params.installReason);
15962        }
15963
15964        int copyApk(IMediaContainerService imcs, boolean temp) {
15965            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15966                    + move.fromUuid + " to " + move.toUuid);
15967            synchronized (mInstaller) {
15968                try {
15969                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15970                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15971                } catch (InstallerException e) {
15972                    Slog.w(TAG, "Failed to move app", e);
15973                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15974                }
15975            }
15976
15977            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15978            resourceFile = codeFile;
15979            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15980
15981            return PackageManager.INSTALL_SUCCEEDED;
15982        }
15983
15984        int doPreInstall(int status) {
15985            if (status != PackageManager.INSTALL_SUCCEEDED) {
15986                cleanUp(move.toUuid);
15987            }
15988            return status;
15989        }
15990
15991        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15992            if (status != PackageManager.INSTALL_SUCCEEDED) {
15993                cleanUp(move.toUuid);
15994                return false;
15995            }
15996
15997            // Reflect the move in app info
15998            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15999            pkg.setApplicationInfoCodePath(pkg.codePath);
16000            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16001            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16002            pkg.setApplicationInfoResourcePath(pkg.codePath);
16003            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16004            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16005
16006            return true;
16007        }
16008
16009        int doPostInstall(int status, int uid) {
16010            if (status == PackageManager.INSTALL_SUCCEEDED) {
16011                cleanUp(move.fromUuid);
16012            } else {
16013                cleanUp(move.toUuid);
16014            }
16015            return status;
16016        }
16017
16018        @Override
16019        String getCodePath() {
16020            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16021        }
16022
16023        @Override
16024        String getResourcePath() {
16025            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16026        }
16027
16028        private boolean cleanUp(String volumeUuid) {
16029            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16030                    move.dataAppName);
16031            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16032            final int[] userIds = sUserManager.getUserIds();
16033            synchronized (mInstallLock) {
16034                // Clean up both app data and code
16035                // All package moves are frozen until finished
16036                for (int userId : userIds) {
16037                    try {
16038                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16039                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16040                    } catch (InstallerException e) {
16041                        Slog.w(TAG, String.valueOf(e));
16042                    }
16043                }
16044                removeCodePathLI(codeFile);
16045            }
16046            return true;
16047        }
16048
16049        void cleanUpResourcesLI() {
16050            throw new UnsupportedOperationException();
16051        }
16052
16053        boolean doPostDeleteLI(boolean delete) {
16054            throw new UnsupportedOperationException();
16055        }
16056    }
16057
16058    static String getAsecPackageName(String packageCid) {
16059        int idx = packageCid.lastIndexOf("-");
16060        if (idx == -1) {
16061            return packageCid;
16062        }
16063        return packageCid.substring(0, idx);
16064    }
16065
16066    // Utility method used to create code paths based on package name and available index.
16067    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16068        String idxStr = "";
16069        int idx = 1;
16070        // Fall back to default value of idx=1 if prefix is not
16071        // part of oldCodePath
16072        if (oldCodePath != null) {
16073            String subStr = oldCodePath;
16074            // Drop the suffix right away
16075            if (suffix != null && subStr.endsWith(suffix)) {
16076                subStr = subStr.substring(0, subStr.length() - suffix.length());
16077            }
16078            // If oldCodePath already contains prefix find out the
16079            // ending index to either increment or decrement.
16080            int sidx = subStr.lastIndexOf(prefix);
16081            if (sidx != -1) {
16082                subStr = subStr.substring(sidx + prefix.length());
16083                if (subStr != null) {
16084                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16085                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16086                    }
16087                    try {
16088                        idx = Integer.parseInt(subStr);
16089                        if (idx <= 1) {
16090                            idx++;
16091                        } else {
16092                            idx--;
16093                        }
16094                    } catch(NumberFormatException e) {
16095                    }
16096                }
16097            }
16098        }
16099        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16100        return prefix + idxStr;
16101    }
16102
16103    private File getNextCodePath(File targetDir, String packageName) {
16104        File result;
16105        SecureRandom random = new SecureRandom();
16106        byte[] bytes = new byte[16];
16107        do {
16108            random.nextBytes(bytes);
16109            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16110            result = new File(targetDir, packageName + "-" + suffix);
16111        } while (result.exists());
16112        return result;
16113    }
16114
16115    // Utility method that returns the relative package path with respect
16116    // to the installation directory. Like say for /data/data/com.test-1.apk
16117    // string com.test-1 is returned.
16118    static String deriveCodePathName(String codePath) {
16119        if (codePath == null) {
16120            return null;
16121        }
16122        final File codeFile = new File(codePath);
16123        final String name = codeFile.getName();
16124        if (codeFile.isDirectory()) {
16125            return name;
16126        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16127            final int lastDot = name.lastIndexOf('.');
16128            return name.substring(0, lastDot);
16129        } else {
16130            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16131            return null;
16132        }
16133    }
16134
16135    static class PackageInstalledInfo {
16136        String name;
16137        int uid;
16138        // The set of users that originally had this package installed.
16139        int[] origUsers;
16140        // The set of users that now have this package installed.
16141        int[] newUsers;
16142        PackageParser.Package pkg;
16143        int returnCode;
16144        String returnMsg;
16145        PackageRemovedInfo removedInfo;
16146        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16147
16148        public void setError(int code, String msg) {
16149            setReturnCode(code);
16150            setReturnMessage(msg);
16151            Slog.w(TAG, msg);
16152        }
16153
16154        public void setError(String msg, PackageParserException e) {
16155            setReturnCode(e.error);
16156            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16157            Slog.w(TAG, msg, e);
16158        }
16159
16160        public void setError(String msg, PackageManagerException e) {
16161            returnCode = e.error;
16162            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16163            Slog.w(TAG, msg, e);
16164        }
16165
16166        public void setReturnCode(int returnCode) {
16167            this.returnCode = returnCode;
16168            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16169            for (int i = 0; i < childCount; i++) {
16170                addedChildPackages.valueAt(i).returnCode = returnCode;
16171            }
16172        }
16173
16174        private void setReturnMessage(String returnMsg) {
16175            this.returnMsg = returnMsg;
16176            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16177            for (int i = 0; i < childCount; i++) {
16178                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16179            }
16180        }
16181
16182        // In some error cases we want to convey more info back to the observer
16183        String origPackage;
16184        String origPermission;
16185    }
16186
16187    /*
16188     * Install a non-existing package.
16189     */
16190    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16191            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16192            PackageInstalledInfo res, int installReason) {
16193        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16194
16195        // Remember this for later, in case we need to rollback this install
16196        String pkgName = pkg.packageName;
16197
16198        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16199
16200        synchronized(mPackages) {
16201            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16202            if (renamedPackage != null) {
16203                // A package with the same name is already installed, though
16204                // it has been renamed to an older name.  The package we
16205                // are trying to install should be installed as an update to
16206                // the existing one, but that has not been requested, so bail.
16207                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16208                        + " without first uninstalling package running as "
16209                        + renamedPackage);
16210                return;
16211            }
16212            if (mPackages.containsKey(pkgName)) {
16213                // Don't allow installation over an existing package with the same name.
16214                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16215                        + " without first uninstalling.");
16216                return;
16217            }
16218        }
16219
16220        try {
16221            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16222                    System.currentTimeMillis(), user);
16223
16224            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16225
16226            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16227                prepareAppDataAfterInstallLIF(newPackage);
16228
16229            } else {
16230                // Remove package from internal structures, but keep around any
16231                // data that might have already existed
16232                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16233                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16234            }
16235        } catch (PackageManagerException e) {
16236            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16237        }
16238
16239        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16240    }
16241
16242    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16243        // Can't rotate keys during boot or if sharedUser.
16244        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16245                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16246            return false;
16247        }
16248        // app is using upgradeKeySets; make sure all are valid
16249        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16250        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16251        for (int i = 0; i < upgradeKeySets.length; i++) {
16252            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16253                Slog.wtf(TAG, "Package "
16254                         + (oldPs.name != null ? oldPs.name : "<null>")
16255                         + " contains upgrade-key-set reference to unknown key-set: "
16256                         + upgradeKeySets[i]
16257                         + " reverting to signatures check.");
16258                return false;
16259            }
16260        }
16261        return true;
16262    }
16263
16264    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16265        // Upgrade keysets are being used.  Determine if new package has a superset of the
16266        // required keys.
16267        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16268        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16269        for (int i = 0; i < upgradeKeySets.length; i++) {
16270            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16271            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16272                return true;
16273            }
16274        }
16275        return false;
16276    }
16277
16278    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16279        try (DigestInputStream digestStream =
16280                new DigestInputStream(new FileInputStream(file), digest)) {
16281            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16282        }
16283    }
16284
16285    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16286            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16287            int installReason) {
16288        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16289
16290        final PackageParser.Package oldPackage;
16291        final PackageSetting ps;
16292        final String pkgName = pkg.packageName;
16293        final int[] allUsers;
16294        final int[] installedUsers;
16295
16296        synchronized(mPackages) {
16297            oldPackage = mPackages.get(pkgName);
16298            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16299
16300            // don't allow upgrade to target a release SDK from a pre-release SDK
16301            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16302                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16303            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16304                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16305            if (oldTargetsPreRelease
16306                    && !newTargetsPreRelease
16307                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16308                Slog.w(TAG, "Can't install package targeting released sdk");
16309                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16310                return;
16311            }
16312
16313            ps = mSettings.mPackages.get(pkgName);
16314
16315            // verify signatures are valid
16316            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16317                if (!checkUpgradeKeySetLP(ps, pkg)) {
16318                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16319                            "New package not signed by keys specified by upgrade-keysets: "
16320                                    + pkgName);
16321                    return;
16322                }
16323            } else {
16324                // default to original signature matching
16325                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16326                        != PackageManager.SIGNATURE_MATCH) {
16327                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16328                            "New package has a different signature: " + pkgName);
16329                    return;
16330                }
16331            }
16332
16333            // don't allow a system upgrade unless the upgrade hash matches
16334            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16335                byte[] digestBytes = null;
16336                try {
16337                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16338                    updateDigest(digest, new File(pkg.baseCodePath));
16339                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16340                        for (String path : pkg.splitCodePaths) {
16341                            updateDigest(digest, new File(path));
16342                        }
16343                    }
16344                    digestBytes = digest.digest();
16345                } catch (NoSuchAlgorithmException | IOException e) {
16346                    res.setError(INSTALL_FAILED_INVALID_APK,
16347                            "Could not compute hash: " + pkgName);
16348                    return;
16349                }
16350                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16351                    res.setError(INSTALL_FAILED_INVALID_APK,
16352                            "New package fails restrict-update check: " + pkgName);
16353                    return;
16354                }
16355                // retain upgrade restriction
16356                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16357            }
16358
16359            // Check for shared user id changes
16360            String invalidPackageName =
16361                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16362            if (invalidPackageName != null) {
16363                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16364                        "Package " + invalidPackageName + " tried to change user "
16365                                + oldPackage.mSharedUserId);
16366                return;
16367            }
16368
16369            // In case of rollback, remember per-user/profile install state
16370            allUsers = sUserManager.getUserIds();
16371            installedUsers = ps.queryInstalledUsers(allUsers, true);
16372
16373            // don't allow an upgrade from full to ephemeral
16374            if (isInstantApp) {
16375                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16376                    for (int currentUser : allUsers) {
16377                        if (!ps.getInstantApp(currentUser)) {
16378                            // can't downgrade from full to instant
16379                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16380                                    + " for user: " + currentUser);
16381                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16382                            return;
16383                        }
16384                    }
16385                } else if (!ps.getInstantApp(user.getIdentifier())) {
16386                    // can't downgrade from full to instant
16387                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16388                            + " for user: " + user.getIdentifier());
16389                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16390                    return;
16391                }
16392            }
16393        }
16394
16395        // Update what is removed
16396        res.removedInfo = new PackageRemovedInfo(this);
16397        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16398        res.removedInfo.removedPackage = oldPackage.packageName;
16399        res.removedInfo.installerPackageName = ps.installerPackageName;
16400        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16401        res.removedInfo.isUpdate = true;
16402        res.removedInfo.origUsers = installedUsers;
16403        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16404        for (int i = 0; i < installedUsers.length; i++) {
16405            final int userId = installedUsers[i];
16406            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16407        }
16408
16409        final int childCount = (oldPackage.childPackages != null)
16410                ? oldPackage.childPackages.size() : 0;
16411        for (int i = 0; i < childCount; i++) {
16412            boolean childPackageUpdated = false;
16413            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16414            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16415            if (res.addedChildPackages != null) {
16416                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16417                if (childRes != null) {
16418                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16419                    childRes.removedInfo.removedPackage = childPkg.packageName;
16420                    if (childPs != null) {
16421                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16422                    }
16423                    childRes.removedInfo.isUpdate = true;
16424                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16425                    childPackageUpdated = true;
16426                }
16427            }
16428            if (!childPackageUpdated) {
16429                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16430                childRemovedRes.removedPackage = childPkg.packageName;
16431                if (childPs != null) {
16432                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16433                }
16434                childRemovedRes.isUpdate = false;
16435                childRemovedRes.dataRemoved = true;
16436                synchronized (mPackages) {
16437                    if (childPs != null) {
16438                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16439                    }
16440                }
16441                if (res.removedInfo.removedChildPackages == null) {
16442                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16443                }
16444                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16445            }
16446        }
16447
16448        boolean sysPkg = (isSystemApp(oldPackage));
16449        if (sysPkg) {
16450            // Set the system/privileged flags as needed
16451            final boolean privileged =
16452                    (oldPackage.applicationInfo.privateFlags
16453                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16454            final int systemPolicyFlags = policyFlags
16455                    | PackageParser.PARSE_IS_SYSTEM
16456                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16457
16458            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16459                    user, allUsers, installerPackageName, res, installReason);
16460        } else {
16461            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16462                    user, allUsers, installerPackageName, res, installReason);
16463        }
16464    }
16465
16466    public List<String> getPreviousCodePaths(String packageName) {
16467        final PackageSetting ps = mSettings.mPackages.get(packageName);
16468        final List<String> result = new ArrayList<String>();
16469        if (ps != null && ps.oldCodePaths != null) {
16470            result.addAll(ps.oldCodePaths);
16471        }
16472        return result;
16473    }
16474
16475    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16476            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16477            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16478            int installReason) {
16479        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16480                + deletedPackage);
16481
16482        String pkgName = deletedPackage.packageName;
16483        boolean deletedPkg = true;
16484        boolean addedPkg = false;
16485        boolean updatedSettings = false;
16486        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16487        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16488                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16489
16490        final long origUpdateTime = (pkg.mExtras != null)
16491                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16492
16493        // First delete the existing package while retaining the data directory
16494        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16495                res.removedInfo, true, pkg)) {
16496            // If the existing package wasn't successfully deleted
16497            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16498            deletedPkg = false;
16499        } else {
16500            // Successfully deleted the old package; proceed with replace.
16501
16502            // If deleted package lived in a container, give users a chance to
16503            // relinquish resources before killing.
16504            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16505                if (DEBUG_INSTALL) {
16506                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16507                }
16508                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16509                final ArrayList<String> pkgList = new ArrayList<String>(1);
16510                pkgList.add(deletedPackage.applicationInfo.packageName);
16511                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16512            }
16513
16514            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16515                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16516            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16517
16518            try {
16519                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16520                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16521                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16522                        installReason);
16523
16524                // Update the in-memory copy of the previous code paths.
16525                PackageSetting ps = mSettings.mPackages.get(pkgName);
16526                if (!killApp) {
16527                    if (ps.oldCodePaths == null) {
16528                        ps.oldCodePaths = new ArraySet<>();
16529                    }
16530                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16531                    if (deletedPackage.splitCodePaths != null) {
16532                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16533                    }
16534                } else {
16535                    ps.oldCodePaths = null;
16536                }
16537                if (ps.childPackageNames != null) {
16538                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16539                        final String childPkgName = ps.childPackageNames.get(i);
16540                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16541                        childPs.oldCodePaths = ps.oldCodePaths;
16542                    }
16543                }
16544                // set instant app status, but, only if it's explicitly specified
16545                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16546                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16547                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16548                prepareAppDataAfterInstallLIF(newPackage);
16549                addedPkg = true;
16550                mDexManager.notifyPackageUpdated(newPackage.packageName,
16551                        newPackage.baseCodePath, newPackage.splitCodePaths);
16552            } catch (PackageManagerException e) {
16553                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16554            }
16555        }
16556
16557        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16558            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16559
16560            // Revert all internal state mutations and added folders for the failed install
16561            if (addedPkg) {
16562                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16563                        res.removedInfo, true, null);
16564            }
16565
16566            // Restore the old package
16567            if (deletedPkg) {
16568                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16569                File restoreFile = new File(deletedPackage.codePath);
16570                // Parse old package
16571                boolean oldExternal = isExternal(deletedPackage);
16572                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16573                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16574                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16575                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16576                try {
16577                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16578                            null);
16579                } catch (PackageManagerException e) {
16580                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16581                            + e.getMessage());
16582                    return;
16583                }
16584
16585                synchronized (mPackages) {
16586                    // Ensure the installer package name up to date
16587                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16588
16589                    // Update permissions for restored package
16590                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16591
16592                    mSettings.writeLPr();
16593                }
16594
16595                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16596            }
16597        } else {
16598            synchronized (mPackages) {
16599                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16600                if (ps != null) {
16601                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16602                    if (res.removedInfo.removedChildPackages != null) {
16603                        final int childCount = res.removedInfo.removedChildPackages.size();
16604                        // Iterate in reverse as we may modify the collection
16605                        for (int i = childCount - 1; i >= 0; i--) {
16606                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16607                            if (res.addedChildPackages.containsKey(childPackageName)) {
16608                                res.removedInfo.removedChildPackages.removeAt(i);
16609                            } else {
16610                                PackageRemovedInfo childInfo = res.removedInfo
16611                                        .removedChildPackages.valueAt(i);
16612                                childInfo.removedForAllUsers = mPackages.get(
16613                                        childInfo.removedPackage) == null;
16614                            }
16615                        }
16616                    }
16617                }
16618            }
16619        }
16620    }
16621
16622    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16623            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16624            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16625            int installReason) {
16626        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16627                + ", old=" + deletedPackage);
16628
16629        final boolean disabledSystem;
16630
16631        // Remove existing system package
16632        removePackageLI(deletedPackage, true);
16633
16634        synchronized (mPackages) {
16635            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16636        }
16637        if (!disabledSystem) {
16638            // We didn't need to disable the .apk as a current system package,
16639            // which means we are replacing another update that is already
16640            // installed.  We need to make sure to delete the older one's .apk.
16641            res.removedInfo.args = createInstallArgsForExisting(0,
16642                    deletedPackage.applicationInfo.getCodePath(),
16643                    deletedPackage.applicationInfo.getResourcePath(),
16644                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16645        } else {
16646            res.removedInfo.args = null;
16647        }
16648
16649        // Successfully disabled the old package. Now proceed with re-installation
16650        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16651                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16652        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16653
16654        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16655        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16656                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16657
16658        PackageParser.Package newPackage = null;
16659        try {
16660            // Add the package to the internal data structures
16661            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16662
16663            // Set the update and install times
16664            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16665            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16666                    System.currentTimeMillis());
16667
16668            // Update the package dynamic state if succeeded
16669            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16670                // Now that the install succeeded make sure we remove data
16671                // directories for any child package the update removed.
16672                final int deletedChildCount = (deletedPackage.childPackages != null)
16673                        ? deletedPackage.childPackages.size() : 0;
16674                final int newChildCount = (newPackage.childPackages != null)
16675                        ? newPackage.childPackages.size() : 0;
16676                for (int i = 0; i < deletedChildCount; i++) {
16677                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16678                    boolean childPackageDeleted = true;
16679                    for (int j = 0; j < newChildCount; j++) {
16680                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16681                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16682                            childPackageDeleted = false;
16683                            break;
16684                        }
16685                    }
16686                    if (childPackageDeleted) {
16687                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16688                                deletedChildPkg.packageName);
16689                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16690                            PackageRemovedInfo removedChildRes = res.removedInfo
16691                                    .removedChildPackages.get(deletedChildPkg.packageName);
16692                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16693                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16694                        }
16695                    }
16696                }
16697
16698                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16699                        installReason);
16700                prepareAppDataAfterInstallLIF(newPackage);
16701
16702                mDexManager.notifyPackageUpdated(newPackage.packageName,
16703                            newPackage.baseCodePath, newPackage.splitCodePaths);
16704            }
16705        } catch (PackageManagerException e) {
16706            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16707            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16708        }
16709
16710        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16711            // Re installation failed. Restore old information
16712            // Remove new pkg information
16713            if (newPackage != null) {
16714                removeInstalledPackageLI(newPackage, true);
16715            }
16716            // Add back the old system package
16717            try {
16718                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16719            } catch (PackageManagerException e) {
16720                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16721            }
16722
16723            synchronized (mPackages) {
16724                if (disabledSystem) {
16725                    enableSystemPackageLPw(deletedPackage);
16726                }
16727
16728                // Ensure the installer package name up to date
16729                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16730
16731                // Update permissions for restored package
16732                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16733
16734                mSettings.writeLPr();
16735            }
16736
16737            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16738                    + " after failed upgrade");
16739        }
16740    }
16741
16742    /**
16743     * Checks whether the parent or any of the child packages have a change shared
16744     * user. For a package to be a valid update the shred users of the parent and
16745     * the children should match. We may later support changing child shared users.
16746     * @param oldPkg The updated package.
16747     * @param newPkg The update package.
16748     * @return The shared user that change between the versions.
16749     */
16750    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16751            PackageParser.Package newPkg) {
16752        // Check parent shared user
16753        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16754            return newPkg.packageName;
16755        }
16756        // Check child shared users
16757        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16758        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16759        for (int i = 0; i < newChildCount; i++) {
16760            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16761            // If this child was present, did it have the same shared user?
16762            for (int j = 0; j < oldChildCount; j++) {
16763                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16764                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16765                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16766                    return newChildPkg.packageName;
16767                }
16768            }
16769        }
16770        return null;
16771    }
16772
16773    private void removeNativeBinariesLI(PackageSetting ps) {
16774        // Remove the lib path for the parent package
16775        if (ps != null) {
16776            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16777            // Remove the lib path for the child packages
16778            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16779            for (int i = 0; i < childCount; i++) {
16780                PackageSetting childPs = null;
16781                synchronized (mPackages) {
16782                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16783                }
16784                if (childPs != null) {
16785                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16786                            .legacyNativeLibraryPathString);
16787                }
16788            }
16789        }
16790    }
16791
16792    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16793        // Enable the parent package
16794        mSettings.enableSystemPackageLPw(pkg.packageName);
16795        // Enable the child packages
16796        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16797        for (int i = 0; i < childCount; i++) {
16798            PackageParser.Package childPkg = pkg.childPackages.get(i);
16799            mSettings.enableSystemPackageLPw(childPkg.packageName);
16800        }
16801    }
16802
16803    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16804            PackageParser.Package newPkg) {
16805        // Disable the parent package (parent always replaced)
16806        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16807        // Disable the child packages
16808        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16809        for (int i = 0; i < childCount; i++) {
16810            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16811            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16812            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16813        }
16814        return disabled;
16815    }
16816
16817    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16818            String installerPackageName) {
16819        // Enable the parent package
16820        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16821        // Enable the child packages
16822        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16823        for (int i = 0; i < childCount; i++) {
16824            PackageParser.Package childPkg = pkg.childPackages.get(i);
16825            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16826        }
16827    }
16828
16829    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16830        // Collect all used permissions in the UID
16831        ArraySet<String> usedPermissions = new ArraySet<>();
16832        final int packageCount = su.packages.size();
16833        for (int i = 0; i < packageCount; i++) {
16834            PackageSetting ps = su.packages.valueAt(i);
16835            if (ps.pkg == null) {
16836                continue;
16837            }
16838            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16839            for (int j = 0; j < requestedPermCount; j++) {
16840                String permission = ps.pkg.requestedPermissions.get(j);
16841                BasePermission bp = mSettings.mPermissions.get(permission);
16842                if (bp != null) {
16843                    usedPermissions.add(permission);
16844                }
16845            }
16846        }
16847
16848        PermissionsState permissionsState = su.getPermissionsState();
16849        // Prune install permissions
16850        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16851        final int installPermCount = installPermStates.size();
16852        for (int i = installPermCount - 1; i >= 0;  i--) {
16853            PermissionState permissionState = installPermStates.get(i);
16854            if (!usedPermissions.contains(permissionState.getName())) {
16855                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16856                if (bp != null) {
16857                    permissionsState.revokeInstallPermission(bp);
16858                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16859                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16860                }
16861            }
16862        }
16863
16864        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16865
16866        // Prune runtime permissions
16867        for (int userId : allUserIds) {
16868            List<PermissionState> runtimePermStates = permissionsState
16869                    .getRuntimePermissionStates(userId);
16870            final int runtimePermCount = runtimePermStates.size();
16871            for (int i = runtimePermCount - 1; i >= 0; i--) {
16872                PermissionState permissionState = runtimePermStates.get(i);
16873                if (!usedPermissions.contains(permissionState.getName())) {
16874                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16875                    if (bp != null) {
16876                        permissionsState.revokeRuntimePermission(bp, userId);
16877                        permissionsState.updatePermissionFlags(bp, userId,
16878                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16879                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16880                                runtimePermissionChangedUserIds, userId);
16881                    }
16882                }
16883            }
16884        }
16885
16886        return runtimePermissionChangedUserIds;
16887    }
16888
16889    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16890            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16891        // Update the parent package setting
16892        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16893                res, user, installReason);
16894        // Update the child packages setting
16895        final int childCount = (newPackage.childPackages != null)
16896                ? newPackage.childPackages.size() : 0;
16897        for (int i = 0; i < childCount; i++) {
16898            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16899            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16900            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16901                    childRes.origUsers, childRes, user, installReason);
16902        }
16903    }
16904
16905    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16906            String installerPackageName, int[] allUsers, int[] installedForUsers,
16907            PackageInstalledInfo res, UserHandle user, int installReason) {
16908        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16909
16910        String pkgName = newPackage.packageName;
16911        synchronized (mPackages) {
16912            //write settings. the installStatus will be incomplete at this stage.
16913            //note that the new package setting would have already been
16914            //added to mPackages. It hasn't been persisted yet.
16915            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16916            // TODO: Remove this write? It's also written at the end of this method
16917            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16918            mSettings.writeLPr();
16919            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16920        }
16921
16922        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16923        synchronized (mPackages) {
16924            updatePermissionsLPw(newPackage.packageName, newPackage,
16925                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16926                            ? UPDATE_PERMISSIONS_ALL : 0));
16927            // For system-bundled packages, we assume that installing an upgraded version
16928            // of the package implies that the user actually wants to run that new code,
16929            // so we enable the package.
16930            PackageSetting ps = mSettings.mPackages.get(pkgName);
16931            final int userId = user.getIdentifier();
16932            if (ps != null) {
16933                if (isSystemApp(newPackage)) {
16934                    if (DEBUG_INSTALL) {
16935                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16936                    }
16937                    // Enable system package for requested users
16938                    if (res.origUsers != null) {
16939                        for (int origUserId : res.origUsers) {
16940                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16941                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16942                                        origUserId, installerPackageName);
16943                            }
16944                        }
16945                    }
16946                    // Also convey the prior install/uninstall state
16947                    if (allUsers != null && installedForUsers != null) {
16948                        for (int currentUserId : allUsers) {
16949                            final boolean installed = ArrayUtils.contains(
16950                                    installedForUsers, currentUserId);
16951                            if (DEBUG_INSTALL) {
16952                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16953                            }
16954                            ps.setInstalled(installed, currentUserId);
16955                        }
16956                        // these install state changes will be persisted in the
16957                        // upcoming call to mSettings.writeLPr().
16958                    }
16959                }
16960                // It's implied that when a user requests installation, they want the app to be
16961                // installed and enabled.
16962                if (userId != UserHandle.USER_ALL) {
16963                    ps.setInstalled(true, userId);
16964                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16965                }
16966
16967                // When replacing an existing package, preserve the original install reason for all
16968                // users that had the package installed before.
16969                final Set<Integer> previousUserIds = new ArraySet<>();
16970                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16971                    final int installReasonCount = res.removedInfo.installReasons.size();
16972                    for (int i = 0; i < installReasonCount; i++) {
16973                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16974                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16975                        ps.setInstallReason(previousInstallReason, previousUserId);
16976                        previousUserIds.add(previousUserId);
16977                    }
16978                }
16979
16980                // Set install reason for users that are having the package newly installed.
16981                if (userId == UserHandle.USER_ALL) {
16982                    for (int currentUserId : sUserManager.getUserIds()) {
16983                        if (!previousUserIds.contains(currentUserId)) {
16984                            ps.setInstallReason(installReason, currentUserId);
16985                        }
16986                    }
16987                } else if (!previousUserIds.contains(userId)) {
16988                    ps.setInstallReason(installReason, userId);
16989                }
16990                mSettings.writeKernelMappingLPr(ps);
16991            }
16992            res.name = pkgName;
16993            res.uid = newPackage.applicationInfo.uid;
16994            res.pkg = newPackage;
16995            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16996            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16997            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16998            //to update install status
16999            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17000            mSettings.writeLPr();
17001            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17002        }
17003
17004        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17005    }
17006
17007    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17008        try {
17009            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17010            installPackageLI(args, res);
17011        } finally {
17012            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17013        }
17014    }
17015
17016    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17017        final int installFlags = args.installFlags;
17018        final String installerPackageName = args.installerPackageName;
17019        final String volumeUuid = args.volumeUuid;
17020        final File tmpPackageFile = new File(args.getCodePath());
17021        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17022        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17023                || (args.volumeUuid != null));
17024        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17025        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17026        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17027        boolean replace = false;
17028        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17029        if (args.move != null) {
17030            // moving a complete application; perform an initial scan on the new install location
17031            scanFlags |= SCAN_INITIAL;
17032        }
17033        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17034            scanFlags |= SCAN_DONT_KILL_APP;
17035        }
17036        if (instantApp) {
17037            scanFlags |= SCAN_AS_INSTANT_APP;
17038        }
17039        if (fullApp) {
17040            scanFlags |= SCAN_AS_FULL_APP;
17041        }
17042
17043        // Result object to be returned
17044        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17045
17046        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17047
17048        // Sanity check
17049        if (instantApp && (forwardLocked || onExternal)) {
17050            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17051                    + " external=" + onExternal);
17052            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17053            return;
17054        }
17055
17056        // Retrieve PackageSettings and parse package
17057        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17058                | PackageParser.PARSE_ENFORCE_CODE
17059                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17060                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17061                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17062                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17063        PackageParser pp = new PackageParser();
17064        pp.setSeparateProcesses(mSeparateProcesses);
17065        pp.setDisplayMetrics(mMetrics);
17066        pp.setCallback(mPackageParserCallback);
17067
17068        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17069        final PackageParser.Package pkg;
17070        try {
17071            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17072        } catch (PackageParserException e) {
17073            res.setError("Failed parse during installPackageLI", e);
17074            return;
17075        } finally {
17076            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17077        }
17078
17079        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17080        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17081            Slog.w(TAG, "Instant app package " + pkg.packageName
17082                    + " does not target O, this will be a fatal error.");
17083            // STOPSHIP: Make this a fatal error
17084            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17085        }
17086        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17087            Slog.w(TAG, "Instant app package " + pkg.packageName
17088                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17089            // STOPSHIP: Make this a fatal error
17090            pkg.applicationInfo.targetSandboxVersion = 2;
17091        }
17092
17093        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17094            // Static shared libraries have synthetic package names
17095            renameStaticSharedLibraryPackage(pkg);
17096
17097            // No static shared libs on external storage
17098            if (onExternal) {
17099                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17100                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17101                        "Packages declaring static-shared libs cannot be updated");
17102                return;
17103            }
17104        }
17105
17106        // If we are installing a clustered package add results for the children
17107        if (pkg.childPackages != null) {
17108            synchronized (mPackages) {
17109                final int childCount = pkg.childPackages.size();
17110                for (int i = 0; i < childCount; i++) {
17111                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17112                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17113                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17114                    childRes.pkg = childPkg;
17115                    childRes.name = childPkg.packageName;
17116                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17117                    if (childPs != null) {
17118                        childRes.origUsers = childPs.queryInstalledUsers(
17119                                sUserManager.getUserIds(), true);
17120                    }
17121                    if ((mPackages.containsKey(childPkg.packageName))) {
17122                        childRes.removedInfo = new PackageRemovedInfo(this);
17123                        childRes.removedInfo.removedPackage = childPkg.packageName;
17124                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17125                    }
17126                    if (res.addedChildPackages == null) {
17127                        res.addedChildPackages = new ArrayMap<>();
17128                    }
17129                    res.addedChildPackages.put(childPkg.packageName, childRes);
17130                }
17131            }
17132        }
17133
17134        // If package doesn't declare API override, mark that we have an install
17135        // time CPU ABI override.
17136        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17137            pkg.cpuAbiOverride = args.abiOverride;
17138        }
17139
17140        String pkgName = res.name = pkg.packageName;
17141        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17142            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17143                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17144                return;
17145            }
17146        }
17147
17148        try {
17149            // either use what we've been given or parse directly from the APK
17150            if (args.certificates != null) {
17151                try {
17152                    PackageParser.populateCertificates(pkg, args.certificates);
17153                } catch (PackageParserException e) {
17154                    // there was something wrong with the certificates we were given;
17155                    // try to pull them from the APK
17156                    PackageParser.collectCertificates(pkg, parseFlags);
17157                }
17158            } else {
17159                PackageParser.collectCertificates(pkg, parseFlags);
17160            }
17161        } catch (PackageParserException e) {
17162            res.setError("Failed collect during installPackageLI", e);
17163            return;
17164        }
17165
17166        // Get rid of all references to package scan path via parser.
17167        pp = null;
17168        String oldCodePath = null;
17169        boolean systemApp = false;
17170        synchronized (mPackages) {
17171            // Check if installing already existing package
17172            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17173                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17174                if (pkg.mOriginalPackages != null
17175                        && pkg.mOriginalPackages.contains(oldName)
17176                        && mPackages.containsKey(oldName)) {
17177                    // This package is derived from an original package,
17178                    // and this device has been updating from that original
17179                    // name.  We must continue using the original name, so
17180                    // rename the new package here.
17181                    pkg.setPackageName(oldName);
17182                    pkgName = pkg.packageName;
17183                    replace = true;
17184                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17185                            + oldName + " pkgName=" + pkgName);
17186                } else if (mPackages.containsKey(pkgName)) {
17187                    // This package, under its official name, already exists
17188                    // on the device; we should replace it.
17189                    replace = true;
17190                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17191                }
17192
17193                // Child packages are installed through the parent package
17194                if (pkg.parentPackage != null) {
17195                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17196                            "Package " + pkg.packageName + " is child of package "
17197                                    + pkg.parentPackage.parentPackage + ". Child packages "
17198                                    + "can be updated only through the parent package.");
17199                    return;
17200                }
17201
17202                if (replace) {
17203                    // Prevent apps opting out from runtime permissions
17204                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17205                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17206                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17207                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17208                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17209                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17210                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17211                                        + " doesn't support runtime permissions but the old"
17212                                        + " target SDK " + oldTargetSdk + " does.");
17213                        return;
17214                    }
17215                    // Prevent apps from downgrading their targetSandbox.
17216                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17217                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17218                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17219                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17220                                "Package " + pkg.packageName + " new target sandbox "
17221                                + newTargetSandbox + " is incompatible with the previous value of"
17222                                + oldTargetSandbox + ".");
17223                        return;
17224                    }
17225
17226                    // Prevent installing of child packages
17227                    if (oldPackage.parentPackage != null) {
17228                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17229                                "Package " + pkg.packageName + " is child of package "
17230                                        + oldPackage.parentPackage + ". Child packages "
17231                                        + "can be updated only through the parent package.");
17232                        return;
17233                    }
17234                }
17235            }
17236
17237            PackageSetting ps = mSettings.mPackages.get(pkgName);
17238            if (ps != null) {
17239                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17240
17241                // Static shared libs have same package with different versions where
17242                // we internally use a synthetic package name to allow multiple versions
17243                // of the same package, therefore we need to compare signatures against
17244                // the package setting for the latest library version.
17245                PackageSetting signatureCheckPs = ps;
17246                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17247                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17248                    if (libraryEntry != null) {
17249                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17250                    }
17251                }
17252
17253                // Quick sanity check that we're signed correctly if updating;
17254                // we'll check this again later when scanning, but we want to
17255                // bail early here before tripping over redefined permissions.
17256                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17257                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17258                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17259                                + pkg.packageName + " upgrade keys do not match the "
17260                                + "previously installed version");
17261                        return;
17262                    }
17263                } else {
17264                    try {
17265                        verifySignaturesLP(signatureCheckPs, pkg);
17266                    } catch (PackageManagerException e) {
17267                        res.setError(e.error, e.getMessage());
17268                        return;
17269                    }
17270                }
17271
17272                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17273                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17274                    systemApp = (ps.pkg.applicationInfo.flags &
17275                            ApplicationInfo.FLAG_SYSTEM) != 0;
17276                }
17277                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17278            }
17279
17280            int N = pkg.permissions.size();
17281            for (int i = N-1; i >= 0; i--) {
17282                PackageParser.Permission perm = pkg.permissions.get(i);
17283                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17284
17285                // Don't allow anyone but the system to define ephemeral permissions.
17286                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17287                        && !systemApp) {
17288                    Slog.w(TAG, "Non-System package " + pkg.packageName
17289                            + " attempting to delcare ephemeral permission "
17290                            + perm.info.name + "; Removing ephemeral.");
17291                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17292                }
17293                // Check whether the newly-scanned package wants to define an already-defined perm
17294                if (bp != null) {
17295                    // If the defining package is signed with our cert, it's okay.  This
17296                    // also includes the "updating the same package" case, of course.
17297                    // "updating same package" could also involve key-rotation.
17298                    final boolean sigsOk;
17299                    if (bp.sourcePackage.equals(pkg.packageName)
17300                            && (bp.packageSetting instanceof PackageSetting)
17301                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17302                                    scanFlags))) {
17303                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17304                    } else {
17305                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17306                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17307                    }
17308                    if (!sigsOk) {
17309                        // If the owning package is the system itself, we log but allow
17310                        // install to proceed; we fail the install on all other permission
17311                        // redefinitions.
17312                        if (!bp.sourcePackage.equals("android")) {
17313                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17314                                    + pkg.packageName + " attempting to redeclare permission "
17315                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17316                            res.origPermission = perm.info.name;
17317                            res.origPackage = bp.sourcePackage;
17318                            return;
17319                        } else {
17320                            Slog.w(TAG, "Package " + pkg.packageName
17321                                    + " attempting to redeclare system permission "
17322                                    + perm.info.name + "; ignoring new declaration");
17323                            pkg.permissions.remove(i);
17324                        }
17325                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17326                        // Prevent apps to change protection level to dangerous from any other
17327                        // type as this would allow a privilege escalation where an app adds a
17328                        // normal/signature permission in other app's group and later redefines
17329                        // it as dangerous leading to the group auto-grant.
17330                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17331                                == PermissionInfo.PROTECTION_DANGEROUS) {
17332                            if (bp != null && !bp.isRuntime()) {
17333                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17334                                        + "non-runtime permission " + perm.info.name
17335                                        + " to runtime; keeping old protection level");
17336                                perm.info.protectionLevel = bp.protectionLevel;
17337                            }
17338                        }
17339                    }
17340                }
17341            }
17342        }
17343
17344        if (systemApp) {
17345            if (onExternal) {
17346                // Abort update; system app can't be replaced with app on sdcard
17347                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17348                        "Cannot install updates to system apps on sdcard");
17349                return;
17350            } else if (instantApp) {
17351                // Abort update; system app can't be replaced with an instant app
17352                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17353                        "Cannot update a system app with an instant app");
17354                return;
17355            }
17356        }
17357
17358        if (args.move != null) {
17359            // We did an in-place move, so dex is ready to roll
17360            scanFlags |= SCAN_NO_DEX;
17361            scanFlags |= SCAN_MOVE;
17362
17363            synchronized (mPackages) {
17364                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17365                if (ps == null) {
17366                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17367                            "Missing settings for moved package " + pkgName);
17368                }
17369
17370                // We moved the entire application as-is, so bring over the
17371                // previously derived ABI information.
17372                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17373                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17374            }
17375
17376        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17377            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17378            scanFlags |= SCAN_NO_DEX;
17379
17380            try {
17381                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17382                    args.abiOverride : pkg.cpuAbiOverride);
17383                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17384                        true /*extractLibs*/, mAppLib32InstallDir);
17385            } catch (PackageManagerException pme) {
17386                Slog.e(TAG, "Error deriving application ABI", pme);
17387                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17388                return;
17389            }
17390
17391            // Shared libraries for the package need to be updated.
17392            synchronized (mPackages) {
17393                try {
17394                    updateSharedLibrariesLPr(pkg, null);
17395                } catch (PackageManagerException e) {
17396                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17397                }
17398            }
17399
17400            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17401            // Do not run PackageDexOptimizer through the local performDexOpt
17402            // method because `pkg` may not be in `mPackages` yet.
17403            //
17404            // Also, don't fail application installs if the dexopt step fails.
17405            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17406                    null /* instructionSets */, false /* checkProfiles */,
17407                    getCompilerFilterForReason(REASON_INSTALL),
17408                    getOrCreateCompilerPackageStats(pkg),
17409                    mDexManager.isUsedByOtherApps(pkg.packageName));
17410            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17411
17412            // Notify BackgroundDexOptService that the package has been changed.
17413            // If this is an update of a package which used to fail to compile,
17414            // BDOS will remove it from its blacklist.
17415            // TODO: Layering violation
17416            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17417        }
17418
17419        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17420            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17421            return;
17422        }
17423
17424        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17425
17426        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17427                "installPackageLI")) {
17428            if (replace) {
17429                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17430                    // Static libs have a synthetic package name containing the version
17431                    // and cannot be updated as an update would get a new package name,
17432                    // unless this is the exact same version code which is useful for
17433                    // development.
17434                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17435                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17436                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17437                                + "static-shared libs cannot be updated");
17438                        return;
17439                    }
17440                }
17441                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17442                        installerPackageName, res, args.installReason);
17443            } else {
17444                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17445                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17446            }
17447        }
17448
17449        synchronized (mPackages) {
17450            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17451            if (ps != null) {
17452                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17453                ps.setUpdateAvailable(false /*updateAvailable*/);
17454            }
17455
17456            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17457            for (int i = 0; i < childCount; i++) {
17458                PackageParser.Package childPkg = pkg.childPackages.get(i);
17459                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17460                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17461                if (childPs != null) {
17462                    childRes.newUsers = childPs.queryInstalledUsers(
17463                            sUserManager.getUserIds(), true);
17464                }
17465            }
17466
17467            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17468                updateSequenceNumberLP(pkgName, res.newUsers);
17469                updateInstantAppInstallerLocked(pkgName);
17470            }
17471        }
17472    }
17473
17474    private void startIntentFilterVerifications(int userId, boolean replacing,
17475            PackageParser.Package pkg) {
17476        if (mIntentFilterVerifierComponent == null) {
17477            Slog.w(TAG, "No IntentFilter verification will not be done as "
17478                    + "there is no IntentFilterVerifier available!");
17479            return;
17480        }
17481
17482        final int verifierUid = getPackageUid(
17483                mIntentFilterVerifierComponent.getPackageName(),
17484                MATCH_DEBUG_TRIAGED_MISSING,
17485                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17486
17487        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17488        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17489        mHandler.sendMessage(msg);
17490
17491        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17492        for (int i = 0; i < childCount; i++) {
17493            PackageParser.Package childPkg = pkg.childPackages.get(i);
17494            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17495            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17496            mHandler.sendMessage(msg);
17497        }
17498    }
17499
17500    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17501            PackageParser.Package pkg) {
17502        int size = pkg.activities.size();
17503        if (size == 0) {
17504            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17505                    "No activity, so no need to verify any IntentFilter!");
17506            return;
17507        }
17508
17509        final boolean hasDomainURLs = hasDomainURLs(pkg);
17510        if (!hasDomainURLs) {
17511            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17512                    "No domain URLs, so no need to verify any IntentFilter!");
17513            return;
17514        }
17515
17516        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17517                + " if any IntentFilter from the " + size
17518                + " Activities needs verification ...");
17519
17520        int count = 0;
17521        final String packageName = pkg.packageName;
17522
17523        synchronized (mPackages) {
17524            // If this is a new install and we see that we've already run verification for this
17525            // package, we have nothing to do: it means the state was restored from backup.
17526            if (!replacing) {
17527                IntentFilterVerificationInfo ivi =
17528                        mSettings.getIntentFilterVerificationLPr(packageName);
17529                if (ivi != null) {
17530                    if (DEBUG_DOMAIN_VERIFICATION) {
17531                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17532                                + ivi.getStatusString());
17533                    }
17534                    return;
17535                }
17536            }
17537
17538            // If any filters need to be verified, then all need to be.
17539            boolean needToVerify = false;
17540            for (PackageParser.Activity a : pkg.activities) {
17541                for (ActivityIntentInfo filter : a.intents) {
17542                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17543                        if (DEBUG_DOMAIN_VERIFICATION) {
17544                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17545                        }
17546                        needToVerify = true;
17547                        break;
17548                    }
17549                }
17550            }
17551
17552            if (needToVerify) {
17553                final int verificationId = mIntentFilterVerificationToken++;
17554                for (PackageParser.Activity a : pkg.activities) {
17555                    for (ActivityIntentInfo filter : a.intents) {
17556                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17557                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17558                                    "Verification needed for IntentFilter:" + filter.toString());
17559                            mIntentFilterVerifier.addOneIntentFilterVerification(
17560                                    verifierUid, userId, verificationId, filter, packageName);
17561                            count++;
17562                        }
17563                    }
17564                }
17565            }
17566        }
17567
17568        if (count > 0) {
17569            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17570                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17571                    +  " for userId:" + userId);
17572            mIntentFilterVerifier.startVerifications(userId);
17573        } else {
17574            if (DEBUG_DOMAIN_VERIFICATION) {
17575                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17576            }
17577        }
17578    }
17579
17580    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17581        final ComponentName cn  = filter.activity.getComponentName();
17582        final String packageName = cn.getPackageName();
17583
17584        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17585                packageName);
17586        if (ivi == null) {
17587            return true;
17588        }
17589        int status = ivi.getStatus();
17590        switch (status) {
17591            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17592            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17593                return true;
17594
17595            default:
17596                // Nothing to do
17597                return false;
17598        }
17599    }
17600
17601    private static boolean isMultiArch(ApplicationInfo info) {
17602        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17603    }
17604
17605    private static boolean isExternal(PackageParser.Package pkg) {
17606        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17607    }
17608
17609    private static boolean isExternal(PackageSetting ps) {
17610        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17611    }
17612
17613    private static boolean isSystemApp(PackageParser.Package pkg) {
17614        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17615    }
17616
17617    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17618        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17619    }
17620
17621    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17622        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17623    }
17624
17625    private static boolean isSystemApp(PackageSetting ps) {
17626        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17627    }
17628
17629    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17630        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17631    }
17632
17633    private int packageFlagsToInstallFlags(PackageSetting ps) {
17634        int installFlags = 0;
17635        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17636            // This existing package was an external ASEC install when we have
17637            // the external flag without a UUID
17638            installFlags |= PackageManager.INSTALL_EXTERNAL;
17639        }
17640        if (ps.isForwardLocked()) {
17641            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17642        }
17643        return installFlags;
17644    }
17645
17646    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17647        if (isExternal(pkg)) {
17648            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17649                return StorageManager.UUID_PRIMARY_PHYSICAL;
17650            } else {
17651                return pkg.volumeUuid;
17652            }
17653        } else {
17654            return StorageManager.UUID_PRIVATE_INTERNAL;
17655        }
17656    }
17657
17658    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17659        if (isExternal(pkg)) {
17660            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17661                return mSettings.getExternalVersion();
17662            } else {
17663                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17664            }
17665        } else {
17666            return mSettings.getInternalVersion();
17667        }
17668    }
17669
17670    private void deleteTempPackageFiles() {
17671        final FilenameFilter filter = new FilenameFilter() {
17672            public boolean accept(File dir, String name) {
17673                return name.startsWith("vmdl") && name.endsWith(".tmp");
17674            }
17675        };
17676        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17677            file.delete();
17678        }
17679    }
17680
17681    @Override
17682    public void deletePackageAsUser(String packageName, int versionCode,
17683            IPackageDeleteObserver observer, int userId, int flags) {
17684        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17685                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17686    }
17687
17688    @Override
17689    public void deletePackageVersioned(VersionedPackage versionedPackage,
17690            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17691        mContext.enforceCallingOrSelfPermission(
17692                android.Manifest.permission.DELETE_PACKAGES, null);
17693        Preconditions.checkNotNull(versionedPackage);
17694        Preconditions.checkNotNull(observer);
17695        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17696                PackageManager.VERSION_CODE_HIGHEST,
17697                Integer.MAX_VALUE, "versionCode must be >= -1");
17698
17699        final String packageName = versionedPackage.getPackageName();
17700        // TODO: We will change version code to long, so in the new API it is long
17701        final int versionCode = (int) versionedPackage.getVersionCode();
17702        final String internalPackageName;
17703        synchronized (mPackages) {
17704            // Normalize package name to handle renamed packages and static libs
17705            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17706                    // TODO: We will change version code to long, so in the new API it is long
17707                    (int) versionedPackage.getVersionCode());
17708        }
17709
17710        final int uid = Binder.getCallingUid();
17711        if (!isOrphaned(internalPackageName)
17712                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17713            try {
17714                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17715                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17716                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17717                observer.onUserActionRequired(intent);
17718            } catch (RemoteException re) {
17719            }
17720            return;
17721        }
17722        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17723        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17724        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17725            mContext.enforceCallingOrSelfPermission(
17726                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17727                    "deletePackage for user " + userId);
17728        }
17729
17730        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17731            try {
17732                observer.onPackageDeleted(packageName,
17733                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17734            } catch (RemoteException re) {
17735            }
17736            return;
17737        }
17738
17739        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17740            try {
17741                observer.onPackageDeleted(packageName,
17742                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17743            } catch (RemoteException re) {
17744            }
17745            return;
17746        }
17747
17748        if (DEBUG_REMOVE) {
17749            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17750                    + " deleteAllUsers: " + deleteAllUsers + " version="
17751                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17752                    ? "VERSION_CODE_HIGHEST" : versionCode));
17753        }
17754        // Queue up an async operation since the package deletion may take a little while.
17755        mHandler.post(new Runnable() {
17756            public void run() {
17757                mHandler.removeCallbacks(this);
17758                int returnCode;
17759                if (!deleteAllUsers) {
17760                    returnCode = deletePackageX(internalPackageName, versionCode,
17761                            userId, deleteFlags);
17762                } else {
17763                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17764                            internalPackageName, users);
17765                    // If nobody is blocking uninstall, proceed with delete for all users
17766                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17767                        returnCode = deletePackageX(internalPackageName, versionCode,
17768                                userId, deleteFlags);
17769                    } else {
17770                        // Otherwise uninstall individually for users with blockUninstalls=false
17771                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17772                        for (int userId : users) {
17773                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17774                                returnCode = deletePackageX(internalPackageName, versionCode,
17775                                        userId, userFlags);
17776                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17777                                    Slog.w(TAG, "Package delete failed for user " + userId
17778                                            + ", returnCode " + returnCode);
17779                                }
17780                            }
17781                        }
17782                        // The app has only been marked uninstalled for certain users.
17783                        // We still need to report that delete was blocked
17784                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17785                    }
17786                }
17787                try {
17788                    observer.onPackageDeleted(packageName, returnCode, null);
17789                } catch (RemoteException e) {
17790                    Log.i(TAG, "Observer no longer exists.");
17791                } //end catch
17792            } //end run
17793        });
17794    }
17795
17796    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17797        if (pkg.staticSharedLibName != null) {
17798            return pkg.manifestPackageName;
17799        }
17800        return pkg.packageName;
17801    }
17802
17803    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17804        // Handle renamed packages
17805        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17806        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17807
17808        // Is this a static library?
17809        SparseArray<SharedLibraryEntry> versionedLib =
17810                mStaticLibsByDeclaringPackage.get(packageName);
17811        if (versionedLib == null || versionedLib.size() <= 0) {
17812            return packageName;
17813        }
17814
17815        // Figure out which lib versions the caller can see
17816        SparseIntArray versionsCallerCanSee = null;
17817        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17818        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17819                && callingAppId != Process.ROOT_UID) {
17820            versionsCallerCanSee = new SparseIntArray();
17821            String libName = versionedLib.valueAt(0).info.getName();
17822            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17823            if (uidPackages != null) {
17824                for (String uidPackage : uidPackages) {
17825                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17826                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17827                    if (libIdx >= 0) {
17828                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17829                        versionsCallerCanSee.append(libVersion, libVersion);
17830                    }
17831                }
17832            }
17833        }
17834
17835        // Caller can see nothing - done
17836        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17837            return packageName;
17838        }
17839
17840        // Find the version the caller can see and the app version code
17841        SharedLibraryEntry highestVersion = null;
17842        final int versionCount = versionedLib.size();
17843        for (int i = 0; i < versionCount; i++) {
17844            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17845            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17846                    libEntry.info.getVersion()) < 0) {
17847                continue;
17848            }
17849            // TODO: We will change version code to long, so in the new API it is long
17850            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17851            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17852                if (libVersionCode == versionCode) {
17853                    return libEntry.apk;
17854                }
17855            } else if (highestVersion == null) {
17856                highestVersion = libEntry;
17857            } else if (libVersionCode  > highestVersion.info
17858                    .getDeclaringPackage().getVersionCode()) {
17859                highestVersion = libEntry;
17860            }
17861        }
17862
17863        if (highestVersion != null) {
17864            return highestVersion.apk;
17865        }
17866
17867        return packageName;
17868    }
17869
17870    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17871        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17872              || callingUid == Process.SYSTEM_UID) {
17873            return true;
17874        }
17875        final int callingUserId = UserHandle.getUserId(callingUid);
17876        // If the caller installed the pkgName, then allow it to silently uninstall.
17877        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17878            return true;
17879        }
17880
17881        // Allow package verifier to silently uninstall.
17882        if (mRequiredVerifierPackage != null &&
17883                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17884            return true;
17885        }
17886
17887        // Allow package uninstaller to silently uninstall.
17888        if (mRequiredUninstallerPackage != null &&
17889                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17890            return true;
17891        }
17892
17893        // Allow storage manager to silently uninstall.
17894        if (mStorageManagerPackage != null &&
17895                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17896            return true;
17897        }
17898        return false;
17899    }
17900
17901    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17902        int[] result = EMPTY_INT_ARRAY;
17903        for (int userId : userIds) {
17904            if (getBlockUninstallForUser(packageName, userId)) {
17905                result = ArrayUtils.appendInt(result, userId);
17906            }
17907        }
17908        return result;
17909    }
17910
17911    @Override
17912    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17913        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17914    }
17915
17916    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17917        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17918                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17919        try {
17920            if (dpm != null) {
17921                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17922                        /* callingUserOnly =*/ false);
17923                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17924                        : deviceOwnerComponentName.getPackageName();
17925                // Does the package contains the device owner?
17926                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17927                // this check is probably not needed, since DO should be registered as a device
17928                // admin on some user too. (Original bug for this: b/17657954)
17929                if (packageName.equals(deviceOwnerPackageName)) {
17930                    return true;
17931                }
17932                // Does it contain a device admin for any user?
17933                int[] users;
17934                if (userId == UserHandle.USER_ALL) {
17935                    users = sUserManager.getUserIds();
17936                } else {
17937                    users = new int[]{userId};
17938                }
17939                for (int i = 0; i < users.length; ++i) {
17940                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17941                        return true;
17942                    }
17943                }
17944            }
17945        } catch (RemoteException e) {
17946        }
17947        return false;
17948    }
17949
17950    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17951        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17952    }
17953
17954    /**
17955     *  This method is an internal method that could be get invoked either
17956     *  to delete an installed package or to clean up a failed installation.
17957     *  After deleting an installed package, a broadcast is sent to notify any
17958     *  listeners that the package has been removed. For cleaning up a failed
17959     *  installation, the broadcast is not necessary since the package's
17960     *  installation wouldn't have sent the initial broadcast either
17961     *  The key steps in deleting a package are
17962     *  deleting the package information in internal structures like mPackages,
17963     *  deleting the packages base directories through installd
17964     *  updating mSettings to reflect current status
17965     *  persisting settings for later use
17966     *  sending a broadcast if necessary
17967     */
17968    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17969        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17970        final boolean res;
17971
17972        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17973                ? UserHandle.USER_ALL : userId;
17974
17975        if (isPackageDeviceAdmin(packageName, removeUser)) {
17976            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17977            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17978        }
17979
17980        PackageSetting uninstalledPs = null;
17981        PackageParser.Package pkg = null;
17982
17983        // for the uninstall-updates case and restricted profiles, remember the per-
17984        // user handle installed state
17985        int[] allUsers;
17986        synchronized (mPackages) {
17987            uninstalledPs = mSettings.mPackages.get(packageName);
17988            if (uninstalledPs == null) {
17989                Slog.w(TAG, "Not removing non-existent package " + packageName);
17990                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17991            }
17992
17993            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17994                    && uninstalledPs.versionCode != versionCode) {
17995                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17996                        + uninstalledPs.versionCode + " != " + versionCode);
17997                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17998            }
17999
18000            // Static shared libs can be declared by any package, so let us not
18001            // allow removing a package if it provides a lib others depend on.
18002            pkg = mPackages.get(packageName);
18003            if (pkg != null && pkg.staticSharedLibName != null) {
18004                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18005                        pkg.staticSharedLibVersion);
18006                if (libEntry != null) {
18007                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18008                            libEntry.info, 0, userId);
18009                    if (!ArrayUtils.isEmpty(libClientPackages)) {
18010                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18011                                + " hosting lib " + libEntry.info.getName() + " version "
18012                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
18013                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18014                    }
18015                }
18016            }
18017
18018            allUsers = sUserManager.getUserIds();
18019            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18020        }
18021
18022        final int freezeUser;
18023        if (isUpdatedSystemApp(uninstalledPs)
18024                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18025            // We're downgrading a system app, which will apply to all users, so
18026            // freeze them all during the downgrade
18027            freezeUser = UserHandle.USER_ALL;
18028        } else {
18029            freezeUser = removeUser;
18030        }
18031
18032        synchronized (mInstallLock) {
18033            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18034            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18035                    deleteFlags, "deletePackageX")) {
18036                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18037                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18038            }
18039            synchronized (mPackages) {
18040                if (res) {
18041                    if (pkg != null) {
18042                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18043                    }
18044                    updateSequenceNumberLP(packageName, info.removedUsers);
18045                    updateInstantAppInstallerLocked(packageName);
18046                }
18047            }
18048        }
18049
18050        if (res) {
18051            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18052            info.sendPackageRemovedBroadcasts(killApp);
18053            info.sendSystemPackageUpdatedBroadcasts();
18054            info.sendSystemPackageAppearedBroadcasts();
18055        }
18056        // Force a gc here.
18057        Runtime.getRuntime().gc();
18058        // Delete the resources here after sending the broadcast to let
18059        // other processes clean up before deleting resources.
18060        if (info.args != null) {
18061            synchronized (mInstallLock) {
18062                info.args.doPostDeleteLI(true);
18063            }
18064        }
18065
18066        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18067    }
18068
18069    static class PackageRemovedInfo {
18070        final PackageSender packageSender;
18071        String removedPackage;
18072        String installerPackageName;
18073        int uid = -1;
18074        int removedAppId = -1;
18075        int[] origUsers;
18076        int[] removedUsers = null;
18077        int[] broadcastUsers = null;
18078        SparseArray<Integer> installReasons;
18079        boolean isRemovedPackageSystemUpdate = false;
18080        boolean isUpdate;
18081        boolean dataRemoved;
18082        boolean removedForAllUsers;
18083        boolean isStaticSharedLib;
18084        // Clean up resources deleted packages.
18085        InstallArgs args = null;
18086        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18087        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18088
18089        PackageRemovedInfo(PackageSender packageSender) {
18090            this.packageSender = packageSender;
18091        }
18092
18093        void sendPackageRemovedBroadcasts(boolean killApp) {
18094            sendPackageRemovedBroadcastInternal(killApp);
18095            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18096            for (int i = 0; i < childCount; i++) {
18097                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18098                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18099            }
18100        }
18101
18102        void sendSystemPackageUpdatedBroadcasts() {
18103            if (isRemovedPackageSystemUpdate) {
18104                sendSystemPackageUpdatedBroadcastsInternal();
18105                final int childCount = (removedChildPackages != null)
18106                        ? removedChildPackages.size() : 0;
18107                for (int i = 0; i < childCount; i++) {
18108                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18109                    if (childInfo.isRemovedPackageSystemUpdate) {
18110                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18111                    }
18112                }
18113            }
18114        }
18115
18116        void sendSystemPackageAppearedBroadcasts() {
18117            final int packageCount = (appearedChildPackages != null)
18118                    ? appearedChildPackages.size() : 0;
18119            for (int i = 0; i < packageCount; i++) {
18120                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18121                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18122                    true, UserHandle.getAppId(installedInfo.uid),
18123                    installedInfo.newUsers);
18124            }
18125        }
18126
18127        private void sendSystemPackageUpdatedBroadcastsInternal() {
18128            Bundle extras = new Bundle(2);
18129            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18130            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18131            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18132                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18133            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18134                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18135            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18136                null, null, 0, removedPackage, null, null);
18137            if (installerPackageName != null) {
18138                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18139                        removedPackage, extras, 0 /*flags*/,
18140                        installerPackageName, null, null);
18141                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18142                        removedPackage, extras, 0 /*flags*/,
18143                        installerPackageName, null, null);
18144            }
18145        }
18146
18147        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18148            // Don't send static shared library removal broadcasts as these
18149            // libs are visible only the the apps that depend on them an one
18150            // cannot remove the library if it has a dependency.
18151            if (isStaticSharedLib) {
18152                return;
18153            }
18154            Bundle extras = new Bundle(2);
18155            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18156            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18157            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18158            if (isUpdate || isRemovedPackageSystemUpdate) {
18159                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18160            }
18161            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18162            if (removedPackage != null) {
18163                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18164                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18165                if (installerPackageName != null) {
18166                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18167                            removedPackage, extras, 0 /*flags*/,
18168                            installerPackageName, null, broadcastUsers);
18169                }
18170                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18171                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18172                        removedPackage, extras,
18173                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18174                        null, null, broadcastUsers);
18175                }
18176            }
18177            if (removedAppId >= 0) {
18178                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18179                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18180            }
18181        }
18182
18183        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18184            removedUsers = userIds;
18185            if (removedUsers == null) {
18186                broadcastUsers = null;
18187                return;
18188            }
18189
18190            broadcastUsers = EMPTY_INT_ARRAY;
18191            for (int i = userIds.length - 1; i >= 0; --i) {
18192                final int userId = userIds[i];
18193                if (deletedPackageSetting.getInstantApp(userId)) {
18194                    continue;
18195                }
18196                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18197            }
18198        }
18199    }
18200
18201    /*
18202     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18203     * flag is not set, the data directory is removed as well.
18204     * make sure this flag is set for partially installed apps. If not its meaningless to
18205     * delete a partially installed application.
18206     */
18207    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18208            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18209        String packageName = ps.name;
18210        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18211        // Retrieve object to delete permissions for shared user later on
18212        final PackageParser.Package deletedPkg;
18213        final PackageSetting deletedPs;
18214        // reader
18215        synchronized (mPackages) {
18216            deletedPkg = mPackages.get(packageName);
18217            deletedPs = mSettings.mPackages.get(packageName);
18218            if (outInfo != null) {
18219                outInfo.removedPackage = packageName;
18220                outInfo.installerPackageName = ps.installerPackageName;
18221                outInfo.isStaticSharedLib = deletedPkg != null
18222                        && deletedPkg.staticSharedLibName != null;
18223                outInfo.populateUsers(deletedPs == null ? null
18224                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18225            }
18226        }
18227
18228        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18229
18230        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18231            final PackageParser.Package resolvedPkg;
18232            if (deletedPkg != null) {
18233                resolvedPkg = deletedPkg;
18234            } else {
18235                // We don't have a parsed package when it lives on an ejected
18236                // adopted storage device, so fake something together
18237                resolvedPkg = new PackageParser.Package(ps.name);
18238                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18239            }
18240            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18241                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18242            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18243            if (outInfo != null) {
18244                outInfo.dataRemoved = true;
18245            }
18246            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18247        }
18248
18249        int removedAppId = -1;
18250
18251        // writer
18252        synchronized (mPackages) {
18253            boolean installedStateChanged = false;
18254            if (deletedPs != null) {
18255                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18256                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18257                    clearDefaultBrowserIfNeeded(packageName);
18258                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18259                    removedAppId = mSettings.removePackageLPw(packageName);
18260                    if (outInfo != null) {
18261                        outInfo.removedAppId = removedAppId;
18262                    }
18263                    updatePermissionsLPw(deletedPs.name, null, 0);
18264                    if (deletedPs.sharedUser != null) {
18265                        // Remove permissions associated with package. Since runtime
18266                        // permissions are per user we have to kill the removed package
18267                        // or packages running under the shared user of the removed
18268                        // package if revoking the permissions requested only by the removed
18269                        // package is successful and this causes a change in gids.
18270                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18271                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18272                                    userId);
18273                            if (userIdToKill == UserHandle.USER_ALL
18274                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18275                                // If gids changed for this user, kill all affected packages.
18276                                mHandler.post(new Runnable() {
18277                                    @Override
18278                                    public void run() {
18279                                        // This has to happen with no lock held.
18280                                        killApplication(deletedPs.name, deletedPs.appId,
18281                                                KILL_APP_REASON_GIDS_CHANGED);
18282                                    }
18283                                });
18284                                break;
18285                            }
18286                        }
18287                    }
18288                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18289                }
18290                // make sure to preserve per-user disabled state if this removal was just
18291                // a downgrade of a system app to the factory package
18292                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18293                    if (DEBUG_REMOVE) {
18294                        Slog.d(TAG, "Propagating install state across downgrade");
18295                    }
18296                    for (int userId : allUserHandles) {
18297                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18298                        if (DEBUG_REMOVE) {
18299                            Slog.d(TAG, "    user " + userId + " => " + installed);
18300                        }
18301                        if (installed != ps.getInstalled(userId)) {
18302                            installedStateChanged = true;
18303                        }
18304                        ps.setInstalled(installed, userId);
18305                    }
18306                }
18307            }
18308            // can downgrade to reader
18309            if (writeSettings) {
18310                // Save settings now
18311                mSettings.writeLPr();
18312            }
18313            if (installedStateChanged) {
18314                mSettings.writeKernelMappingLPr(ps);
18315            }
18316        }
18317        if (removedAppId != -1) {
18318            // A user ID was deleted here. Go through all users and remove it
18319            // from KeyStore.
18320            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18321        }
18322    }
18323
18324    static boolean locationIsPrivileged(File path) {
18325        try {
18326            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18327                    .getCanonicalPath();
18328            return path.getCanonicalPath().startsWith(privilegedAppDir);
18329        } catch (IOException e) {
18330            Slog.e(TAG, "Unable to access code path " + path);
18331        }
18332        return false;
18333    }
18334
18335    /*
18336     * Tries to delete system package.
18337     */
18338    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18339            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18340            boolean writeSettings) {
18341        if (deletedPs.parentPackageName != null) {
18342            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18343            return false;
18344        }
18345
18346        final boolean applyUserRestrictions
18347                = (allUserHandles != null) && (outInfo.origUsers != null);
18348        final PackageSetting disabledPs;
18349        // Confirm if the system package has been updated
18350        // An updated system app can be deleted. This will also have to restore
18351        // the system pkg from system partition
18352        // reader
18353        synchronized (mPackages) {
18354            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18355        }
18356
18357        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18358                + " disabledPs=" + disabledPs);
18359
18360        if (disabledPs == null) {
18361            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18362            return false;
18363        } else if (DEBUG_REMOVE) {
18364            Slog.d(TAG, "Deleting system pkg from data partition");
18365        }
18366
18367        if (DEBUG_REMOVE) {
18368            if (applyUserRestrictions) {
18369                Slog.d(TAG, "Remembering install states:");
18370                for (int userId : allUserHandles) {
18371                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18372                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18373                }
18374            }
18375        }
18376
18377        // Delete the updated package
18378        outInfo.isRemovedPackageSystemUpdate = true;
18379        if (outInfo.removedChildPackages != null) {
18380            final int childCount = (deletedPs.childPackageNames != null)
18381                    ? deletedPs.childPackageNames.size() : 0;
18382            for (int i = 0; i < childCount; i++) {
18383                String childPackageName = deletedPs.childPackageNames.get(i);
18384                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18385                        .contains(childPackageName)) {
18386                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18387                            childPackageName);
18388                    if (childInfo != null) {
18389                        childInfo.isRemovedPackageSystemUpdate = true;
18390                    }
18391                }
18392            }
18393        }
18394
18395        if (disabledPs.versionCode < deletedPs.versionCode) {
18396            // Delete data for downgrades
18397            flags &= ~PackageManager.DELETE_KEEP_DATA;
18398        } else {
18399            // Preserve data by setting flag
18400            flags |= PackageManager.DELETE_KEEP_DATA;
18401        }
18402
18403        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18404                outInfo, writeSettings, disabledPs.pkg);
18405        if (!ret) {
18406            return false;
18407        }
18408
18409        // writer
18410        synchronized (mPackages) {
18411            // Reinstate the old system package
18412            enableSystemPackageLPw(disabledPs.pkg);
18413            // Remove any native libraries from the upgraded package.
18414            removeNativeBinariesLI(deletedPs);
18415        }
18416
18417        // Install the system package
18418        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18419        int parseFlags = mDefParseFlags
18420                | PackageParser.PARSE_MUST_BE_APK
18421                | PackageParser.PARSE_IS_SYSTEM
18422                | PackageParser.PARSE_IS_SYSTEM_DIR;
18423        if (locationIsPrivileged(disabledPs.codePath)) {
18424            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18425        }
18426
18427        final PackageParser.Package newPkg;
18428        try {
18429            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18430                0 /* currentTime */, null);
18431        } catch (PackageManagerException e) {
18432            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18433                    + e.getMessage());
18434            return false;
18435        }
18436
18437        try {
18438            // update shared libraries for the newly re-installed system package
18439            updateSharedLibrariesLPr(newPkg, null);
18440        } catch (PackageManagerException e) {
18441            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18442        }
18443
18444        prepareAppDataAfterInstallLIF(newPkg);
18445
18446        // writer
18447        synchronized (mPackages) {
18448            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18449
18450            // Propagate the permissions state as we do not want to drop on the floor
18451            // runtime permissions. The update permissions method below will take
18452            // care of removing obsolete permissions and grant install permissions.
18453            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18454            updatePermissionsLPw(newPkg.packageName, newPkg,
18455                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18456
18457            if (applyUserRestrictions) {
18458                boolean installedStateChanged = false;
18459                if (DEBUG_REMOVE) {
18460                    Slog.d(TAG, "Propagating install state across reinstall");
18461                }
18462                for (int userId : allUserHandles) {
18463                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18464                    if (DEBUG_REMOVE) {
18465                        Slog.d(TAG, "    user " + userId + " => " + installed);
18466                    }
18467                    if (installed != ps.getInstalled(userId)) {
18468                        installedStateChanged = true;
18469                    }
18470                    ps.setInstalled(installed, userId);
18471
18472                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18473                }
18474                // Regardless of writeSettings we need to ensure that this restriction
18475                // state propagation is persisted
18476                mSettings.writeAllUsersPackageRestrictionsLPr();
18477                if (installedStateChanged) {
18478                    mSettings.writeKernelMappingLPr(ps);
18479                }
18480            }
18481            // can downgrade to reader here
18482            if (writeSettings) {
18483                mSettings.writeLPr();
18484            }
18485        }
18486        return true;
18487    }
18488
18489    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18490            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18491            PackageRemovedInfo outInfo, boolean writeSettings,
18492            PackageParser.Package replacingPackage) {
18493        synchronized (mPackages) {
18494            if (outInfo != null) {
18495                outInfo.uid = ps.appId;
18496            }
18497
18498            if (outInfo != null && outInfo.removedChildPackages != null) {
18499                final int childCount = (ps.childPackageNames != null)
18500                        ? ps.childPackageNames.size() : 0;
18501                for (int i = 0; i < childCount; i++) {
18502                    String childPackageName = ps.childPackageNames.get(i);
18503                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18504                    if (childPs == null) {
18505                        return false;
18506                    }
18507                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18508                            childPackageName);
18509                    if (childInfo != null) {
18510                        childInfo.uid = childPs.appId;
18511                    }
18512                }
18513            }
18514        }
18515
18516        // Delete package data from internal structures and also remove data if flag is set
18517        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18518
18519        // Delete the child packages data
18520        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18521        for (int i = 0; i < childCount; i++) {
18522            PackageSetting childPs;
18523            synchronized (mPackages) {
18524                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18525            }
18526            if (childPs != null) {
18527                PackageRemovedInfo childOutInfo = (outInfo != null
18528                        && outInfo.removedChildPackages != null)
18529                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18530                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18531                        && (replacingPackage != null
18532                        && !replacingPackage.hasChildPackage(childPs.name))
18533                        ? flags & ~DELETE_KEEP_DATA : flags;
18534                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18535                        deleteFlags, writeSettings);
18536            }
18537        }
18538
18539        // Delete application code and resources only for parent packages
18540        if (ps.parentPackageName == null) {
18541            if (deleteCodeAndResources && (outInfo != null)) {
18542                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18543                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18544                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18545            }
18546        }
18547
18548        return true;
18549    }
18550
18551    @Override
18552    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18553            int userId) {
18554        mContext.enforceCallingOrSelfPermission(
18555                android.Manifest.permission.DELETE_PACKAGES, null);
18556        synchronized (mPackages) {
18557            // Cannot block uninstall of static shared libs as they are
18558            // considered a part of the using app (emulating static linking).
18559            // Also static libs are installed always on internal storage.
18560            PackageParser.Package pkg = mPackages.get(packageName);
18561            if (pkg != null && pkg.staticSharedLibName != null) {
18562                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18563                        + " providing static shared library: " + pkg.staticSharedLibName);
18564                return false;
18565            }
18566            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18567            mSettings.writePackageRestrictionsLPr(userId);
18568        }
18569        return true;
18570    }
18571
18572    @Override
18573    public boolean getBlockUninstallForUser(String packageName, int userId) {
18574        synchronized (mPackages) {
18575            return mSettings.getBlockUninstallLPr(userId, packageName);
18576        }
18577    }
18578
18579    @Override
18580    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18581        int callingUid = Binder.getCallingUid();
18582        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18583            throw new SecurityException(
18584                    "setRequiredForSystemUser can only be run by the system or root");
18585        }
18586        synchronized (mPackages) {
18587            PackageSetting ps = mSettings.mPackages.get(packageName);
18588            if (ps == null) {
18589                Log.w(TAG, "Package doesn't exist: " + packageName);
18590                return false;
18591            }
18592            if (systemUserApp) {
18593                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18594            } else {
18595                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18596            }
18597            mSettings.writeLPr();
18598        }
18599        return true;
18600    }
18601
18602    /*
18603     * This method handles package deletion in general
18604     */
18605    private boolean deletePackageLIF(String packageName, UserHandle user,
18606            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18607            PackageRemovedInfo outInfo, boolean writeSettings,
18608            PackageParser.Package replacingPackage) {
18609        if (packageName == null) {
18610            Slog.w(TAG, "Attempt to delete null packageName.");
18611            return false;
18612        }
18613
18614        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18615
18616        PackageSetting ps;
18617        synchronized (mPackages) {
18618            ps = mSettings.mPackages.get(packageName);
18619            if (ps == null) {
18620                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18621                return false;
18622            }
18623
18624            if (ps.parentPackageName != null && (!isSystemApp(ps)
18625                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18626                if (DEBUG_REMOVE) {
18627                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18628                            + ((user == null) ? UserHandle.USER_ALL : user));
18629                }
18630                final int removedUserId = (user != null) ? user.getIdentifier()
18631                        : UserHandle.USER_ALL;
18632                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18633                    return false;
18634                }
18635                markPackageUninstalledForUserLPw(ps, user);
18636                scheduleWritePackageRestrictionsLocked(user);
18637                return true;
18638            }
18639        }
18640
18641        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18642                && user.getIdentifier() != UserHandle.USER_ALL)) {
18643            // The caller is asking that the package only be deleted for a single
18644            // user.  To do this, we just mark its uninstalled state and delete
18645            // its data. If this is a system app, we only allow this to happen if
18646            // they have set the special DELETE_SYSTEM_APP which requests different
18647            // semantics than normal for uninstalling system apps.
18648            markPackageUninstalledForUserLPw(ps, user);
18649
18650            if (!isSystemApp(ps)) {
18651                // Do not uninstall the APK if an app should be cached
18652                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18653                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18654                    // Other user still have this package installed, so all
18655                    // we need to do is clear this user's data and save that
18656                    // it is uninstalled.
18657                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18658                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18659                        return false;
18660                    }
18661                    scheduleWritePackageRestrictionsLocked(user);
18662                    return true;
18663                } else {
18664                    // We need to set it back to 'installed' so the uninstall
18665                    // broadcasts will be sent correctly.
18666                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18667                    ps.setInstalled(true, user.getIdentifier());
18668                    mSettings.writeKernelMappingLPr(ps);
18669                }
18670            } else {
18671                // This is a system app, so we assume that the
18672                // other users still have this package installed, so all
18673                // we need to do is clear this user's data and save that
18674                // it is uninstalled.
18675                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18676                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18677                    return false;
18678                }
18679                scheduleWritePackageRestrictionsLocked(user);
18680                return true;
18681            }
18682        }
18683
18684        // If we are deleting a composite package for all users, keep track
18685        // of result for each child.
18686        if (ps.childPackageNames != null && outInfo != null) {
18687            synchronized (mPackages) {
18688                final int childCount = ps.childPackageNames.size();
18689                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18690                for (int i = 0; i < childCount; i++) {
18691                    String childPackageName = ps.childPackageNames.get(i);
18692                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18693                    childInfo.removedPackage = childPackageName;
18694                    childInfo.installerPackageName = ps.installerPackageName;
18695                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18696                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18697                    if (childPs != null) {
18698                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18699                    }
18700                }
18701            }
18702        }
18703
18704        boolean ret = false;
18705        if (isSystemApp(ps)) {
18706            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18707            // When an updated system application is deleted we delete the existing resources
18708            // as well and fall back to existing code in system partition
18709            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18710        } else {
18711            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18712            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18713                    outInfo, writeSettings, replacingPackage);
18714        }
18715
18716        // Take a note whether we deleted the package for all users
18717        if (outInfo != null) {
18718            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18719            if (outInfo.removedChildPackages != null) {
18720                synchronized (mPackages) {
18721                    final int childCount = outInfo.removedChildPackages.size();
18722                    for (int i = 0; i < childCount; i++) {
18723                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18724                        if (childInfo != null) {
18725                            childInfo.removedForAllUsers = mPackages.get(
18726                                    childInfo.removedPackage) == null;
18727                        }
18728                    }
18729                }
18730            }
18731            // If we uninstalled an update to a system app there may be some
18732            // child packages that appeared as they are declared in the system
18733            // app but were not declared in the update.
18734            if (isSystemApp(ps)) {
18735                synchronized (mPackages) {
18736                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18737                    final int childCount = (updatedPs.childPackageNames != null)
18738                            ? updatedPs.childPackageNames.size() : 0;
18739                    for (int i = 0; i < childCount; i++) {
18740                        String childPackageName = updatedPs.childPackageNames.get(i);
18741                        if (outInfo.removedChildPackages == null
18742                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18743                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18744                            if (childPs == null) {
18745                                continue;
18746                            }
18747                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18748                            installRes.name = childPackageName;
18749                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18750                            installRes.pkg = mPackages.get(childPackageName);
18751                            installRes.uid = childPs.pkg.applicationInfo.uid;
18752                            if (outInfo.appearedChildPackages == null) {
18753                                outInfo.appearedChildPackages = new ArrayMap<>();
18754                            }
18755                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18756                        }
18757                    }
18758                }
18759            }
18760        }
18761
18762        return ret;
18763    }
18764
18765    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18766        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18767                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18768        for (int nextUserId : userIds) {
18769            if (DEBUG_REMOVE) {
18770                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18771            }
18772            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18773                    false /*installed*/,
18774                    true /*stopped*/,
18775                    true /*notLaunched*/,
18776                    false /*hidden*/,
18777                    false /*suspended*/,
18778                    false /*instantApp*/,
18779                    null /*lastDisableAppCaller*/,
18780                    null /*enabledComponents*/,
18781                    null /*disabledComponents*/,
18782                    ps.readUserState(nextUserId).domainVerificationStatus,
18783                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18784        }
18785        mSettings.writeKernelMappingLPr(ps);
18786    }
18787
18788    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18789            PackageRemovedInfo outInfo) {
18790        final PackageParser.Package pkg;
18791        synchronized (mPackages) {
18792            pkg = mPackages.get(ps.name);
18793        }
18794
18795        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18796                : new int[] {userId};
18797        for (int nextUserId : userIds) {
18798            if (DEBUG_REMOVE) {
18799                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18800                        + nextUserId);
18801            }
18802
18803            destroyAppDataLIF(pkg, userId,
18804                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18805            destroyAppProfilesLIF(pkg, userId);
18806            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18807            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18808            schedulePackageCleaning(ps.name, nextUserId, false);
18809            synchronized (mPackages) {
18810                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18811                    scheduleWritePackageRestrictionsLocked(nextUserId);
18812                }
18813                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18814            }
18815        }
18816
18817        if (outInfo != null) {
18818            outInfo.removedPackage = ps.name;
18819            outInfo.installerPackageName = ps.installerPackageName;
18820            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18821            outInfo.removedAppId = ps.appId;
18822            outInfo.removedUsers = userIds;
18823            outInfo.broadcastUsers = userIds;
18824        }
18825
18826        return true;
18827    }
18828
18829    private final class ClearStorageConnection implements ServiceConnection {
18830        IMediaContainerService mContainerService;
18831
18832        @Override
18833        public void onServiceConnected(ComponentName name, IBinder service) {
18834            synchronized (this) {
18835                mContainerService = IMediaContainerService.Stub
18836                        .asInterface(Binder.allowBlocking(service));
18837                notifyAll();
18838            }
18839        }
18840
18841        @Override
18842        public void onServiceDisconnected(ComponentName name) {
18843        }
18844    }
18845
18846    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18847        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18848
18849        final boolean mounted;
18850        if (Environment.isExternalStorageEmulated()) {
18851            mounted = true;
18852        } else {
18853            final String status = Environment.getExternalStorageState();
18854
18855            mounted = status.equals(Environment.MEDIA_MOUNTED)
18856                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18857        }
18858
18859        if (!mounted) {
18860            return;
18861        }
18862
18863        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18864        int[] users;
18865        if (userId == UserHandle.USER_ALL) {
18866            users = sUserManager.getUserIds();
18867        } else {
18868            users = new int[] { userId };
18869        }
18870        final ClearStorageConnection conn = new ClearStorageConnection();
18871        if (mContext.bindServiceAsUser(
18872                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18873            try {
18874                for (int curUser : users) {
18875                    long timeout = SystemClock.uptimeMillis() + 5000;
18876                    synchronized (conn) {
18877                        long now;
18878                        while (conn.mContainerService == null &&
18879                                (now = SystemClock.uptimeMillis()) < timeout) {
18880                            try {
18881                                conn.wait(timeout - now);
18882                            } catch (InterruptedException e) {
18883                            }
18884                        }
18885                    }
18886                    if (conn.mContainerService == null) {
18887                        return;
18888                    }
18889
18890                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18891                    clearDirectory(conn.mContainerService,
18892                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18893                    if (allData) {
18894                        clearDirectory(conn.mContainerService,
18895                                userEnv.buildExternalStorageAppDataDirs(packageName));
18896                        clearDirectory(conn.mContainerService,
18897                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18898                    }
18899                }
18900            } finally {
18901                mContext.unbindService(conn);
18902            }
18903        }
18904    }
18905
18906    @Override
18907    public void clearApplicationProfileData(String packageName) {
18908        enforceSystemOrRoot("Only the system can clear all profile data");
18909
18910        final PackageParser.Package pkg;
18911        synchronized (mPackages) {
18912            pkg = mPackages.get(packageName);
18913        }
18914
18915        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18916            synchronized (mInstallLock) {
18917                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18918            }
18919        }
18920    }
18921
18922    @Override
18923    public void clearApplicationUserData(final String packageName,
18924            final IPackageDataObserver observer, final int userId) {
18925        mContext.enforceCallingOrSelfPermission(
18926                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18927
18928        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18929                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18930
18931        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18932            throw new SecurityException("Cannot clear data for a protected package: "
18933                    + packageName);
18934        }
18935        // Queue up an async operation since the package deletion may take a little while.
18936        mHandler.post(new Runnable() {
18937            public void run() {
18938                mHandler.removeCallbacks(this);
18939                final boolean succeeded;
18940                try (PackageFreezer freezer = freezePackage(packageName,
18941                        "clearApplicationUserData")) {
18942                    synchronized (mInstallLock) {
18943                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18944                    }
18945                    clearExternalStorageDataSync(packageName, userId, true);
18946                    synchronized (mPackages) {
18947                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18948                                packageName, userId);
18949                    }
18950                }
18951                if (succeeded) {
18952                    // invoke DeviceStorageMonitor's update method to clear any notifications
18953                    DeviceStorageMonitorInternal dsm = LocalServices
18954                            .getService(DeviceStorageMonitorInternal.class);
18955                    if (dsm != null) {
18956                        dsm.checkMemory();
18957                    }
18958                }
18959                if(observer != null) {
18960                    try {
18961                        observer.onRemoveCompleted(packageName, succeeded);
18962                    } catch (RemoteException e) {
18963                        Log.i(TAG, "Observer no longer exists.");
18964                    }
18965                } //end if observer
18966            } //end run
18967        });
18968    }
18969
18970    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18971        if (packageName == null) {
18972            Slog.w(TAG, "Attempt to delete null packageName.");
18973            return false;
18974        }
18975
18976        // Try finding details about the requested package
18977        PackageParser.Package pkg;
18978        synchronized (mPackages) {
18979            pkg = mPackages.get(packageName);
18980            if (pkg == null) {
18981                final PackageSetting ps = mSettings.mPackages.get(packageName);
18982                if (ps != null) {
18983                    pkg = ps.pkg;
18984                }
18985            }
18986
18987            if (pkg == null) {
18988                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18989                return false;
18990            }
18991
18992            PackageSetting ps = (PackageSetting) pkg.mExtras;
18993            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18994        }
18995
18996        clearAppDataLIF(pkg, userId,
18997                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18998
18999        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19000        removeKeystoreDataIfNeeded(userId, appId);
19001
19002        UserManagerInternal umInternal = getUserManagerInternal();
19003        final int flags;
19004        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19005            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19006        } else if (umInternal.isUserRunning(userId)) {
19007            flags = StorageManager.FLAG_STORAGE_DE;
19008        } else {
19009            flags = 0;
19010        }
19011        prepareAppDataContentsLIF(pkg, userId, flags);
19012
19013        return true;
19014    }
19015
19016    /**
19017     * Reverts user permission state changes (permissions and flags) in
19018     * all packages for a given user.
19019     *
19020     * @param userId The device user for which to do a reset.
19021     */
19022    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19023        final int packageCount = mPackages.size();
19024        for (int i = 0; i < packageCount; i++) {
19025            PackageParser.Package pkg = mPackages.valueAt(i);
19026            PackageSetting ps = (PackageSetting) pkg.mExtras;
19027            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19028        }
19029    }
19030
19031    private void resetNetworkPolicies(int userId) {
19032        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19033    }
19034
19035    /**
19036     * Reverts user permission state changes (permissions and flags).
19037     *
19038     * @param ps The package for which to reset.
19039     * @param userId The device user for which to do a reset.
19040     */
19041    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19042            final PackageSetting ps, final int userId) {
19043        if (ps.pkg == null) {
19044            return;
19045        }
19046
19047        // These are flags that can change base on user actions.
19048        final int userSettableMask = FLAG_PERMISSION_USER_SET
19049                | FLAG_PERMISSION_USER_FIXED
19050                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19051                | FLAG_PERMISSION_REVIEW_REQUIRED;
19052
19053        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19054                | FLAG_PERMISSION_POLICY_FIXED;
19055
19056        boolean writeInstallPermissions = false;
19057        boolean writeRuntimePermissions = false;
19058
19059        final int permissionCount = ps.pkg.requestedPermissions.size();
19060        for (int i = 0; i < permissionCount; i++) {
19061            String permission = ps.pkg.requestedPermissions.get(i);
19062
19063            BasePermission bp = mSettings.mPermissions.get(permission);
19064            if (bp == null) {
19065                continue;
19066            }
19067
19068            // If shared user we just reset the state to which only this app contributed.
19069            if (ps.sharedUser != null) {
19070                boolean used = false;
19071                final int packageCount = ps.sharedUser.packages.size();
19072                for (int j = 0; j < packageCount; j++) {
19073                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19074                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19075                            && pkg.pkg.requestedPermissions.contains(permission)) {
19076                        used = true;
19077                        break;
19078                    }
19079                }
19080                if (used) {
19081                    continue;
19082                }
19083            }
19084
19085            PermissionsState permissionsState = ps.getPermissionsState();
19086
19087            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19088
19089            // Always clear the user settable flags.
19090            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19091                    bp.name) != null;
19092            // If permission review is enabled and this is a legacy app, mark the
19093            // permission as requiring a review as this is the initial state.
19094            int flags = 0;
19095            if (mPermissionReviewRequired
19096                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19097                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19098            }
19099            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19100                if (hasInstallState) {
19101                    writeInstallPermissions = true;
19102                } else {
19103                    writeRuntimePermissions = true;
19104                }
19105            }
19106
19107            // Below is only runtime permission handling.
19108            if (!bp.isRuntime()) {
19109                continue;
19110            }
19111
19112            // Never clobber system or policy.
19113            if ((oldFlags & policyOrSystemFlags) != 0) {
19114                continue;
19115            }
19116
19117            // If this permission was granted by default, make sure it is.
19118            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19119                if (permissionsState.grantRuntimePermission(bp, userId)
19120                        != PERMISSION_OPERATION_FAILURE) {
19121                    writeRuntimePermissions = true;
19122                }
19123            // If permission review is enabled the permissions for a legacy apps
19124            // are represented as constantly granted runtime ones, so don't revoke.
19125            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19126                // Otherwise, reset the permission.
19127                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19128                switch (revokeResult) {
19129                    case PERMISSION_OPERATION_SUCCESS:
19130                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19131                        writeRuntimePermissions = true;
19132                        final int appId = ps.appId;
19133                        mHandler.post(new Runnable() {
19134                            @Override
19135                            public void run() {
19136                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19137                            }
19138                        });
19139                    } break;
19140                }
19141            }
19142        }
19143
19144        // Synchronously write as we are taking permissions away.
19145        if (writeRuntimePermissions) {
19146            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19147        }
19148
19149        // Synchronously write as we are taking permissions away.
19150        if (writeInstallPermissions) {
19151            mSettings.writeLPr();
19152        }
19153    }
19154
19155    /**
19156     * Remove entries from the keystore daemon. Will only remove it if the
19157     * {@code appId} is valid.
19158     */
19159    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19160        if (appId < 0) {
19161            return;
19162        }
19163
19164        final KeyStore keyStore = KeyStore.getInstance();
19165        if (keyStore != null) {
19166            if (userId == UserHandle.USER_ALL) {
19167                for (final int individual : sUserManager.getUserIds()) {
19168                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19169                }
19170            } else {
19171                keyStore.clearUid(UserHandle.getUid(userId, appId));
19172            }
19173        } else {
19174            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19175        }
19176    }
19177
19178    @Override
19179    public void deleteApplicationCacheFiles(final String packageName,
19180            final IPackageDataObserver observer) {
19181        final int userId = UserHandle.getCallingUserId();
19182        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19183    }
19184
19185    @Override
19186    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19187            final IPackageDataObserver observer) {
19188        mContext.enforceCallingOrSelfPermission(
19189                android.Manifest.permission.DELETE_CACHE_FILES, null);
19190        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19191                /* requireFullPermission= */ true, /* checkShell= */ false,
19192                "delete application cache files");
19193
19194        final PackageParser.Package pkg;
19195        synchronized (mPackages) {
19196            pkg = mPackages.get(packageName);
19197        }
19198
19199        // Queue up an async operation since the package deletion may take a little while.
19200        mHandler.post(new Runnable() {
19201            public void run() {
19202                synchronized (mInstallLock) {
19203                    final int flags = StorageManager.FLAG_STORAGE_DE
19204                            | StorageManager.FLAG_STORAGE_CE;
19205                    // We're only clearing cache files, so we don't care if the
19206                    // app is unfrozen and still able to run
19207                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19208                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19209                }
19210                clearExternalStorageDataSync(packageName, userId, false);
19211                if (observer != null) {
19212                    try {
19213                        observer.onRemoveCompleted(packageName, true);
19214                    } catch (RemoteException e) {
19215                        Log.i(TAG, "Observer no longer exists.");
19216                    }
19217                }
19218            }
19219        });
19220    }
19221
19222    @Override
19223    public void getPackageSizeInfo(final String packageName, int userHandle,
19224            final IPackageStatsObserver observer) {
19225        throw new UnsupportedOperationException(
19226                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19227    }
19228
19229    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19230        final PackageSetting ps;
19231        synchronized (mPackages) {
19232            ps = mSettings.mPackages.get(packageName);
19233            if (ps == null) {
19234                Slog.w(TAG, "Failed to find settings for " + packageName);
19235                return false;
19236            }
19237        }
19238
19239        final String[] packageNames = { packageName };
19240        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19241        final String[] codePaths = { ps.codePathString };
19242
19243        try {
19244            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19245                    ps.appId, ceDataInodes, codePaths, stats);
19246
19247            // For now, ignore code size of packages on system partition
19248            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19249                stats.codeSize = 0;
19250            }
19251
19252            // External clients expect these to be tracked separately
19253            stats.dataSize -= stats.cacheSize;
19254
19255        } catch (InstallerException e) {
19256            Slog.w(TAG, String.valueOf(e));
19257            return false;
19258        }
19259
19260        return true;
19261    }
19262
19263    private int getUidTargetSdkVersionLockedLPr(int uid) {
19264        Object obj = mSettings.getUserIdLPr(uid);
19265        if (obj instanceof SharedUserSetting) {
19266            final SharedUserSetting sus = (SharedUserSetting) obj;
19267            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19268            final Iterator<PackageSetting> it = sus.packages.iterator();
19269            while (it.hasNext()) {
19270                final PackageSetting ps = it.next();
19271                if (ps.pkg != null) {
19272                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19273                    if (v < vers) vers = v;
19274                }
19275            }
19276            return vers;
19277        } else if (obj instanceof PackageSetting) {
19278            final PackageSetting ps = (PackageSetting) obj;
19279            if (ps.pkg != null) {
19280                return ps.pkg.applicationInfo.targetSdkVersion;
19281            }
19282        }
19283        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19284    }
19285
19286    @Override
19287    public void addPreferredActivity(IntentFilter filter, int match,
19288            ComponentName[] set, ComponentName activity, int userId) {
19289        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19290                "Adding preferred");
19291    }
19292
19293    private void addPreferredActivityInternal(IntentFilter filter, int match,
19294            ComponentName[] set, ComponentName activity, boolean always, int userId,
19295            String opname) {
19296        // writer
19297        int callingUid = Binder.getCallingUid();
19298        enforceCrossUserPermission(callingUid, userId,
19299                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19300        if (filter.countActions() == 0) {
19301            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19302            return;
19303        }
19304        synchronized (mPackages) {
19305            if (mContext.checkCallingOrSelfPermission(
19306                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19307                    != PackageManager.PERMISSION_GRANTED) {
19308                if (getUidTargetSdkVersionLockedLPr(callingUid)
19309                        < Build.VERSION_CODES.FROYO) {
19310                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19311                            + callingUid);
19312                    return;
19313                }
19314                mContext.enforceCallingOrSelfPermission(
19315                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19316            }
19317
19318            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19319            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19320                    + userId + ":");
19321            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19322            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19323            scheduleWritePackageRestrictionsLocked(userId);
19324            postPreferredActivityChangedBroadcast(userId);
19325        }
19326    }
19327
19328    private void postPreferredActivityChangedBroadcast(int userId) {
19329        mHandler.post(() -> {
19330            final IActivityManager am = ActivityManager.getService();
19331            if (am == null) {
19332                return;
19333            }
19334
19335            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19336            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19337            try {
19338                am.broadcastIntent(null, intent, null, null,
19339                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19340                        null, false, false, userId);
19341            } catch (RemoteException e) {
19342            }
19343        });
19344    }
19345
19346    @Override
19347    public void replacePreferredActivity(IntentFilter filter, int match,
19348            ComponentName[] set, ComponentName activity, int userId) {
19349        if (filter.countActions() != 1) {
19350            throw new IllegalArgumentException(
19351                    "replacePreferredActivity expects filter to have only 1 action.");
19352        }
19353        if (filter.countDataAuthorities() != 0
19354                || filter.countDataPaths() != 0
19355                || filter.countDataSchemes() > 1
19356                || filter.countDataTypes() != 0) {
19357            throw new IllegalArgumentException(
19358                    "replacePreferredActivity expects filter to have no data authorities, " +
19359                    "paths, or types; and at most one scheme.");
19360        }
19361
19362        final int callingUid = Binder.getCallingUid();
19363        enforceCrossUserPermission(callingUid, userId,
19364                true /* requireFullPermission */, false /* checkShell */,
19365                "replace preferred activity");
19366        synchronized (mPackages) {
19367            if (mContext.checkCallingOrSelfPermission(
19368                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19369                    != PackageManager.PERMISSION_GRANTED) {
19370                if (getUidTargetSdkVersionLockedLPr(callingUid)
19371                        < Build.VERSION_CODES.FROYO) {
19372                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19373                            + Binder.getCallingUid());
19374                    return;
19375                }
19376                mContext.enforceCallingOrSelfPermission(
19377                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19378            }
19379
19380            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19381            if (pir != null) {
19382                // Get all of the existing entries that exactly match this filter.
19383                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19384                if (existing != null && existing.size() == 1) {
19385                    PreferredActivity cur = existing.get(0);
19386                    if (DEBUG_PREFERRED) {
19387                        Slog.i(TAG, "Checking replace of preferred:");
19388                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19389                        if (!cur.mPref.mAlways) {
19390                            Slog.i(TAG, "  -- CUR; not mAlways!");
19391                        } else {
19392                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19393                            Slog.i(TAG, "  -- CUR: mSet="
19394                                    + Arrays.toString(cur.mPref.mSetComponents));
19395                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19396                            Slog.i(TAG, "  -- NEW: mMatch="
19397                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19398                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19399                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19400                        }
19401                    }
19402                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19403                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19404                            && cur.mPref.sameSet(set)) {
19405                        // Setting the preferred activity to what it happens to be already
19406                        if (DEBUG_PREFERRED) {
19407                            Slog.i(TAG, "Replacing with same preferred activity "
19408                                    + cur.mPref.mShortComponent + " for user "
19409                                    + userId + ":");
19410                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19411                        }
19412                        return;
19413                    }
19414                }
19415
19416                if (existing != null) {
19417                    if (DEBUG_PREFERRED) {
19418                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19419                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19420                    }
19421                    for (int i = 0; i < existing.size(); i++) {
19422                        PreferredActivity pa = existing.get(i);
19423                        if (DEBUG_PREFERRED) {
19424                            Slog.i(TAG, "Removing existing preferred activity "
19425                                    + pa.mPref.mComponent + ":");
19426                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19427                        }
19428                        pir.removeFilter(pa);
19429                    }
19430                }
19431            }
19432            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19433                    "Replacing preferred");
19434        }
19435    }
19436
19437    @Override
19438    public void clearPackagePreferredActivities(String packageName) {
19439        final int uid = Binder.getCallingUid();
19440        // writer
19441        synchronized (mPackages) {
19442            PackageParser.Package pkg = mPackages.get(packageName);
19443            if (pkg == null || pkg.applicationInfo.uid != uid) {
19444                if (mContext.checkCallingOrSelfPermission(
19445                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19446                        != PackageManager.PERMISSION_GRANTED) {
19447                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19448                            < Build.VERSION_CODES.FROYO) {
19449                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19450                                + Binder.getCallingUid());
19451                        return;
19452                    }
19453                    mContext.enforceCallingOrSelfPermission(
19454                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19455                }
19456            }
19457
19458            int user = UserHandle.getCallingUserId();
19459            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19460                scheduleWritePackageRestrictionsLocked(user);
19461            }
19462        }
19463    }
19464
19465    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19466    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19467        ArrayList<PreferredActivity> removed = null;
19468        boolean changed = false;
19469        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19470            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19471            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19472            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19473                continue;
19474            }
19475            Iterator<PreferredActivity> it = pir.filterIterator();
19476            while (it.hasNext()) {
19477                PreferredActivity pa = it.next();
19478                // Mark entry for removal only if it matches the package name
19479                // and the entry is of type "always".
19480                if (packageName == null ||
19481                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19482                                && pa.mPref.mAlways)) {
19483                    if (removed == null) {
19484                        removed = new ArrayList<PreferredActivity>();
19485                    }
19486                    removed.add(pa);
19487                }
19488            }
19489            if (removed != null) {
19490                for (int j=0; j<removed.size(); j++) {
19491                    PreferredActivity pa = removed.get(j);
19492                    pir.removeFilter(pa);
19493                }
19494                changed = true;
19495            }
19496        }
19497        if (changed) {
19498            postPreferredActivityChangedBroadcast(userId);
19499        }
19500        return changed;
19501    }
19502
19503    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19504    private void clearIntentFilterVerificationsLPw(int userId) {
19505        final int packageCount = mPackages.size();
19506        for (int i = 0; i < packageCount; i++) {
19507            PackageParser.Package pkg = mPackages.valueAt(i);
19508            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19509        }
19510    }
19511
19512    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19513    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19514        if (userId == UserHandle.USER_ALL) {
19515            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19516                    sUserManager.getUserIds())) {
19517                for (int oneUserId : sUserManager.getUserIds()) {
19518                    scheduleWritePackageRestrictionsLocked(oneUserId);
19519                }
19520            }
19521        } else {
19522            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19523                scheduleWritePackageRestrictionsLocked(userId);
19524            }
19525        }
19526    }
19527
19528    /** Clears state for all users, and touches intent filter verification policy */
19529    void clearDefaultBrowserIfNeeded(String packageName) {
19530        for (int oneUserId : sUserManager.getUserIds()) {
19531            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19532        }
19533    }
19534
19535    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19536        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19537        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19538            if (packageName.equals(defaultBrowserPackageName)) {
19539                setDefaultBrowserPackageName(null, userId);
19540            }
19541        }
19542    }
19543
19544    @Override
19545    public void resetApplicationPreferences(int userId) {
19546        mContext.enforceCallingOrSelfPermission(
19547                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19548        final long identity = Binder.clearCallingIdentity();
19549        // writer
19550        try {
19551            synchronized (mPackages) {
19552                clearPackagePreferredActivitiesLPw(null, userId);
19553                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19554                // TODO: We have to reset the default SMS and Phone. This requires
19555                // significant refactoring to keep all default apps in the package
19556                // manager (cleaner but more work) or have the services provide
19557                // callbacks to the package manager to request a default app reset.
19558                applyFactoryDefaultBrowserLPw(userId);
19559                clearIntentFilterVerificationsLPw(userId);
19560                primeDomainVerificationsLPw(userId);
19561                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19562                scheduleWritePackageRestrictionsLocked(userId);
19563            }
19564            resetNetworkPolicies(userId);
19565        } finally {
19566            Binder.restoreCallingIdentity(identity);
19567        }
19568    }
19569
19570    @Override
19571    public int getPreferredActivities(List<IntentFilter> outFilters,
19572            List<ComponentName> outActivities, String packageName) {
19573
19574        int num = 0;
19575        final int userId = UserHandle.getCallingUserId();
19576        // reader
19577        synchronized (mPackages) {
19578            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19579            if (pir != null) {
19580                final Iterator<PreferredActivity> it = pir.filterIterator();
19581                while (it.hasNext()) {
19582                    final PreferredActivity pa = it.next();
19583                    if (packageName == null
19584                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19585                                    && pa.mPref.mAlways)) {
19586                        if (outFilters != null) {
19587                            outFilters.add(new IntentFilter(pa));
19588                        }
19589                        if (outActivities != null) {
19590                            outActivities.add(pa.mPref.mComponent);
19591                        }
19592                    }
19593                }
19594            }
19595        }
19596
19597        return num;
19598    }
19599
19600    @Override
19601    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19602            int userId) {
19603        int callingUid = Binder.getCallingUid();
19604        if (callingUid != Process.SYSTEM_UID) {
19605            throw new SecurityException(
19606                    "addPersistentPreferredActivity can only be run by the system");
19607        }
19608        if (filter.countActions() == 0) {
19609            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19610            return;
19611        }
19612        synchronized (mPackages) {
19613            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19614                    ":");
19615            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19616            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19617                    new PersistentPreferredActivity(filter, activity));
19618            scheduleWritePackageRestrictionsLocked(userId);
19619            postPreferredActivityChangedBroadcast(userId);
19620        }
19621    }
19622
19623    @Override
19624    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19625        int callingUid = Binder.getCallingUid();
19626        if (callingUid != Process.SYSTEM_UID) {
19627            throw new SecurityException(
19628                    "clearPackagePersistentPreferredActivities can only be run by the system");
19629        }
19630        ArrayList<PersistentPreferredActivity> removed = null;
19631        boolean changed = false;
19632        synchronized (mPackages) {
19633            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19634                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19635                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19636                        .valueAt(i);
19637                if (userId != thisUserId) {
19638                    continue;
19639                }
19640                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19641                while (it.hasNext()) {
19642                    PersistentPreferredActivity ppa = it.next();
19643                    // Mark entry for removal only if it matches the package name.
19644                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19645                        if (removed == null) {
19646                            removed = new ArrayList<PersistentPreferredActivity>();
19647                        }
19648                        removed.add(ppa);
19649                    }
19650                }
19651                if (removed != null) {
19652                    for (int j=0; j<removed.size(); j++) {
19653                        PersistentPreferredActivity ppa = removed.get(j);
19654                        ppir.removeFilter(ppa);
19655                    }
19656                    changed = true;
19657                }
19658            }
19659
19660            if (changed) {
19661                scheduleWritePackageRestrictionsLocked(userId);
19662                postPreferredActivityChangedBroadcast(userId);
19663            }
19664        }
19665    }
19666
19667    /**
19668     * Common machinery for picking apart a restored XML blob and passing
19669     * it to a caller-supplied functor to be applied to the running system.
19670     */
19671    private void restoreFromXml(XmlPullParser parser, int userId,
19672            String expectedStartTag, BlobXmlRestorer functor)
19673            throws IOException, XmlPullParserException {
19674        int type;
19675        while ((type = parser.next()) != XmlPullParser.START_TAG
19676                && type != XmlPullParser.END_DOCUMENT) {
19677        }
19678        if (type != XmlPullParser.START_TAG) {
19679            // oops didn't find a start tag?!
19680            if (DEBUG_BACKUP) {
19681                Slog.e(TAG, "Didn't find start tag during restore");
19682            }
19683            return;
19684        }
19685Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19686        // this is supposed to be TAG_PREFERRED_BACKUP
19687        if (!expectedStartTag.equals(parser.getName())) {
19688            if (DEBUG_BACKUP) {
19689                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19690            }
19691            return;
19692        }
19693
19694        // skip interfering stuff, then we're aligned with the backing implementation
19695        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19696Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19697        functor.apply(parser, userId);
19698    }
19699
19700    private interface BlobXmlRestorer {
19701        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19702    }
19703
19704    /**
19705     * Non-Binder method, support for the backup/restore mechanism: write the
19706     * full set of preferred activities in its canonical XML format.  Returns the
19707     * XML output as a byte array, or null if there is none.
19708     */
19709    @Override
19710    public byte[] getPreferredActivityBackup(int userId) {
19711        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19712            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19713        }
19714
19715        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19716        try {
19717            final XmlSerializer serializer = new FastXmlSerializer();
19718            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19719            serializer.startDocument(null, true);
19720            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19721
19722            synchronized (mPackages) {
19723                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19724            }
19725
19726            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19727            serializer.endDocument();
19728            serializer.flush();
19729        } catch (Exception e) {
19730            if (DEBUG_BACKUP) {
19731                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19732            }
19733            return null;
19734        }
19735
19736        return dataStream.toByteArray();
19737    }
19738
19739    @Override
19740    public void restorePreferredActivities(byte[] backup, int userId) {
19741        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19742            throw new SecurityException("Only the system may call restorePreferredActivities()");
19743        }
19744
19745        try {
19746            final XmlPullParser parser = Xml.newPullParser();
19747            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19748            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19749                    new BlobXmlRestorer() {
19750                        @Override
19751                        public void apply(XmlPullParser parser, int userId)
19752                                throws XmlPullParserException, IOException {
19753                            synchronized (mPackages) {
19754                                mSettings.readPreferredActivitiesLPw(parser, userId);
19755                            }
19756                        }
19757                    } );
19758        } catch (Exception e) {
19759            if (DEBUG_BACKUP) {
19760                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19761            }
19762        }
19763    }
19764
19765    /**
19766     * Non-Binder method, support for the backup/restore mechanism: write the
19767     * default browser (etc) settings in its canonical XML format.  Returns the default
19768     * browser XML representation as a byte array, or null if there is none.
19769     */
19770    @Override
19771    public byte[] getDefaultAppsBackup(int userId) {
19772        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19773            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19774        }
19775
19776        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19777        try {
19778            final XmlSerializer serializer = new FastXmlSerializer();
19779            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19780            serializer.startDocument(null, true);
19781            serializer.startTag(null, TAG_DEFAULT_APPS);
19782
19783            synchronized (mPackages) {
19784                mSettings.writeDefaultAppsLPr(serializer, userId);
19785            }
19786
19787            serializer.endTag(null, TAG_DEFAULT_APPS);
19788            serializer.endDocument();
19789            serializer.flush();
19790        } catch (Exception e) {
19791            if (DEBUG_BACKUP) {
19792                Slog.e(TAG, "Unable to write default apps for backup", e);
19793            }
19794            return null;
19795        }
19796
19797        return dataStream.toByteArray();
19798    }
19799
19800    @Override
19801    public void restoreDefaultApps(byte[] backup, int userId) {
19802        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19803            throw new SecurityException("Only the system may call restoreDefaultApps()");
19804        }
19805
19806        try {
19807            final XmlPullParser parser = Xml.newPullParser();
19808            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19809            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19810                    new BlobXmlRestorer() {
19811                        @Override
19812                        public void apply(XmlPullParser parser, int userId)
19813                                throws XmlPullParserException, IOException {
19814                            synchronized (mPackages) {
19815                                mSettings.readDefaultAppsLPw(parser, userId);
19816                            }
19817                        }
19818                    } );
19819        } catch (Exception e) {
19820            if (DEBUG_BACKUP) {
19821                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19822            }
19823        }
19824    }
19825
19826    @Override
19827    public byte[] getIntentFilterVerificationBackup(int userId) {
19828        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19829            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19830        }
19831
19832        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19833        try {
19834            final XmlSerializer serializer = new FastXmlSerializer();
19835            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19836            serializer.startDocument(null, true);
19837            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19838
19839            synchronized (mPackages) {
19840                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19841            }
19842
19843            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19844            serializer.endDocument();
19845            serializer.flush();
19846        } catch (Exception e) {
19847            if (DEBUG_BACKUP) {
19848                Slog.e(TAG, "Unable to write default apps for backup", e);
19849            }
19850            return null;
19851        }
19852
19853        return dataStream.toByteArray();
19854    }
19855
19856    @Override
19857    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19858        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19859            throw new SecurityException("Only the system may call restorePreferredActivities()");
19860        }
19861
19862        try {
19863            final XmlPullParser parser = Xml.newPullParser();
19864            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19865            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19866                    new BlobXmlRestorer() {
19867                        @Override
19868                        public void apply(XmlPullParser parser, int userId)
19869                                throws XmlPullParserException, IOException {
19870                            synchronized (mPackages) {
19871                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19872                                mSettings.writeLPr();
19873                            }
19874                        }
19875                    } );
19876        } catch (Exception e) {
19877            if (DEBUG_BACKUP) {
19878                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19879            }
19880        }
19881    }
19882
19883    @Override
19884    public byte[] getPermissionGrantBackup(int userId) {
19885        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19886            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19887        }
19888
19889        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19890        try {
19891            final XmlSerializer serializer = new FastXmlSerializer();
19892            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19893            serializer.startDocument(null, true);
19894            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19895
19896            synchronized (mPackages) {
19897                serializeRuntimePermissionGrantsLPr(serializer, userId);
19898            }
19899
19900            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19901            serializer.endDocument();
19902            serializer.flush();
19903        } catch (Exception e) {
19904            if (DEBUG_BACKUP) {
19905                Slog.e(TAG, "Unable to write default apps for backup", e);
19906            }
19907            return null;
19908        }
19909
19910        return dataStream.toByteArray();
19911    }
19912
19913    @Override
19914    public void restorePermissionGrants(byte[] backup, int userId) {
19915        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19916            throw new SecurityException("Only the system may call restorePermissionGrants()");
19917        }
19918
19919        try {
19920            final XmlPullParser parser = Xml.newPullParser();
19921            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19922            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19923                    new BlobXmlRestorer() {
19924                        @Override
19925                        public void apply(XmlPullParser parser, int userId)
19926                                throws XmlPullParserException, IOException {
19927                            synchronized (mPackages) {
19928                                processRestoredPermissionGrantsLPr(parser, userId);
19929                            }
19930                        }
19931                    } );
19932        } catch (Exception e) {
19933            if (DEBUG_BACKUP) {
19934                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19935            }
19936        }
19937    }
19938
19939    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19940            throws IOException {
19941        serializer.startTag(null, TAG_ALL_GRANTS);
19942
19943        final int N = mSettings.mPackages.size();
19944        for (int i = 0; i < N; i++) {
19945            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19946            boolean pkgGrantsKnown = false;
19947
19948            PermissionsState packagePerms = ps.getPermissionsState();
19949
19950            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19951                final int grantFlags = state.getFlags();
19952                // only look at grants that are not system/policy fixed
19953                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19954                    final boolean isGranted = state.isGranted();
19955                    // And only back up the user-twiddled state bits
19956                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19957                        final String packageName = mSettings.mPackages.keyAt(i);
19958                        if (!pkgGrantsKnown) {
19959                            serializer.startTag(null, TAG_GRANT);
19960                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19961                            pkgGrantsKnown = true;
19962                        }
19963
19964                        final boolean userSet =
19965                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19966                        final boolean userFixed =
19967                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19968                        final boolean revoke =
19969                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19970
19971                        serializer.startTag(null, TAG_PERMISSION);
19972                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19973                        if (isGranted) {
19974                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19975                        }
19976                        if (userSet) {
19977                            serializer.attribute(null, ATTR_USER_SET, "true");
19978                        }
19979                        if (userFixed) {
19980                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19981                        }
19982                        if (revoke) {
19983                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19984                        }
19985                        serializer.endTag(null, TAG_PERMISSION);
19986                    }
19987                }
19988            }
19989
19990            if (pkgGrantsKnown) {
19991                serializer.endTag(null, TAG_GRANT);
19992            }
19993        }
19994
19995        serializer.endTag(null, TAG_ALL_GRANTS);
19996    }
19997
19998    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19999            throws XmlPullParserException, IOException {
20000        String pkgName = null;
20001        int outerDepth = parser.getDepth();
20002        int type;
20003        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20004                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20005            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20006                continue;
20007            }
20008
20009            final String tagName = parser.getName();
20010            if (tagName.equals(TAG_GRANT)) {
20011                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20012                if (DEBUG_BACKUP) {
20013                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20014                }
20015            } else if (tagName.equals(TAG_PERMISSION)) {
20016
20017                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20018                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20019
20020                int newFlagSet = 0;
20021                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20022                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20023                }
20024                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20025                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20026                }
20027                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20028                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20029                }
20030                if (DEBUG_BACKUP) {
20031                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20032                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20033                }
20034                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20035                if (ps != null) {
20036                    // Already installed so we apply the grant immediately
20037                    if (DEBUG_BACKUP) {
20038                        Slog.v(TAG, "        + already installed; applying");
20039                    }
20040                    PermissionsState perms = ps.getPermissionsState();
20041                    BasePermission bp = mSettings.mPermissions.get(permName);
20042                    if (bp != null) {
20043                        if (isGranted) {
20044                            perms.grantRuntimePermission(bp, userId);
20045                        }
20046                        if (newFlagSet != 0) {
20047                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20048                        }
20049                    }
20050                } else {
20051                    // Need to wait for post-restore install to apply the grant
20052                    if (DEBUG_BACKUP) {
20053                        Slog.v(TAG, "        - not yet installed; saving for later");
20054                    }
20055                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20056                            isGranted, newFlagSet, userId);
20057                }
20058            } else {
20059                PackageManagerService.reportSettingsProblem(Log.WARN,
20060                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20061                XmlUtils.skipCurrentTag(parser);
20062            }
20063        }
20064
20065        scheduleWriteSettingsLocked();
20066        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20067    }
20068
20069    @Override
20070    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20071            int sourceUserId, int targetUserId, int flags) {
20072        mContext.enforceCallingOrSelfPermission(
20073                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20074        int callingUid = Binder.getCallingUid();
20075        enforceOwnerRights(ownerPackage, callingUid);
20076        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20077        if (intentFilter.countActions() == 0) {
20078            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20079            return;
20080        }
20081        synchronized (mPackages) {
20082            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20083                    ownerPackage, targetUserId, flags);
20084            CrossProfileIntentResolver resolver =
20085                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20086            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20087            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20088            if (existing != null) {
20089                int size = existing.size();
20090                for (int i = 0; i < size; i++) {
20091                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20092                        return;
20093                    }
20094                }
20095            }
20096            resolver.addFilter(newFilter);
20097            scheduleWritePackageRestrictionsLocked(sourceUserId);
20098        }
20099    }
20100
20101    @Override
20102    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20103        mContext.enforceCallingOrSelfPermission(
20104                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20105        int callingUid = Binder.getCallingUid();
20106        enforceOwnerRights(ownerPackage, callingUid);
20107        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20108        synchronized (mPackages) {
20109            CrossProfileIntentResolver resolver =
20110                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20111            ArraySet<CrossProfileIntentFilter> set =
20112                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20113            for (CrossProfileIntentFilter filter : set) {
20114                if (filter.getOwnerPackage().equals(ownerPackage)) {
20115                    resolver.removeFilter(filter);
20116                }
20117            }
20118            scheduleWritePackageRestrictionsLocked(sourceUserId);
20119        }
20120    }
20121
20122    // Enforcing that callingUid is owning pkg on userId
20123    private void enforceOwnerRights(String pkg, int callingUid) {
20124        // The system owns everything.
20125        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20126            return;
20127        }
20128        int callingUserId = UserHandle.getUserId(callingUid);
20129        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20130        if (pi == null) {
20131            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20132                    + callingUserId);
20133        }
20134        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20135            throw new SecurityException("Calling uid " + callingUid
20136                    + " does not own package " + pkg);
20137        }
20138    }
20139
20140    @Override
20141    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20142        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20143    }
20144
20145    /**
20146     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20147     * then reports the most likely home activity or null if there are more than one.
20148     */
20149    public ComponentName getDefaultHomeActivity(int userId) {
20150        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20151        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20152        if (cn != null) {
20153            return cn;
20154        }
20155
20156        // Find the launcher with the highest priority and return that component if there are no
20157        // other home activity with the same priority.
20158        int lastPriority = Integer.MIN_VALUE;
20159        ComponentName lastComponent = null;
20160        final int size = allHomeCandidates.size();
20161        for (int i = 0; i < size; i++) {
20162            final ResolveInfo ri = allHomeCandidates.get(i);
20163            if (ri.priority > lastPriority) {
20164                lastComponent = ri.activityInfo.getComponentName();
20165                lastPriority = ri.priority;
20166            } else if (ri.priority == lastPriority) {
20167                // Two components found with same priority.
20168                lastComponent = null;
20169            }
20170        }
20171        return lastComponent;
20172    }
20173
20174    private Intent getHomeIntent() {
20175        Intent intent = new Intent(Intent.ACTION_MAIN);
20176        intent.addCategory(Intent.CATEGORY_HOME);
20177        intent.addCategory(Intent.CATEGORY_DEFAULT);
20178        return intent;
20179    }
20180
20181    private IntentFilter getHomeFilter() {
20182        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20183        filter.addCategory(Intent.CATEGORY_HOME);
20184        filter.addCategory(Intent.CATEGORY_DEFAULT);
20185        return filter;
20186    }
20187
20188    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20189            int userId) {
20190        Intent intent  = getHomeIntent();
20191        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20192                PackageManager.GET_META_DATA, userId);
20193        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20194                true, false, false, userId);
20195
20196        allHomeCandidates.clear();
20197        if (list != null) {
20198            for (ResolveInfo ri : list) {
20199                allHomeCandidates.add(ri);
20200            }
20201        }
20202        return (preferred == null || preferred.activityInfo == null)
20203                ? null
20204                : new ComponentName(preferred.activityInfo.packageName,
20205                        preferred.activityInfo.name);
20206    }
20207
20208    @Override
20209    public void setHomeActivity(ComponentName comp, int userId) {
20210        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20211        getHomeActivitiesAsUser(homeActivities, userId);
20212
20213        boolean found = false;
20214
20215        final int size = homeActivities.size();
20216        final ComponentName[] set = new ComponentName[size];
20217        for (int i = 0; i < size; i++) {
20218            final ResolveInfo candidate = homeActivities.get(i);
20219            final ActivityInfo info = candidate.activityInfo;
20220            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20221            set[i] = activityName;
20222            if (!found && activityName.equals(comp)) {
20223                found = true;
20224            }
20225        }
20226        if (!found) {
20227            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20228                    + userId);
20229        }
20230        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20231                set, comp, userId);
20232    }
20233
20234    private @Nullable String getSetupWizardPackageName() {
20235        final Intent intent = new Intent(Intent.ACTION_MAIN);
20236        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20237
20238        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20239                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20240                        | MATCH_DISABLED_COMPONENTS,
20241                UserHandle.myUserId());
20242        if (matches.size() == 1) {
20243            return matches.get(0).getComponentInfo().packageName;
20244        } else {
20245            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20246                    + ": matches=" + matches);
20247            return null;
20248        }
20249    }
20250
20251    private @Nullable String getStorageManagerPackageName() {
20252        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20253
20254        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20255                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20256                        | MATCH_DISABLED_COMPONENTS,
20257                UserHandle.myUserId());
20258        if (matches.size() == 1) {
20259            return matches.get(0).getComponentInfo().packageName;
20260        } else {
20261            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20262                    + matches.size() + ": matches=" + matches);
20263            return null;
20264        }
20265    }
20266
20267    @Override
20268    public void setApplicationEnabledSetting(String appPackageName,
20269            int newState, int flags, int userId, String callingPackage) {
20270        if (!sUserManager.exists(userId)) return;
20271        if (callingPackage == null) {
20272            callingPackage = Integer.toString(Binder.getCallingUid());
20273        }
20274        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20275    }
20276
20277    @Override
20278    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20279        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20280        synchronized (mPackages) {
20281            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20282            if (pkgSetting != null) {
20283                pkgSetting.setUpdateAvailable(updateAvailable);
20284            }
20285        }
20286    }
20287
20288    @Override
20289    public void setComponentEnabledSetting(ComponentName componentName,
20290            int newState, int flags, int userId) {
20291        if (!sUserManager.exists(userId)) return;
20292        setEnabledSetting(componentName.getPackageName(),
20293                componentName.getClassName(), newState, flags, userId, null);
20294    }
20295
20296    private void setEnabledSetting(final String packageName, String className, int newState,
20297            final int flags, int userId, String callingPackage) {
20298        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20299              || newState == COMPONENT_ENABLED_STATE_ENABLED
20300              || newState == COMPONENT_ENABLED_STATE_DISABLED
20301              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20302              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20303            throw new IllegalArgumentException("Invalid new component state: "
20304                    + newState);
20305        }
20306        PackageSetting pkgSetting;
20307        final int uid = Binder.getCallingUid();
20308        final int permission;
20309        if (uid == Process.SYSTEM_UID) {
20310            permission = PackageManager.PERMISSION_GRANTED;
20311        } else {
20312            permission = mContext.checkCallingOrSelfPermission(
20313                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20314        }
20315        enforceCrossUserPermission(uid, userId,
20316                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20317        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20318        boolean sendNow = false;
20319        boolean isApp = (className == null);
20320        String componentName = isApp ? packageName : className;
20321        int packageUid = -1;
20322        ArrayList<String> components;
20323
20324        // writer
20325        synchronized (mPackages) {
20326            pkgSetting = mSettings.mPackages.get(packageName);
20327            if (pkgSetting == null) {
20328                if (className == null) {
20329                    throw new IllegalArgumentException("Unknown package: " + packageName);
20330                }
20331                throw new IllegalArgumentException(
20332                        "Unknown component: " + packageName + "/" + className);
20333            }
20334        }
20335
20336        // Limit who can change which apps
20337        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20338            // Don't allow apps that don't have permission to modify other apps
20339            if (!allowedByPermission) {
20340                throw new SecurityException(
20341                        "Permission Denial: attempt to change component state from pid="
20342                        + Binder.getCallingPid()
20343                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20344            }
20345            // Don't allow changing protected packages.
20346            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20347                throw new SecurityException("Cannot disable a protected package: " + packageName);
20348            }
20349        }
20350
20351        synchronized (mPackages) {
20352            if (uid == Process.SHELL_UID
20353                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20354                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20355                // unless it is a test package.
20356                int oldState = pkgSetting.getEnabled(userId);
20357                if (className == null
20358                    &&
20359                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20360                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20361                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20362                    &&
20363                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20364                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20365                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20366                    // ok
20367                } else {
20368                    throw new SecurityException(
20369                            "Shell cannot change component state for " + packageName + "/"
20370                            + className + " to " + newState);
20371                }
20372            }
20373            if (className == null) {
20374                // We're dealing with an application/package level state change
20375                if (pkgSetting.getEnabled(userId) == newState) {
20376                    // Nothing to do
20377                    return;
20378                }
20379                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20380                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20381                    // Don't care about who enables an app.
20382                    callingPackage = null;
20383                }
20384                pkgSetting.setEnabled(newState, userId, callingPackage);
20385                // pkgSetting.pkg.mSetEnabled = newState;
20386            } else {
20387                // We're dealing with a component level state change
20388                // First, verify that this is a valid class name.
20389                PackageParser.Package pkg = pkgSetting.pkg;
20390                if (pkg == null || !pkg.hasComponentClassName(className)) {
20391                    if (pkg != null &&
20392                            pkg.applicationInfo.targetSdkVersion >=
20393                                    Build.VERSION_CODES.JELLY_BEAN) {
20394                        throw new IllegalArgumentException("Component class " + className
20395                                + " does not exist in " + packageName);
20396                    } else {
20397                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20398                                + className + " does not exist in " + packageName);
20399                    }
20400                }
20401                switch (newState) {
20402                case COMPONENT_ENABLED_STATE_ENABLED:
20403                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20404                        return;
20405                    }
20406                    break;
20407                case COMPONENT_ENABLED_STATE_DISABLED:
20408                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20409                        return;
20410                    }
20411                    break;
20412                case COMPONENT_ENABLED_STATE_DEFAULT:
20413                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20414                        return;
20415                    }
20416                    break;
20417                default:
20418                    Slog.e(TAG, "Invalid new component state: " + newState);
20419                    return;
20420                }
20421            }
20422            scheduleWritePackageRestrictionsLocked(userId);
20423            updateSequenceNumberLP(packageName, new int[] { userId });
20424            final long callingId = Binder.clearCallingIdentity();
20425            try {
20426                updateInstantAppInstallerLocked(packageName);
20427            } finally {
20428                Binder.restoreCallingIdentity(callingId);
20429            }
20430            components = mPendingBroadcasts.get(userId, packageName);
20431            final boolean newPackage = components == null;
20432            if (newPackage) {
20433                components = new ArrayList<String>();
20434            }
20435            if (!components.contains(componentName)) {
20436                components.add(componentName);
20437            }
20438            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20439                sendNow = true;
20440                // Purge entry from pending broadcast list if another one exists already
20441                // since we are sending one right away.
20442                mPendingBroadcasts.remove(userId, packageName);
20443            } else {
20444                if (newPackage) {
20445                    mPendingBroadcasts.put(userId, packageName, components);
20446                }
20447                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20448                    // Schedule a message
20449                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20450                }
20451            }
20452        }
20453
20454        long callingId = Binder.clearCallingIdentity();
20455        try {
20456            if (sendNow) {
20457                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20458                sendPackageChangedBroadcast(packageName,
20459                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20460            }
20461        } finally {
20462            Binder.restoreCallingIdentity(callingId);
20463        }
20464    }
20465
20466    @Override
20467    public void flushPackageRestrictionsAsUser(int userId) {
20468        if (!sUserManager.exists(userId)) {
20469            return;
20470        }
20471        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20472                false /* checkShell */, "flushPackageRestrictions");
20473        synchronized (mPackages) {
20474            mSettings.writePackageRestrictionsLPr(userId);
20475            mDirtyUsers.remove(userId);
20476            if (mDirtyUsers.isEmpty()) {
20477                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20478            }
20479        }
20480    }
20481
20482    private void sendPackageChangedBroadcast(String packageName,
20483            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20484        if (DEBUG_INSTALL)
20485            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20486                    + componentNames);
20487        Bundle extras = new Bundle(4);
20488        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20489        String nameList[] = new String[componentNames.size()];
20490        componentNames.toArray(nameList);
20491        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20492        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20493        extras.putInt(Intent.EXTRA_UID, packageUid);
20494        // If this is not reporting a change of the overall package, then only send it
20495        // to registered receivers.  We don't want to launch a swath of apps for every
20496        // little component state change.
20497        final int flags = !componentNames.contains(packageName)
20498                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20499        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20500                new int[] {UserHandle.getUserId(packageUid)});
20501    }
20502
20503    @Override
20504    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20505        if (!sUserManager.exists(userId)) return;
20506        final int uid = Binder.getCallingUid();
20507        final int permission = mContext.checkCallingOrSelfPermission(
20508                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20509        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20510        enforceCrossUserPermission(uid, userId,
20511                true /* requireFullPermission */, true /* checkShell */, "stop package");
20512        // writer
20513        synchronized (mPackages) {
20514            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20515                    allowedByPermission, uid, userId)) {
20516                scheduleWritePackageRestrictionsLocked(userId);
20517            }
20518        }
20519    }
20520
20521    @Override
20522    public String getInstallerPackageName(String packageName) {
20523        // reader
20524        synchronized (mPackages) {
20525            return mSettings.getInstallerPackageNameLPr(packageName);
20526        }
20527    }
20528
20529    public boolean isOrphaned(String packageName) {
20530        // reader
20531        synchronized (mPackages) {
20532            return mSettings.isOrphaned(packageName);
20533        }
20534    }
20535
20536    @Override
20537    public int getApplicationEnabledSetting(String packageName, int userId) {
20538        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20539        int uid = Binder.getCallingUid();
20540        enforceCrossUserPermission(uid, userId,
20541                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20542        // reader
20543        synchronized (mPackages) {
20544            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20545        }
20546    }
20547
20548    @Override
20549    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20550        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20551        int uid = Binder.getCallingUid();
20552        enforceCrossUserPermission(uid, userId,
20553                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20554        // reader
20555        synchronized (mPackages) {
20556            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20557        }
20558    }
20559
20560    @Override
20561    public void enterSafeMode() {
20562        enforceSystemOrRoot("Only the system can request entering safe mode");
20563
20564        if (!mSystemReady) {
20565            mSafeMode = true;
20566        }
20567    }
20568
20569    @Override
20570    public void systemReady() {
20571        mSystemReady = true;
20572        final ContentResolver resolver = mContext.getContentResolver();
20573        ContentObserver co = new ContentObserver(mHandler) {
20574            @Override
20575            public void onChange(boolean selfChange) {
20576                mEphemeralAppsDisabled =
20577                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20578                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20579            }
20580        };
20581        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20582                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20583                false, co, UserHandle.USER_SYSTEM);
20584        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20585                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20586        co.onChange(true);
20587
20588        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20589        // disabled after already being started.
20590        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20591                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20592
20593        // Read the compatibilty setting when the system is ready.
20594        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20595                mContext.getContentResolver(),
20596                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20597        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20598        if (DEBUG_SETTINGS) {
20599            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20600        }
20601
20602        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20603
20604        synchronized (mPackages) {
20605            // Verify that all of the preferred activity components actually
20606            // exist.  It is possible for applications to be updated and at
20607            // that point remove a previously declared activity component that
20608            // had been set as a preferred activity.  We try to clean this up
20609            // the next time we encounter that preferred activity, but it is
20610            // possible for the user flow to never be able to return to that
20611            // situation so here we do a sanity check to make sure we haven't
20612            // left any junk around.
20613            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20614            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20615                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20616                removed.clear();
20617                for (PreferredActivity pa : pir.filterSet()) {
20618                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20619                        removed.add(pa);
20620                    }
20621                }
20622                if (removed.size() > 0) {
20623                    for (int r=0; r<removed.size(); r++) {
20624                        PreferredActivity pa = removed.get(r);
20625                        Slog.w(TAG, "Removing dangling preferred activity: "
20626                                + pa.mPref.mComponent);
20627                        pir.removeFilter(pa);
20628                    }
20629                    mSettings.writePackageRestrictionsLPr(
20630                            mSettings.mPreferredActivities.keyAt(i));
20631                }
20632            }
20633
20634            for (int userId : UserManagerService.getInstance().getUserIds()) {
20635                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20636                    grantPermissionsUserIds = ArrayUtils.appendInt(
20637                            grantPermissionsUserIds, userId);
20638                }
20639            }
20640        }
20641        sUserManager.systemReady();
20642
20643        // If we upgraded grant all default permissions before kicking off.
20644        for (int userId : grantPermissionsUserIds) {
20645            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20646        }
20647
20648        // If we did not grant default permissions, we preload from this the
20649        // default permission exceptions lazily to ensure we don't hit the
20650        // disk on a new user creation.
20651        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20652            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20653        }
20654
20655        // Kick off any messages waiting for system ready
20656        if (mPostSystemReadyMessages != null) {
20657            for (Message msg : mPostSystemReadyMessages) {
20658                msg.sendToTarget();
20659            }
20660            mPostSystemReadyMessages = null;
20661        }
20662
20663        // Watch for external volumes that come and go over time
20664        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20665        storage.registerListener(mStorageListener);
20666
20667        mInstallerService.systemReady();
20668        mPackageDexOptimizer.systemReady();
20669
20670        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20671                StorageManagerInternal.class);
20672        StorageManagerInternal.addExternalStoragePolicy(
20673                new StorageManagerInternal.ExternalStorageMountPolicy() {
20674            @Override
20675            public int getMountMode(int uid, String packageName) {
20676                if (Process.isIsolated(uid)) {
20677                    return Zygote.MOUNT_EXTERNAL_NONE;
20678                }
20679                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20680                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20681                }
20682                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20683                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20684                }
20685                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20686                    return Zygote.MOUNT_EXTERNAL_READ;
20687                }
20688                return Zygote.MOUNT_EXTERNAL_WRITE;
20689            }
20690
20691            @Override
20692            public boolean hasExternalStorage(int uid, String packageName) {
20693                return true;
20694            }
20695        });
20696
20697        // Now that we're mostly running, clean up stale users and apps
20698        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20699        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20700
20701        if (mPrivappPermissionsViolations != null) {
20702            Slog.wtf(TAG,"Signature|privileged permissions not in "
20703                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20704            mPrivappPermissionsViolations = null;
20705        }
20706    }
20707
20708    public void waitForAppDataPrepared() {
20709        if (mPrepareAppDataFuture == null) {
20710            return;
20711        }
20712        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20713        mPrepareAppDataFuture = null;
20714    }
20715
20716    @Override
20717    public boolean isSafeMode() {
20718        return mSafeMode;
20719    }
20720
20721    @Override
20722    public boolean hasSystemUidErrors() {
20723        return mHasSystemUidErrors;
20724    }
20725
20726    static String arrayToString(int[] array) {
20727        StringBuffer buf = new StringBuffer(128);
20728        buf.append('[');
20729        if (array != null) {
20730            for (int i=0; i<array.length; i++) {
20731                if (i > 0) buf.append(", ");
20732                buf.append(array[i]);
20733            }
20734        }
20735        buf.append(']');
20736        return buf.toString();
20737    }
20738
20739    static class DumpState {
20740        public static final int DUMP_LIBS = 1 << 0;
20741        public static final int DUMP_FEATURES = 1 << 1;
20742        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20743        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20744        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20745        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20746        public static final int DUMP_PERMISSIONS = 1 << 6;
20747        public static final int DUMP_PACKAGES = 1 << 7;
20748        public static final int DUMP_SHARED_USERS = 1 << 8;
20749        public static final int DUMP_MESSAGES = 1 << 9;
20750        public static final int DUMP_PROVIDERS = 1 << 10;
20751        public static final int DUMP_VERIFIERS = 1 << 11;
20752        public static final int DUMP_PREFERRED = 1 << 12;
20753        public static final int DUMP_PREFERRED_XML = 1 << 13;
20754        public static final int DUMP_KEYSETS = 1 << 14;
20755        public static final int DUMP_VERSION = 1 << 15;
20756        public static final int DUMP_INSTALLS = 1 << 16;
20757        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20758        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20759        public static final int DUMP_FROZEN = 1 << 19;
20760        public static final int DUMP_DEXOPT = 1 << 20;
20761        public static final int DUMP_COMPILER_STATS = 1 << 21;
20762        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20763        public static final int DUMP_CHANGES = 1 << 23;
20764
20765        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20766
20767        private int mTypes;
20768
20769        private int mOptions;
20770
20771        private boolean mTitlePrinted;
20772
20773        private SharedUserSetting mSharedUser;
20774
20775        public boolean isDumping(int type) {
20776            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20777                return true;
20778            }
20779
20780            return (mTypes & type) != 0;
20781        }
20782
20783        public void setDump(int type) {
20784            mTypes |= type;
20785        }
20786
20787        public boolean isOptionEnabled(int option) {
20788            return (mOptions & option) != 0;
20789        }
20790
20791        public void setOptionEnabled(int option) {
20792            mOptions |= option;
20793        }
20794
20795        public boolean onTitlePrinted() {
20796            final boolean printed = mTitlePrinted;
20797            mTitlePrinted = true;
20798            return printed;
20799        }
20800
20801        public boolean getTitlePrinted() {
20802            return mTitlePrinted;
20803        }
20804
20805        public void setTitlePrinted(boolean enabled) {
20806            mTitlePrinted = enabled;
20807        }
20808
20809        public SharedUserSetting getSharedUser() {
20810            return mSharedUser;
20811        }
20812
20813        public void setSharedUser(SharedUserSetting user) {
20814            mSharedUser = user;
20815        }
20816    }
20817
20818    @Override
20819    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20820            FileDescriptor err, String[] args, ShellCallback callback,
20821            ResultReceiver resultReceiver) {
20822        (new PackageManagerShellCommand(this)).exec(
20823                this, in, out, err, args, callback, resultReceiver);
20824    }
20825
20826    @Override
20827    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20828        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20829
20830        DumpState dumpState = new DumpState();
20831        boolean fullPreferred = false;
20832        boolean checkin = false;
20833
20834        String packageName = null;
20835        ArraySet<String> permissionNames = null;
20836
20837        int opti = 0;
20838        while (opti < args.length) {
20839            String opt = args[opti];
20840            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20841                break;
20842            }
20843            opti++;
20844
20845            if ("-a".equals(opt)) {
20846                // Right now we only know how to print all.
20847            } else if ("-h".equals(opt)) {
20848                pw.println("Package manager dump options:");
20849                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20850                pw.println("    --checkin: dump for a checkin");
20851                pw.println("    -f: print details of intent filters");
20852                pw.println("    -h: print this help");
20853                pw.println("  cmd may be one of:");
20854                pw.println("    l[ibraries]: list known shared libraries");
20855                pw.println("    f[eatures]: list device features");
20856                pw.println("    k[eysets]: print known keysets");
20857                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20858                pw.println("    perm[issions]: dump permissions");
20859                pw.println("    permission [name ...]: dump declaration and use of given permission");
20860                pw.println("    pref[erred]: print preferred package settings");
20861                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20862                pw.println("    prov[iders]: dump content providers");
20863                pw.println("    p[ackages]: dump installed packages");
20864                pw.println("    s[hared-users]: dump shared user IDs");
20865                pw.println("    m[essages]: print collected runtime messages");
20866                pw.println("    v[erifiers]: print package verifier info");
20867                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20868                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20869                pw.println("    version: print database version info");
20870                pw.println("    write: write current settings now");
20871                pw.println("    installs: details about install sessions");
20872                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20873                pw.println("    dexopt: dump dexopt state");
20874                pw.println("    compiler-stats: dump compiler statistics");
20875                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20876                pw.println("    <package.name>: info about given package");
20877                return;
20878            } else if ("--checkin".equals(opt)) {
20879                checkin = true;
20880            } else if ("-f".equals(opt)) {
20881                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20882            } else if ("--proto".equals(opt)) {
20883                dumpProto(fd);
20884                return;
20885            } else {
20886                pw.println("Unknown argument: " + opt + "; use -h for help");
20887            }
20888        }
20889
20890        // Is the caller requesting to dump a particular piece of data?
20891        if (opti < args.length) {
20892            String cmd = args[opti];
20893            opti++;
20894            // Is this a package name?
20895            if ("android".equals(cmd) || cmd.contains(".")) {
20896                packageName = cmd;
20897                // When dumping a single package, we always dump all of its
20898                // filter information since the amount of data will be reasonable.
20899                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20900            } else if ("check-permission".equals(cmd)) {
20901                if (opti >= args.length) {
20902                    pw.println("Error: check-permission missing permission argument");
20903                    return;
20904                }
20905                String perm = args[opti];
20906                opti++;
20907                if (opti >= args.length) {
20908                    pw.println("Error: check-permission missing package argument");
20909                    return;
20910                }
20911
20912                String pkg = args[opti];
20913                opti++;
20914                int user = UserHandle.getUserId(Binder.getCallingUid());
20915                if (opti < args.length) {
20916                    try {
20917                        user = Integer.parseInt(args[opti]);
20918                    } catch (NumberFormatException e) {
20919                        pw.println("Error: check-permission user argument is not a number: "
20920                                + args[opti]);
20921                        return;
20922                    }
20923                }
20924
20925                // Normalize package name to handle renamed packages and static libs
20926                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20927
20928                pw.println(checkPermission(perm, pkg, user));
20929                return;
20930            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20931                dumpState.setDump(DumpState.DUMP_LIBS);
20932            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20933                dumpState.setDump(DumpState.DUMP_FEATURES);
20934            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20935                if (opti >= args.length) {
20936                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20937                            | DumpState.DUMP_SERVICE_RESOLVERS
20938                            | DumpState.DUMP_RECEIVER_RESOLVERS
20939                            | DumpState.DUMP_CONTENT_RESOLVERS);
20940                } else {
20941                    while (opti < args.length) {
20942                        String name = args[opti];
20943                        if ("a".equals(name) || "activity".equals(name)) {
20944                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20945                        } else if ("s".equals(name) || "service".equals(name)) {
20946                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20947                        } else if ("r".equals(name) || "receiver".equals(name)) {
20948                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20949                        } else if ("c".equals(name) || "content".equals(name)) {
20950                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20951                        } else {
20952                            pw.println("Error: unknown resolver table type: " + name);
20953                            return;
20954                        }
20955                        opti++;
20956                    }
20957                }
20958            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20959                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20960            } else if ("permission".equals(cmd)) {
20961                if (opti >= args.length) {
20962                    pw.println("Error: permission requires permission name");
20963                    return;
20964                }
20965                permissionNames = new ArraySet<>();
20966                while (opti < args.length) {
20967                    permissionNames.add(args[opti]);
20968                    opti++;
20969                }
20970                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20971                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20972            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20973                dumpState.setDump(DumpState.DUMP_PREFERRED);
20974            } else if ("preferred-xml".equals(cmd)) {
20975                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20976                if (opti < args.length && "--full".equals(args[opti])) {
20977                    fullPreferred = true;
20978                    opti++;
20979                }
20980            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20981                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20982            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20983                dumpState.setDump(DumpState.DUMP_PACKAGES);
20984            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20985                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20986            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20987                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20988            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20989                dumpState.setDump(DumpState.DUMP_MESSAGES);
20990            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20991                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20992            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20993                    || "intent-filter-verifiers".equals(cmd)) {
20994                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20995            } else if ("version".equals(cmd)) {
20996                dumpState.setDump(DumpState.DUMP_VERSION);
20997            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20998                dumpState.setDump(DumpState.DUMP_KEYSETS);
20999            } else if ("installs".equals(cmd)) {
21000                dumpState.setDump(DumpState.DUMP_INSTALLS);
21001            } else if ("frozen".equals(cmd)) {
21002                dumpState.setDump(DumpState.DUMP_FROZEN);
21003            } else if ("dexopt".equals(cmd)) {
21004                dumpState.setDump(DumpState.DUMP_DEXOPT);
21005            } else if ("compiler-stats".equals(cmd)) {
21006                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21007            } else if ("enabled-overlays".equals(cmd)) {
21008                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21009            } else if ("changes".equals(cmd)) {
21010                dumpState.setDump(DumpState.DUMP_CHANGES);
21011            } else if ("write".equals(cmd)) {
21012                synchronized (mPackages) {
21013                    mSettings.writeLPr();
21014                    pw.println("Settings written.");
21015                    return;
21016                }
21017            }
21018        }
21019
21020        if (checkin) {
21021            pw.println("vers,1");
21022        }
21023
21024        // reader
21025        synchronized (mPackages) {
21026            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21027                if (!checkin) {
21028                    if (dumpState.onTitlePrinted())
21029                        pw.println();
21030                    pw.println("Database versions:");
21031                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21032                }
21033            }
21034
21035            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21036                if (!checkin) {
21037                    if (dumpState.onTitlePrinted())
21038                        pw.println();
21039                    pw.println("Verifiers:");
21040                    pw.print("  Required: ");
21041                    pw.print(mRequiredVerifierPackage);
21042                    pw.print(" (uid=");
21043                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21044                            UserHandle.USER_SYSTEM));
21045                    pw.println(")");
21046                } else if (mRequiredVerifierPackage != null) {
21047                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21048                    pw.print(",");
21049                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21050                            UserHandle.USER_SYSTEM));
21051                }
21052            }
21053
21054            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21055                    packageName == null) {
21056                if (mIntentFilterVerifierComponent != null) {
21057                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21058                    if (!checkin) {
21059                        if (dumpState.onTitlePrinted())
21060                            pw.println();
21061                        pw.println("Intent Filter Verifier:");
21062                        pw.print("  Using: ");
21063                        pw.print(verifierPackageName);
21064                        pw.print(" (uid=");
21065                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21066                                UserHandle.USER_SYSTEM));
21067                        pw.println(")");
21068                    } else if (verifierPackageName != null) {
21069                        pw.print("ifv,"); pw.print(verifierPackageName);
21070                        pw.print(",");
21071                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21072                                UserHandle.USER_SYSTEM));
21073                    }
21074                } else {
21075                    pw.println();
21076                    pw.println("No Intent Filter Verifier available!");
21077                }
21078            }
21079
21080            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21081                boolean printedHeader = false;
21082                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21083                while (it.hasNext()) {
21084                    String libName = it.next();
21085                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21086                    if (versionedLib == null) {
21087                        continue;
21088                    }
21089                    final int versionCount = versionedLib.size();
21090                    for (int i = 0; i < versionCount; i++) {
21091                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21092                        if (!checkin) {
21093                            if (!printedHeader) {
21094                                if (dumpState.onTitlePrinted())
21095                                    pw.println();
21096                                pw.println("Libraries:");
21097                                printedHeader = true;
21098                            }
21099                            pw.print("  ");
21100                        } else {
21101                            pw.print("lib,");
21102                        }
21103                        pw.print(libEntry.info.getName());
21104                        if (libEntry.info.isStatic()) {
21105                            pw.print(" version=" + libEntry.info.getVersion());
21106                        }
21107                        if (!checkin) {
21108                            pw.print(" -> ");
21109                        }
21110                        if (libEntry.path != null) {
21111                            pw.print(" (jar) ");
21112                            pw.print(libEntry.path);
21113                        } else {
21114                            pw.print(" (apk) ");
21115                            pw.print(libEntry.apk);
21116                        }
21117                        pw.println();
21118                    }
21119                }
21120            }
21121
21122            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21123                if (dumpState.onTitlePrinted())
21124                    pw.println();
21125                if (!checkin) {
21126                    pw.println("Features:");
21127                }
21128
21129                synchronized (mAvailableFeatures) {
21130                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21131                        if (checkin) {
21132                            pw.print("feat,");
21133                            pw.print(feat.name);
21134                            pw.print(",");
21135                            pw.println(feat.version);
21136                        } else {
21137                            pw.print("  ");
21138                            pw.print(feat.name);
21139                            if (feat.version > 0) {
21140                                pw.print(" version=");
21141                                pw.print(feat.version);
21142                            }
21143                            pw.println();
21144                        }
21145                    }
21146                }
21147            }
21148
21149            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21150                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21151                        : "Activity Resolver Table:", "  ", packageName,
21152                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21153                    dumpState.setTitlePrinted(true);
21154                }
21155            }
21156            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21157                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21158                        : "Receiver Resolver Table:", "  ", packageName,
21159                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21160                    dumpState.setTitlePrinted(true);
21161                }
21162            }
21163            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21164                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21165                        : "Service Resolver Table:", "  ", packageName,
21166                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21167                    dumpState.setTitlePrinted(true);
21168                }
21169            }
21170            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21171                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21172                        : "Provider Resolver Table:", "  ", packageName,
21173                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21174                    dumpState.setTitlePrinted(true);
21175                }
21176            }
21177
21178            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21179                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21180                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21181                    int user = mSettings.mPreferredActivities.keyAt(i);
21182                    if (pir.dump(pw,
21183                            dumpState.getTitlePrinted()
21184                                ? "\nPreferred Activities User " + user + ":"
21185                                : "Preferred Activities User " + user + ":", "  ",
21186                            packageName, true, false)) {
21187                        dumpState.setTitlePrinted(true);
21188                    }
21189                }
21190            }
21191
21192            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21193                pw.flush();
21194                FileOutputStream fout = new FileOutputStream(fd);
21195                BufferedOutputStream str = new BufferedOutputStream(fout);
21196                XmlSerializer serializer = new FastXmlSerializer();
21197                try {
21198                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21199                    serializer.startDocument(null, true);
21200                    serializer.setFeature(
21201                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21202                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21203                    serializer.endDocument();
21204                    serializer.flush();
21205                } catch (IllegalArgumentException e) {
21206                    pw.println("Failed writing: " + e);
21207                } catch (IllegalStateException e) {
21208                    pw.println("Failed writing: " + e);
21209                } catch (IOException e) {
21210                    pw.println("Failed writing: " + e);
21211                }
21212            }
21213
21214            if (!checkin
21215                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21216                    && packageName == null) {
21217                pw.println();
21218                int count = mSettings.mPackages.size();
21219                if (count == 0) {
21220                    pw.println("No applications!");
21221                    pw.println();
21222                } else {
21223                    final String prefix = "  ";
21224                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21225                    if (allPackageSettings.size() == 0) {
21226                        pw.println("No domain preferred apps!");
21227                        pw.println();
21228                    } else {
21229                        pw.println("App verification status:");
21230                        pw.println();
21231                        count = 0;
21232                        for (PackageSetting ps : allPackageSettings) {
21233                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21234                            if (ivi == null || ivi.getPackageName() == null) continue;
21235                            pw.println(prefix + "Package: " + ivi.getPackageName());
21236                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21237                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21238                            pw.println();
21239                            count++;
21240                        }
21241                        if (count == 0) {
21242                            pw.println(prefix + "No app verification established.");
21243                            pw.println();
21244                        }
21245                        for (int userId : sUserManager.getUserIds()) {
21246                            pw.println("App linkages for user " + userId + ":");
21247                            pw.println();
21248                            count = 0;
21249                            for (PackageSetting ps : allPackageSettings) {
21250                                final long status = ps.getDomainVerificationStatusForUser(userId);
21251                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21252                                        && !DEBUG_DOMAIN_VERIFICATION) {
21253                                    continue;
21254                                }
21255                                pw.println(prefix + "Package: " + ps.name);
21256                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21257                                String statusStr = IntentFilterVerificationInfo.
21258                                        getStatusStringFromValue(status);
21259                                pw.println(prefix + "Status:  " + statusStr);
21260                                pw.println();
21261                                count++;
21262                            }
21263                            if (count == 0) {
21264                                pw.println(prefix + "No configured app linkages.");
21265                                pw.println();
21266                            }
21267                        }
21268                    }
21269                }
21270            }
21271
21272            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21273                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21274                if (packageName == null && permissionNames == null) {
21275                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21276                        if (iperm == 0) {
21277                            if (dumpState.onTitlePrinted())
21278                                pw.println();
21279                            pw.println("AppOp Permissions:");
21280                        }
21281                        pw.print("  AppOp Permission ");
21282                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21283                        pw.println(":");
21284                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21285                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21286                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21287                        }
21288                    }
21289                }
21290            }
21291
21292            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21293                boolean printedSomething = false;
21294                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21295                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21296                        continue;
21297                    }
21298                    if (!printedSomething) {
21299                        if (dumpState.onTitlePrinted())
21300                            pw.println();
21301                        pw.println("Registered ContentProviders:");
21302                        printedSomething = true;
21303                    }
21304                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21305                    pw.print("    "); pw.println(p.toString());
21306                }
21307                printedSomething = false;
21308                for (Map.Entry<String, PackageParser.Provider> entry :
21309                        mProvidersByAuthority.entrySet()) {
21310                    PackageParser.Provider p = entry.getValue();
21311                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21312                        continue;
21313                    }
21314                    if (!printedSomething) {
21315                        if (dumpState.onTitlePrinted())
21316                            pw.println();
21317                        pw.println("ContentProvider Authorities:");
21318                        printedSomething = true;
21319                    }
21320                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21321                    pw.print("    "); pw.println(p.toString());
21322                    if (p.info != null && p.info.applicationInfo != null) {
21323                        final String appInfo = p.info.applicationInfo.toString();
21324                        pw.print("      applicationInfo="); pw.println(appInfo);
21325                    }
21326                }
21327            }
21328
21329            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21330                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21331            }
21332
21333            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21334                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21335            }
21336
21337            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21338                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21339            }
21340
21341            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21342                if (dumpState.onTitlePrinted()) pw.println();
21343                pw.println("Package Changes:");
21344                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21345                final int K = mChangedPackages.size();
21346                for (int i = 0; i < K; i++) {
21347                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21348                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21349                    final int N = changes.size();
21350                    if (N == 0) {
21351                        pw.print("    "); pw.println("No packages changed");
21352                    } else {
21353                        for (int j = 0; j < N; j++) {
21354                            final String pkgName = changes.valueAt(j);
21355                            final int sequenceNumber = changes.keyAt(j);
21356                            pw.print("    ");
21357                            pw.print("seq=");
21358                            pw.print(sequenceNumber);
21359                            pw.print(", package=");
21360                            pw.println(pkgName);
21361                        }
21362                    }
21363                }
21364            }
21365
21366            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21367                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21368            }
21369
21370            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21371                // XXX should handle packageName != null by dumping only install data that
21372                // the given package is involved with.
21373                if (dumpState.onTitlePrinted()) pw.println();
21374
21375                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21376                ipw.println();
21377                ipw.println("Frozen packages:");
21378                ipw.increaseIndent();
21379                if (mFrozenPackages.size() == 0) {
21380                    ipw.println("(none)");
21381                } else {
21382                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21383                        ipw.println(mFrozenPackages.valueAt(i));
21384                    }
21385                }
21386                ipw.decreaseIndent();
21387            }
21388
21389            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21390                if (dumpState.onTitlePrinted()) pw.println();
21391                dumpDexoptStateLPr(pw, packageName);
21392            }
21393
21394            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21395                if (dumpState.onTitlePrinted()) pw.println();
21396                dumpCompilerStatsLPr(pw, packageName);
21397            }
21398
21399            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21400                if (dumpState.onTitlePrinted()) pw.println();
21401                dumpEnabledOverlaysLPr(pw);
21402            }
21403
21404            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21405                if (dumpState.onTitlePrinted()) pw.println();
21406                mSettings.dumpReadMessagesLPr(pw, dumpState);
21407
21408                pw.println();
21409                pw.println("Package warning messages:");
21410                BufferedReader in = null;
21411                String line = null;
21412                try {
21413                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21414                    while ((line = in.readLine()) != null) {
21415                        if (line.contains("ignored: updated version")) continue;
21416                        pw.println(line);
21417                    }
21418                } catch (IOException ignored) {
21419                } finally {
21420                    IoUtils.closeQuietly(in);
21421                }
21422            }
21423
21424            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21425                BufferedReader in = null;
21426                String line = null;
21427                try {
21428                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21429                    while ((line = in.readLine()) != null) {
21430                        if (line.contains("ignored: updated version")) continue;
21431                        pw.print("msg,");
21432                        pw.println(line);
21433                    }
21434                } catch (IOException ignored) {
21435                } finally {
21436                    IoUtils.closeQuietly(in);
21437                }
21438            }
21439        }
21440
21441        // PackageInstaller should be called outside of mPackages lock
21442        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21443            // XXX should handle packageName != null by dumping only install data that
21444            // the given package is involved with.
21445            if (dumpState.onTitlePrinted()) pw.println();
21446            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21447        }
21448    }
21449
21450    private void dumpProto(FileDescriptor fd) {
21451        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21452
21453        synchronized (mPackages) {
21454            final long requiredVerifierPackageToken =
21455                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21456            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21457            proto.write(
21458                    PackageServiceDumpProto.PackageShortProto.UID,
21459                    getPackageUid(
21460                            mRequiredVerifierPackage,
21461                            MATCH_DEBUG_TRIAGED_MISSING,
21462                            UserHandle.USER_SYSTEM));
21463            proto.end(requiredVerifierPackageToken);
21464
21465            if (mIntentFilterVerifierComponent != null) {
21466                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21467                final long verifierPackageToken =
21468                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21469                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21470                proto.write(
21471                        PackageServiceDumpProto.PackageShortProto.UID,
21472                        getPackageUid(
21473                                verifierPackageName,
21474                                MATCH_DEBUG_TRIAGED_MISSING,
21475                                UserHandle.USER_SYSTEM));
21476                proto.end(verifierPackageToken);
21477            }
21478
21479            dumpSharedLibrariesProto(proto);
21480            dumpFeaturesProto(proto);
21481            mSettings.dumpPackagesProto(proto);
21482            mSettings.dumpSharedUsersProto(proto);
21483            dumpMessagesProto(proto);
21484        }
21485        proto.flush();
21486    }
21487
21488    private void dumpMessagesProto(ProtoOutputStream proto) {
21489        BufferedReader in = null;
21490        String line = null;
21491        try {
21492            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21493            while ((line = in.readLine()) != null) {
21494                if (line.contains("ignored: updated version")) continue;
21495                proto.write(PackageServiceDumpProto.MESSAGES, line);
21496            }
21497        } catch (IOException ignored) {
21498        } finally {
21499            IoUtils.closeQuietly(in);
21500        }
21501    }
21502
21503    private void dumpFeaturesProto(ProtoOutputStream proto) {
21504        synchronized (mAvailableFeatures) {
21505            final int count = mAvailableFeatures.size();
21506            for (int i = 0; i < count; i++) {
21507                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21508                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21509                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21510                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21511                proto.end(featureToken);
21512            }
21513        }
21514    }
21515
21516    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21517        final int count = mSharedLibraries.size();
21518        for (int i = 0; i < count; i++) {
21519            final String libName = mSharedLibraries.keyAt(i);
21520            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21521            if (versionedLib == null) {
21522                continue;
21523            }
21524            final int versionCount = versionedLib.size();
21525            for (int j = 0; j < versionCount; j++) {
21526                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21527                final long sharedLibraryToken =
21528                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21529                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21530                final boolean isJar = (libEntry.path != null);
21531                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21532                if (isJar) {
21533                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21534                } else {
21535                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21536                }
21537                proto.end(sharedLibraryToken);
21538            }
21539        }
21540    }
21541
21542    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21543        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21544        ipw.println();
21545        ipw.println("Dexopt state:");
21546        ipw.increaseIndent();
21547        Collection<PackageParser.Package> packages = null;
21548        if (packageName != null) {
21549            PackageParser.Package targetPackage = mPackages.get(packageName);
21550            if (targetPackage != null) {
21551                packages = Collections.singletonList(targetPackage);
21552            } else {
21553                ipw.println("Unable to find package: " + packageName);
21554                return;
21555            }
21556        } else {
21557            packages = mPackages.values();
21558        }
21559
21560        for (PackageParser.Package pkg : packages) {
21561            ipw.println("[" + pkg.packageName + "]");
21562            ipw.increaseIndent();
21563            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21564            ipw.decreaseIndent();
21565        }
21566    }
21567
21568    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21569        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21570        ipw.println();
21571        ipw.println("Compiler stats:");
21572        ipw.increaseIndent();
21573        Collection<PackageParser.Package> packages = null;
21574        if (packageName != null) {
21575            PackageParser.Package targetPackage = mPackages.get(packageName);
21576            if (targetPackage != null) {
21577                packages = Collections.singletonList(targetPackage);
21578            } else {
21579                ipw.println("Unable to find package: " + packageName);
21580                return;
21581            }
21582        } else {
21583            packages = mPackages.values();
21584        }
21585
21586        for (PackageParser.Package pkg : packages) {
21587            ipw.println("[" + pkg.packageName + "]");
21588            ipw.increaseIndent();
21589
21590            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21591            if (stats == null) {
21592                ipw.println("(No recorded stats)");
21593            } else {
21594                stats.dump(ipw);
21595            }
21596            ipw.decreaseIndent();
21597        }
21598    }
21599
21600    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21601        pw.println("Enabled overlay paths:");
21602        final int N = mEnabledOverlayPaths.size();
21603        for (int i = 0; i < N; i++) {
21604            final int userId = mEnabledOverlayPaths.keyAt(i);
21605            pw.println(String.format("    User %d:", userId));
21606            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21607                mEnabledOverlayPaths.valueAt(i);
21608            final int M = userSpecificOverlays.size();
21609            for (int j = 0; j < M; j++) {
21610                final String targetPackageName = userSpecificOverlays.keyAt(j);
21611                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21612                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21613            }
21614        }
21615    }
21616
21617    private String dumpDomainString(String packageName) {
21618        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21619                .getList();
21620        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21621
21622        ArraySet<String> result = new ArraySet<>();
21623        if (iviList.size() > 0) {
21624            for (IntentFilterVerificationInfo ivi : iviList) {
21625                for (String host : ivi.getDomains()) {
21626                    result.add(host);
21627                }
21628            }
21629        }
21630        if (filters != null && filters.size() > 0) {
21631            for (IntentFilter filter : filters) {
21632                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21633                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21634                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21635                    result.addAll(filter.getHostsList());
21636                }
21637            }
21638        }
21639
21640        StringBuilder sb = new StringBuilder(result.size() * 16);
21641        for (String domain : result) {
21642            if (sb.length() > 0) sb.append(" ");
21643            sb.append(domain);
21644        }
21645        return sb.toString();
21646    }
21647
21648    // ------- apps on sdcard specific code -------
21649    static final boolean DEBUG_SD_INSTALL = false;
21650
21651    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21652
21653    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21654
21655    private boolean mMediaMounted = false;
21656
21657    static String getEncryptKey() {
21658        try {
21659            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21660                    SD_ENCRYPTION_KEYSTORE_NAME);
21661            if (sdEncKey == null) {
21662                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21663                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21664                if (sdEncKey == null) {
21665                    Slog.e(TAG, "Failed to create encryption keys");
21666                    return null;
21667                }
21668            }
21669            return sdEncKey;
21670        } catch (NoSuchAlgorithmException nsae) {
21671            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21672            return null;
21673        } catch (IOException ioe) {
21674            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21675            return null;
21676        }
21677    }
21678
21679    /*
21680     * Update media status on PackageManager.
21681     */
21682    @Override
21683    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21684        int callingUid = Binder.getCallingUid();
21685        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21686            throw new SecurityException("Media status can only be updated by the system");
21687        }
21688        // reader; this apparently protects mMediaMounted, but should probably
21689        // be a different lock in that case.
21690        synchronized (mPackages) {
21691            Log.i(TAG, "Updating external media status from "
21692                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21693                    + (mediaStatus ? "mounted" : "unmounted"));
21694            if (DEBUG_SD_INSTALL)
21695                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21696                        + ", mMediaMounted=" + mMediaMounted);
21697            if (mediaStatus == mMediaMounted) {
21698                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21699                        : 0, -1);
21700                mHandler.sendMessage(msg);
21701                return;
21702            }
21703            mMediaMounted = mediaStatus;
21704        }
21705        // Queue up an async operation since the package installation may take a
21706        // little while.
21707        mHandler.post(new Runnable() {
21708            public void run() {
21709                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21710            }
21711        });
21712    }
21713
21714    /**
21715     * Called by StorageManagerService when the initial ASECs to scan are available.
21716     * Should block until all the ASEC containers are finished being scanned.
21717     */
21718    public void scanAvailableAsecs() {
21719        updateExternalMediaStatusInner(true, false, false);
21720    }
21721
21722    /*
21723     * Collect information of applications on external media, map them against
21724     * existing containers and update information based on current mount status.
21725     * Please note that we always have to report status if reportStatus has been
21726     * set to true especially when unloading packages.
21727     */
21728    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21729            boolean externalStorage) {
21730        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21731        int[] uidArr = EmptyArray.INT;
21732
21733        final String[] list = PackageHelper.getSecureContainerList();
21734        if (ArrayUtils.isEmpty(list)) {
21735            Log.i(TAG, "No secure containers found");
21736        } else {
21737            // Process list of secure containers and categorize them
21738            // as active or stale based on their package internal state.
21739
21740            // reader
21741            synchronized (mPackages) {
21742                for (String cid : list) {
21743                    // Leave stages untouched for now; installer service owns them
21744                    if (PackageInstallerService.isStageName(cid)) continue;
21745
21746                    if (DEBUG_SD_INSTALL)
21747                        Log.i(TAG, "Processing container " + cid);
21748                    String pkgName = getAsecPackageName(cid);
21749                    if (pkgName == null) {
21750                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21751                        continue;
21752                    }
21753                    if (DEBUG_SD_INSTALL)
21754                        Log.i(TAG, "Looking for pkg : " + pkgName);
21755
21756                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21757                    if (ps == null) {
21758                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21759                        continue;
21760                    }
21761
21762                    /*
21763                     * Skip packages that are not external if we're unmounting
21764                     * external storage.
21765                     */
21766                    if (externalStorage && !isMounted && !isExternal(ps)) {
21767                        continue;
21768                    }
21769
21770                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21771                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21772                    // The package status is changed only if the code path
21773                    // matches between settings and the container id.
21774                    if (ps.codePathString != null
21775                            && ps.codePathString.startsWith(args.getCodePath())) {
21776                        if (DEBUG_SD_INSTALL) {
21777                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21778                                    + " at code path: " + ps.codePathString);
21779                        }
21780
21781                        // We do have a valid package installed on sdcard
21782                        processCids.put(args, ps.codePathString);
21783                        final int uid = ps.appId;
21784                        if (uid != -1) {
21785                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21786                        }
21787                    } else {
21788                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21789                                + ps.codePathString);
21790                    }
21791                }
21792            }
21793
21794            Arrays.sort(uidArr);
21795        }
21796
21797        // Process packages with valid entries.
21798        if (isMounted) {
21799            if (DEBUG_SD_INSTALL)
21800                Log.i(TAG, "Loading packages");
21801            loadMediaPackages(processCids, uidArr, externalStorage);
21802            startCleaningPackages();
21803            mInstallerService.onSecureContainersAvailable();
21804        } else {
21805            if (DEBUG_SD_INSTALL)
21806                Log.i(TAG, "Unloading packages");
21807            unloadMediaPackages(processCids, uidArr, reportStatus);
21808        }
21809    }
21810
21811    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21812            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21813        final int size = infos.size();
21814        final String[] packageNames = new String[size];
21815        final int[] packageUids = new int[size];
21816        for (int i = 0; i < size; i++) {
21817            final ApplicationInfo info = infos.get(i);
21818            packageNames[i] = info.packageName;
21819            packageUids[i] = info.uid;
21820        }
21821        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21822                finishedReceiver);
21823    }
21824
21825    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21826            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21827        sendResourcesChangedBroadcast(mediaStatus, replacing,
21828                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21829    }
21830
21831    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21832            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21833        int size = pkgList.length;
21834        if (size > 0) {
21835            // Send broadcasts here
21836            Bundle extras = new Bundle();
21837            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21838            if (uidArr != null) {
21839                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21840            }
21841            if (replacing) {
21842                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21843            }
21844            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21845                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21846            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21847        }
21848    }
21849
21850   /*
21851     * Look at potentially valid container ids from processCids If package
21852     * information doesn't match the one on record or package scanning fails,
21853     * the cid is added to list of removeCids. We currently don't delete stale
21854     * containers.
21855     */
21856    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21857            boolean externalStorage) {
21858        ArrayList<String> pkgList = new ArrayList<String>();
21859        Set<AsecInstallArgs> keys = processCids.keySet();
21860
21861        for (AsecInstallArgs args : keys) {
21862            String codePath = processCids.get(args);
21863            if (DEBUG_SD_INSTALL)
21864                Log.i(TAG, "Loading container : " + args.cid);
21865            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21866            try {
21867                // Make sure there are no container errors first.
21868                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21869                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21870                            + " when installing from sdcard");
21871                    continue;
21872                }
21873                // Check code path here.
21874                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21875                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21876                            + " does not match one in settings " + codePath);
21877                    continue;
21878                }
21879                // Parse package
21880                int parseFlags = mDefParseFlags;
21881                if (args.isExternalAsec()) {
21882                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21883                }
21884                if (args.isFwdLocked()) {
21885                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21886                }
21887
21888                synchronized (mInstallLock) {
21889                    PackageParser.Package pkg = null;
21890                    try {
21891                        // Sadly we don't know the package name yet to freeze it
21892                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21893                                SCAN_IGNORE_FROZEN, 0, null);
21894                    } catch (PackageManagerException e) {
21895                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21896                    }
21897                    // Scan the package
21898                    if (pkg != null) {
21899                        /*
21900                         * TODO why is the lock being held? doPostInstall is
21901                         * called in other places without the lock. This needs
21902                         * to be straightened out.
21903                         */
21904                        // writer
21905                        synchronized (mPackages) {
21906                            retCode = PackageManager.INSTALL_SUCCEEDED;
21907                            pkgList.add(pkg.packageName);
21908                            // Post process args
21909                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21910                                    pkg.applicationInfo.uid);
21911                        }
21912                    } else {
21913                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21914                    }
21915                }
21916
21917            } finally {
21918                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21919                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21920                }
21921            }
21922        }
21923        // writer
21924        synchronized (mPackages) {
21925            // If the platform SDK has changed since the last time we booted,
21926            // we need to re-grant app permission to catch any new ones that
21927            // appear. This is really a hack, and means that apps can in some
21928            // cases get permissions that the user didn't initially explicitly
21929            // allow... it would be nice to have some better way to handle
21930            // this situation.
21931            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21932                    : mSettings.getInternalVersion();
21933            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21934                    : StorageManager.UUID_PRIVATE_INTERNAL;
21935
21936            int updateFlags = UPDATE_PERMISSIONS_ALL;
21937            if (ver.sdkVersion != mSdkVersion) {
21938                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21939                        + mSdkVersion + "; regranting permissions for external");
21940                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21941            }
21942            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21943
21944            // Yay, everything is now upgraded
21945            ver.forceCurrent();
21946
21947            // can downgrade to reader
21948            // Persist settings
21949            mSettings.writeLPr();
21950        }
21951        // Send a broadcast to let everyone know we are done processing
21952        if (pkgList.size() > 0) {
21953            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21954        }
21955    }
21956
21957   /*
21958     * Utility method to unload a list of specified containers
21959     */
21960    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21961        // Just unmount all valid containers.
21962        for (AsecInstallArgs arg : cidArgs) {
21963            synchronized (mInstallLock) {
21964                arg.doPostDeleteLI(false);
21965           }
21966       }
21967   }
21968
21969    /*
21970     * Unload packages mounted on external media. This involves deleting package
21971     * data from internal structures, sending broadcasts about disabled packages,
21972     * gc'ing to free up references, unmounting all secure containers
21973     * corresponding to packages on external media, and posting a
21974     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21975     * that we always have to post this message if status has been requested no
21976     * matter what.
21977     */
21978    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21979            final boolean reportStatus) {
21980        if (DEBUG_SD_INSTALL)
21981            Log.i(TAG, "unloading media packages");
21982        ArrayList<String> pkgList = new ArrayList<String>();
21983        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21984        final Set<AsecInstallArgs> keys = processCids.keySet();
21985        for (AsecInstallArgs args : keys) {
21986            String pkgName = args.getPackageName();
21987            if (DEBUG_SD_INSTALL)
21988                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21989            // Delete package internally
21990            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21991            synchronized (mInstallLock) {
21992                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21993                final boolean res;
21994                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21995                        "unloadMediaPackages")) {
21996                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21997                            null);
21998                }
21999                if (res) {
22000                    pkgList.add(pkgName);
22001                } else {
22002                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22003                    failedList.add(args);
22004                }
22005            }
22006        }
22007
22008        // reader
22009        synchronized (mPackages) {
22010            // We didn't update the settings after removing each package;
22011            // write them now for all packages.
22012            mSettings.writeLPr();
22013        }
22014
22015        // We have to absolutely send UPDATED_MEDIA_STATUS only
22016        // after confirming that all the receivers processed the ordered
22017        // broadcast when packages get disabled, force a gc to clean things up.
22018        // and unload all the containers.
22019        if (pkgList.size() > 0) {
22020            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22021                    new IIntentReceiver.Stub() {
22022                public void performReceive(Intent intent, int resultCode, String data,
22023                        Bundle extras, boolean ordered, boolean sticky,
22024                        int sendingUser) throws RemoteException {
22025                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22026                            reportStatus ? 1 : 0, 1, keys);
22027                    mHandler.sendMessage(msg);
22028                }
22029            });
22030        } else {
22031            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22032                    keys);
22033            mHandler.sendMessage(msg);
22034        }
22035    }
22036
22037    private void loadPrivatePackages(final VolumeInfo vol) {
22038        mHandler.post(new Runnable() {
22039            @Override
22040            public void run() {
22041                loadPrivatePackagesInner(vol);
22042            }
22043        });
22044    }
22045
22046    private void loadPrivatePackagesInner(VolumeInfo vol) {
22047        final String volumeUuid = vol.fsUuid;
22048        if (TextUtils.isEmpty(volumeUuid)) {
22049            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22050            return;
22051        }
22052
22053        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22054        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22055        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22056
22057        final VersionInfo ver;
22058        final List<PackageSetting> packages;
22059        synchronized (mPackages) {
22060            ver = mSettings.findOrCreateVersion(volumeUuid);
22061            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22062        }
22063
22064        for (PackageSetting ps : packages) {
22065            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22066            synchronized (mInstallLock) {
22067                final PackageParser.Package pkg;
22068                try {
22069                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22070                    loaded.add(pkg.applicationInfo);
22071
22072                } catch (PackageManagerException e) {
22073                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22074                }
22075
22076                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22077                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22078                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22079                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22080                }
22081            }
22082        }
22083
22084        // Reconcile app data for all started/unlocked users
22085        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22086        final UserManager um = mContext.getSystemService(UserManager.class);
22087        UserManagerInternal umInternal = getUserManagerInternal();
22088        for (UserInfo user : um.getUsers()) {
22089            final int flags;
22090            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22091                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22092            } else if (umInternal.isUserRunning(user.id)) {
22093                flags = StorageManager.FLAG_STORAGE_DE;
22094            } else {
22095                continue;
22096            }
22097
22098            try {
22099                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22100                synchronized (mInstallLock) {
22101                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22102                }
22103            } catch (IllegalStateException e) {
22104                // Device was probably ejected, and we'll process that event momentarily
22105                Slog.w(TAG, "Failed to prepare storage: " + e);
22106            }
22107        }
22108
22109        synchronized (mPackages) {
22110            int updateFlags = UPDATE_PERMISSIONS_ALL;
22111            if (ver.sdkVersion != mSdkVersion) {
22112                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22113                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22114                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22115            }
22116            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22117
22118            // Yay, everything is now upgraded
22119            ver.forceCurrent();
22120
22121            mSettings.writeLPr();
22122        }
22123
22124        for (PackageFreezer freezer : freezers) {
22125            freezer.close();
22126        }
22127
22128        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22129        sendResourcesChangedBroadcast(true, false, loaded, null);
22130    }
22131
22132    private void unloadPrivatePackages(final VolumeInfo vol) {
22133        mHandler.post(new Runnable() {
22134            @Override
22135            public void run() {
22136                unloadPrivatePackagesInner(vol);
22137            }
22138        });
22139    }
22140
22141    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22142        final String volumeUuid = vol.fsUuid;
22143        if (TextUtils.isEmpty(volumeUuid)) {
22144            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22145            return;
22146        }
22147
22148        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22149        synchronized (mInstallLock) {
22150        synchronized (mPackages) {
22151            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22152            for (PackageSetting ps : packages) {
22153                if (ps.pkg == null) continue;
22154
22155                final ApplicationInfo info = ps.pkg.applicationInfo;
22156                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22157                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22158
22159                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22160                        "unloadPrivatePackagesInner")) {
22161                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22162                            false, null)) {
22163                        unloaded.add(info);
22164                    } else {
22165                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22166                    }
22167                }
22168
22169                // Try very hard to release any references to this package
22170                // so we don't risk the system server being killed due to
22171                // open FDs
22172                AttributeCache.instance().removePackage(ps.name);
22173            }
22174
22175            mSettings.writeLPr();
22176        }
22177        }
22178
22179        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22180        sendResourcesChangedBroadcast(false, false, unloaded, null);
22181
22182        // Try very hard to release any references to this path so we don't risk
22183        // the system server being killed due to open FDs
22184        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22185
22186        for (int i = 0; i < 3; i++) {
22187            System.gc();
22188            System.runFinalization();
22189        }
22190    }
22191
22192    private void assertPackageKnown(String volumeUuid, String packageName)
22193            throws PackageManagerException {
22194        synchronized (mPackages) {
22195            // Normalize package name to handle renamed packages
22196            packageName = normalizePackageNameLPr(packageName);
22197
22198            final PackageSetting ps = mSettings.mPackages.get(packageName);
22199            if (ps == null) {
22200                throw new PackageManagerException("Package " + packageName + " is unknown");
22201            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22202                throw new PackageManagerException(
22203                        "Package " + packageName + " found on unknown volume " + volumeUuid
22204                                + "; expected volume " + ps.volumeUuid);
22205            }
22206        }
22207    }
22208
22209    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22210            throws PackageManagerException {
22211        synchronized (mPackages) {
22212            // Normalize package name to handle renamed packages
22213            packageName = normalizePackageNameLPr(packageName);
22214
22215            final PackageSetting ps = mSettings.mPackages.get(packageName);
22216            if (ps == null) {
22217                throw new PackageManagerException("Package " + packageName + " is unknown");
22218            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22219                throw new PackageManagerException(
22220                        "Package " + packageName + " found on unknown volume " + volumeUuid
22221                                + "; expected volume " + ps.volumeUuid);
22222            } else if (!ps.getInstalled(userId)) {
22223                throw new PackageManagerException(
22224                        "Package " + packageName + " not installed for user " + userId);
22225            }
22226        }
22227    }
22228
22229    private List<String> collectAbsoluteCodePaths() {
22230        synchronized (mPackages) {
22231            List<String> codePaths = new ArrayList<>();
22232            final int packageCount = mSettings.mPackages.size();
22233            for (int i = 0; i < packageCount; i++) {
22234                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22235                codePaths.add(ps.codePath.getAbsolutePath());
22236            }
22237            return codePaths;
22238        }
22239    }
22240
22241    /**
22242     * Examine all apps present on given mounted volume, and destroy apps that
22243     * aren't expected, either due to uninstallation or reinstallation on
22244     * another volume.
22245     */
22246    private void reconcileApps(String volumeUuid) {
22247        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22248        List<File> filesToDelete = null;
22249
22250        final File[] files = FileUtils.listFilesOrEmpty(
22251                Environment.getDataAppDirectory(volumeUuid));
22252        for (File file : files) {
22253            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22254                    && !PackageInstallerService.isStageName(file.getName());
22255            if (!isPackage) {
22256                // Ignore entries which are not packages
22257                continue;
22258            }
22259
22260            String absolutePath = file.getAbsolutePath();
22261
22262            boolean pathValid = false;
22263            final int absoluteCodePathCount = absoluteCodePaths.size();
22264            for (int i = 0; i < absoluteCodePathCount; i++) {
22265                String absoluteCodePath = absoluteCodePaths.get(i);
22266                if (absolutePath.startsWith(absoluteCodePath)) {
22267                    pathValid = true;
22268                    break;
22269                }
22270            }
22271
22272            if (!pathValid) {
22273                if (filesToDelete == null) {
22274                    filesToDelete = new ArrayList<>();
22275                }
22276                filesToDelete.add(file);
22277            }
22278        }
22279
22280        if (filesToDelete != null) {
22281            final int fileToDeleteCount = filesToDelete.size();
22282            for (int i = 0; i < fileToDeleteCount; i++) {
22283                File fileToDelete = filesToDelete.get(i);
22284                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22285                synchronized (mInstallLock) {
22286                    removeCodePathLI(fileToDelete);
22287                }
22288            }
22289        }
22290    }
22291
22292    /**
22293     * Reconcile all app data for the given user.
22294     * <p>
22295     * Verifies that directories exist and that ownership and labeling is
22296     * correct for all installed apps on all mounted volumes.
22297     */
22298    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22299        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22300        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22301            final String volumeUuid = vol.getFsUuid();
22302            synchronized (mInstallLock) {
22303                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22304            }
22305        }
22306    }
22307
22308    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22309            boolean migrateAppData) {
22310        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22311    }
22312
22313    /**
22314     * Reconcile all app data on given mounted volume.
22315     * <p>
22316     * Destroys app data that isn't expected, either due to uninstallation or
22317     * reinstallation on another volume.
22318     * <p>
22319     * Verifies that directories exist and that ownership and labeling is
22320     * correct for all installed apps.
22321     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22322     */
22323    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22324            boolean migrateAppData, boolean onlyCoreApps) {
22325        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22326                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22327        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22328
22329        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22330        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22331
22332        // First look for stale data that doesn't belong, and check if things
22333        // have changed since we did our last restorecon
22334        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22335            if (StorageManager.isFileEncryptedNativeOrEmulated()
22336                    && !StorageManager.isUserKeyUnlocked(userId)) {
22337                throw new RuntimeException(
22338                        "Yikes, someone asked us to reconcile CE storage while " + userId
22339                                + " was still locked; this would have caused massive data loss!");
22340            }
22341
22342            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22343            for (File file : files) {
22344                final String packageName = file.getName();
22345                try {
22346                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22347                } catch (PackageManagerException e) {
22348                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22349                    try {
22350                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22351                                StorageManager.FLAG_STORAGE_CE, 0);
22352                    } catch (InstallerException e2) {
22353                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22354                    }
22355                }
22356            }
22357        }
22358        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22359            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22360            for (File file : files) {
22361                final String packageName = file.getName();
22362                try {
22363                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22364                } catch (PackageManagerException e) {
22365                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22366                    try {
22367                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22368                                StorageManager.FLAG_STORAGE_DE, 0);
22369                    } catch (InstallerException e2) {
22370                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22371                    }
22372                }
22373            }
22374        }
22375
22376        // Ensure that data directories are ready to roll for all packages
22377        // installed for this volume and user
22378        final List<PackageSetting> packages;
22379        synchronized (mPackages) {
22380            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22381        }
22382        int preparedCount = 0;
22383        for (PackageSetting ps : packages) {
22384            final String packageName = ps.name;
22385            if (ps.pkg == null) {
22386                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22387                // TODO: might be due to legacy ASEC apps; we should circle back
22388                // and reconcile again once they're scanned
22389                continue;
22390            }
22391            // Skip non-core apps if requested
22392            if (onlyCoreApps && !ps.pkg.coreApp) {
22393                result.add(packageName);
22394                continue;
22395            }
22396
22397            if (ps.getInstalled(userId)) {
22398                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22399                preparedCount++;
22400            }
22401        }
22402
22403        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22404        return result;
22405    }
22406
22407    /**
22408     * Prepare app data for the given app just after it was installed or
22409     * upgraded. This method carefully only touches users that it's installed
22410     * for, and it forces a restorecon to handle any seinfo changes.
22411     * <p>
22412     * Verifies that directories exist and that ownership and labeling is
22413     * correct for all installed apps. If there is an ownership mismatch, it
22414     * will try recovering system apps by wiping data; third-party app data is
22415     * left intact.
22416     * <p>
22417     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22418     */
22419    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22420        final PackageSetting ps;
22421        synchronized (mPackages) {
22422            ps = mSettings.mPackages.get(pkg.packageName);
22423            mSettings.writeKernelMappingLPr(ps);
22424        }
22425
22426        final UserManager um = mContext.getSystemService(UserManager.class);
22427        UserManagerInternal umInternal = getUserManagerInternal();
22428        for (UserInfo user : um.getUsers()) {
22429            final int flags;
22430            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22431                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22432            } else if (umInternal.isUserRunning(user.id)) {
22433                flags = StorageManager.FLAG_STORAGE_DE;
22434            } else {
22435                continue;
22436            }
22437
22438            if (ps.getInstalled(user.id)) {
22439                // TODO: when user data is locked, mark that we're still dirty
22440                prepareAppDataLIF(pkg, user.id, flags);
22441            }
22442        }
22443    }
22444
22445    /**
22446     * Prepare app data for the given app.
22447     * <p>
22448     * Verifies that directories exist and that ownership and labeling is
22449     * correct for all installed apps. If there is an ownership mismatch, this
22450     * will try recovering system apps by wiping data; third-party app data is
22451     * left intact.
22452     */
22453    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22454        if (pkg == null) {
22455            Slog.wtf(TAG, "Package was null!", new Throwable());
22456            return;
22457        }
22458        prepareAppDataLeafLIF(pkg, userId, flags);
22459        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22460        for (int i = 0; i < childCount; i++) {
22461            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22462        }
22463    }
22464
22465    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22466            boolean maybeMigrateAppData) {
22467        prepareAppDataLIF(pkg, userId, flags);
22468
22469        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22470            // We may have just shuffled around app data directories, so
22471            // prepare them one more time
22472            prepareAppDataLIF(pkg, userId, flags);
22473        }
22474    }
22475
22476    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22477        if (DEBUG_APP_DATA) {
22478            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22479                    + Integer.toHexString(flags));
22480        }
22481
22482        final String volumeUuid = pkg.volumeUuid;
22483        final String packageName = pkg.packageName;
22484        final ApplicationInfo app = pkg.applicationInfo;
22485        final int appId = UserHandle.getAppId(app.uid);
22486
22487        Preconditions.checkNotNull(app.seInfo);
22488
22489        long ceDataInode = -1;
22490        try {
22491            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22492                    appId, app.seInfo, app.targetSdkVersion);
22493        } catch (InstallerException e) {
22494            if (app.isSystemApp()) {
22495                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22496                        + ", but trying to recover: " + e);
22497                destroyAppDataLeafLIF(pkg, userId, flags);
22498                try {
22499                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22500                            appId, app.seInfo, app.targetSdkVersion);
22501                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22502                } catch (InstallerException e2) {
22503                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22504                }
22505            } else {
22506                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22507            }
22508        }
22509
22510        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22511            // TODO: mark this structure as dirty so we persist it!
22512            synchronized (mPackages) {
22513                final PackageSetting ps = mSettings.mPackages.get(packageName);
22514                if (ps != null) {
22515                    ps.setCeDataInode(ceDataInode, userId);
22516                }
22517            }
22518        }
22519
22520        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22521    }
22522
22523    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22524        if (pkg == null) {
22525            Slog.wtf(TAG, "Package was null!", new Throwable());
22526            return;
22527        }
22528        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22529        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22530        for (int i = 0; i < childCount; i++) {
22531            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22532        }
22533    }
22534
22535    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22536        final String volumeUuid = pkg.volumeUuid;
22537        final String packageName = pkg.packageName;
22538        final ApplicationInfo app = pkg.applicationInfo;
22539
22540        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22541            // Create a native library symlink only if we have native libraries
22542            // and if the native libraries are 32 bit libraries. We do not provide
22543            // this symlink for 64 bit libraries.
22544            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22545                final String nativeLibPath = app.nativeLibraryDir;
22546                try {
22547                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22548                            nativeLibPath, userId);
22549                } catch (InstallerException e) {
22550                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22551                }
22552            }
22553        }
22554    }
22555
22556    /**
22557     * For system apps on non-FBE devices, this method migrates any existing
22558     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22559     * requested by the app.
22560     */
22561    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22562        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22563                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22564            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22565                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22566            try {
22567                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22568                        storageTarget);
22569            } catch (InstallerException e) {
22570                logCriticalInfo(Log.WARN,
22571                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22572            }
22573            return true;
22574        } else {
22575            return false;
22576        }
22577    }
22578
22579    public PackageFreezer freezePackage(String packageName, String killReason) {
22580        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22581    }
22582
22583    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22584        return new PackageFreezer(packageName, userId, killReason);
22585    }
22586
22587    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22588            String killReason) {
22589        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22590    }
22591
22592    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22593            String killReason) {
22594        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22595            return new PackageFreezer();
22596        } else {
22597            return freezePackage(packageName, userId, killReason);
22598        }
22599    }
22600
22601    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22602            String killReason) {
22603        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22604    }
22605
22606    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22607            String killReason) {
22608        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22609            return new PackageFreezer();
22610        } else {
22611            return freezePackage(packageName, userId, killReason);
22612        }
22613    }
22614
22615    /**
22616     * Class that freezes and kills the given package upon creation, and
22617     * unfreezes it upon closing. This is typically used when doing surgery on
22618     * app code/data to prevent the app from running while you're working.
22619     */
22620    private class PackageFreezer implements AutoCloseable {
22621        private final String mPackageName;
22622        private final PackageFreezer[] mChildren;
22623
22624        private final boolean mWeFroze;
22625
22626        private final AtomicBoolean mClosed = new AtomicBoolean();
22627        private final CloseGuard mCloseGuard = CloseGuard.get();
22628
22629        /**
22630         * Create and return a stub freezer that doesn't actually do anything,
22631         * typically used when someone requested
22632         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22633         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22634         */
22635        public PackageFreezer() {
22636            mPackageName = null;
22637            mChildren = null;
22638            mWeFroze = false;
22639            mCloseGuard.open("close");
22640        }
22641
22642        public PackageFreezer(String packageName, int userId, String killReason) {
22643            synchronized (mPackages) {
22644                mPackageName = packageName;
22645                mWeFroze = mFrozenPackages.add(mPackageName);
22646
22647                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22648                if (ps != null) {
22649                    killApplication(ps.name, ps.appId, userId, killReason);
22650                }
22651
22652                final PackageParser.Package p = mPackages.get(packageName);
22653                if (p != null && p.childPackages != null) {
22654                    final int N = p.childPackages.size();
22655                    mChildren = new PackageFreezer[N];
22656                    for (int i = 0; i < N; i++) {
22657                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22658                                userId, killReason);
22659                    }
22660                } else {
22661                    mChildren = null;
22662                }
22663            }
22664            mCloseGuard.open("close");
22665        }
22666
22667        @Override
22668        protected void finalize() throws Throwable {
22669            try {
22670                mCloseGuard.warnIfOpen();
22671                close();
22672            } finally {
22673                super.finalize();
22674            }
22675        }
22676
22677        @Override
22678        public void close() {
22679            mCloseGuard.close();
22680            if (mClosed.compareAndSet(false, true)) {
22681                synchronized (mPackages) {
22682                    if (mWeFroze) {
22683                        mFrozenPackages.remove(mPackageName);
22684                    }
22685
22686                    if (mChildren != null) {
22687                        for (PackageFreezer freezer : mChildren) {
22688                            freezer.close();
22689                        }
22690                    }
22691                }
22692            }
22693        }
22694    }
22695
22696    /**
22697     * Verify that given package is currently frozen.
22698     */
22699    private void checkPackageFrozen(String packageName) {
22700        synchronized (mPackages) {
22701            if (!mFrozenPackages.contains(packageName)) {
22702                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22703            }
22704        }
22705    }
22706
22707    @Override
22708    public int movePackage(final String packageName, final String volumeUuid) {
22709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22710
22711        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22712        final int moveId = mNextMoveId.getAndIncrement();
22713        mHandler.post(new Runnable() {
22714            @Override
22715            public void run() {
22716                try {
22717                    movePackageInternal(packageName, volumeUuid, moveId, user);
22718                } catch (PackageManagerException e) {
22719                    Slog.w(TAG, "Failed to move " + packageName, e);
22720                    mMoveCallbacks.notifyStatusChanged(moveId,
22721                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22722                }
22723            }
22724        });
22725        return moveId;
22726    }
22727
22728    private void movePackageInternal(final String packageName, final String volumeUuid,
22729            final int moveId, UserHandle user) throws PackageManagerException {
22730        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22731        final PackageManager pm = mContext.getPackageManager();
22732
22733        final boolean currentAsec;
22734        final String currentVolumeUuid;
22735        final File codeFile;
22736        final String installerPackageName;
22737        final String packageAbiOverride;
22738        final int appId;
22739        final String seinfo;
22740        final String label;
22741        final int targetSdkVersion;
22742        final PackageFreezer freezer;
22743        final int[] installedUserIds;
22744
22745        // reader
22746        synchronized (mPackages) {
22747            final PackageParser.Package pkg = mPackages.get(packageName);
22748            final PackageSetting ps = mSettings.mPackages.get(packageName);
22749            if (pkg == null || ps == null) {
22750                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22751            }
22752
22753            if (pkg.applicationInfo.isSystemApp()) {
22754                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22755                        "Cannot move system application");
22756            }
22757
22758            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22759            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22760                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22761            if (isInternalStorage && !allow3rdPartyOnInternal) {
22762                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22763                        "3rd party apps are not allowed on internal storage");
22764            }
22765
22766            if (pkg.applicationInfo.isExternalAsec()) {
22767                currentAsec = true;
22768                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22769            } else if (pkg.applicationInfo.isForwardLocked()) {
22770                currentAsec = true;
22771                currentVolumeUuid = "forward_locked";
22772            } else {
22773                currentAsec = false;
22774                currentVolumeUuid = ps.volumeUuid;
22775
22776                final File probe = new File(pkg.codePath);
22777                final File probeOat = new File(probe, "oat");
22778                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22779                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22780                            "Move only supported for modern cluster style installs");
22781                }
22782            }
22783
22784            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22785                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22786                        "Package already moved to " + volumeUuid);
22787            }
22788            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22789                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22790                        "Device admin cannot be moved");
22791            }
22792
22793            if (mFrozenPackages.contains(packageName)) {
22794                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22795                        "Failed to move already frozen package");
22796            }
22797
22798            codeFile = new File(pkg.codePath);
22799            installerPackageName = ps.installerPackageName;
22800            packageAbiOverride = ps.cpuAbiOverrideString;
22801            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22802            seinfo = pkg.applicationInfo.seInfo;
22803            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22804            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22805            freezer = freezePackage(packageName, "movePackageInternal");
22806            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22807        }
22808
22809        final Bundle extras = new Bundle();
22810        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22811        extras.putString(Intent.EXTRA_TITLE, label);
22812        mMoveCallbacks.notifyCreated(moveId, extras);
22813
22814        int installFlags;
22815        final boolean moveCompleteApp;
22816        final File measurePath;
22817
22818        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22819            installFlags = INSTALL_INTERNAL;
22820            moveCompleteApp = !currentAsec;
22821            measurePath = Environment.getDataAppDirectory(volumeUuid);
22822        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22823            installFlags = INSTALL_EXTERNAL;
22824            moveCompleteApp = false;
22825            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22826        } else {
22827            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22828            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22829                    || !volume.isMountedWritable()) {
22830                freezer.close();
22831                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22832                        "Move location not mounted private volume");
22833            }
22834
22835            Preconditions.checkState(!currentAsec);
22836
22837            installFlags = INSTALL_INTERNAL;
22838            moveCompleteApp = true;
22839            measurePath = Environment.getDataAppDirectory(volumeUuid);
22840        }
22841
22842        final PackageStats stats = new PackageStats(null, -1);
22843        synchronized (mInstaller) {
22844            for (int userId : installedUserIds) {
22845                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22846                    freezer.close();
22847                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22848                            "Failed to measure package size");
22849                }
22850            }
22851        }
22852
22853        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22854                + stats.dataSize);
22855
22856        final long startFreeBytes = measurePath.getUsableSpace();
22857        final long sizeBytes;
22858        if (moveCompleteApp) {
22859            sizeBytes = stats.codeSize + stats.dataSize;
22860        } else {
22861            sizeBytes = stats.codeSize;
22862        }
22863
22864        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22865            freezer.close();
22866            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22867                    "Not enough free space to move");
22868        }
22869
22870        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22871
22872        final CountDownLatch installedLatch = new CountDownLatch(1);
22873        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22874            @Override
22875            public void onUserActionRequired(Intent intent) throws RemoteException {
22876                throw new IllegalStateException();
22877            }
22878
22879            @Override
22880            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22881                    Bundle extras) throws RemoteException {
22882                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22883                        + PackageManager.installStatusToString(returnCode, msg));
22884
22885                installedLatch.countDown();
22886                freezer.close();
22887
22888                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22889                switch (status) {
22890                    case PackageInstaller.STATUS_SUCCESS:
22891                        mMoveCallbacks.notifyStatusChanged(moveId,
22892                                PackageManager.MOVE_SUCCEEDED);
22893                        break;
22894                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22895                        mMoveCallbacks.notifyStatusChanged(moveId,
22896                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22897                        break;
22898                    default:
22899                        mMoveCallbacks.notifyStatusChanged(moveId,
22900                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22901                        break;
22902                }
22903            }
22904        };
22905
22906        final MoveInfo move;
22907        if (moveCompleteApp) {
22908            // Kick off a thread to report progress estimates
22909            new Thread() {
22910                @Override
22911                public void run() {
22912                    while (true) {
22913                        try {
22914                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22915                                break;
22916                            }
22917                        } catch (InterruptedException ignored) {
22918                        }
22919
22920                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22921                        final int progress = 10 + (int) MathUtils.constrain(
22922                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22923                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22924                    }
22925                }
22926            }.start();
22927
22928            final String dataAppName = codeFile.getName();
22929            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22930                    dataAppName, appId, seinfo, targetSdkVersion);
22931        } else {
22932            move = null;
22933        }
22934
22935        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22936
22937        final Message msg = mHandler.obtainMessage(INIT_COPY);
22938        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22939        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22940                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22941                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22942                PackageManager.INSTALL_REASON_UNKNOWN);
22943        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22944        msg.obj = params;
22945
22946        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22947                System.identityHashCode(msg.obj));
22948        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22949                System.identityHashCode(msg.obj));
22950
22951        mHandler.sendMessage(msg);
22952    }
22953
22954    @Override
22955    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22956        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22957
22958        final int realMoveId = mNextMoveId.getAndIncrement();
22959        final Bundle extras = new Bundle();
22960        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22961        mMoveCallbacks.notifyCreated(realMoveId, extras);
22962
22963        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22964            @Override
22965            public void onCreated(int moveId, Bundle extras) {
22966                // Ignored
22967            }
22968
22969            @Override
22970            public void onStatusChanged(int moveId, int status, long estMillis) {
22971                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22972            }
22973        };
22974
22975        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22976        storage.setPrimaryStorageUuid(volumeUuid, callback);
22977        return realMoveId;
22978    }
22979
22980    @Override
22981    public int getMoveStatus(int moveId) {
22982        mContext.enforceCallingOrSelfPermission(
22983                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22984        return mMoveCallbacks.mLastStatus.get(moveId);
22985    }
22986
22987    @Override
22988    public void registerMoveCallback(IPackageMoveObserver callback) {
22989        mContext.enforceCallingOrSelfPermission(
22990                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22991        mMoveCallbacks.register(callback);
22992    }
22993
22994    @Override
22995    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22996        mContext.enforceCallingOrSelfPermission(
22997                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22998        mMoveCallbacks.unregister(callback);
22999    }
23000
23001    @Override
23002    public boolean setInstallLocation(int loc) {
23003        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23004                null);
23005        if (getInstallLocation() == loc) {
23006            return true;
23007        }
23008        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23009                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23010            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23011                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23012            return true;
23013        }
23014        return false;
23015   }
23016
23017    @Override
23018    public int getInstallLocation() {
23019        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23020                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23021                PackageHelper.APP_INSTALL_AUTO);
23022    }
23023
23024    /** Called by UserManagerService */
23025    void cleanUpUser(UserManagerService userManager, int userHandle) {
23026        synchronized (mPackages) {
23027            mDirtyUsers.remove(userHandle);
23028            mUserNeedsBadging.delete(userHandle);
23029            mSettings.removeUserLPw(userHandle);
23030            mPendingBroadcasts.remove(userHandle);
23031            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23032            removeUnusedPackagesLPw(userManager, userHandle);
23033        }
23034    }
23035
23036    /**
23037     * We're removing userHandle and would like to remove any downloaded packages
23038     * that are no longer in use by any other user.
23039     * @param userHandle the user being removed
23040     */
23041    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23042        final boolean DEBUG_CLEAN_APKS = false;
23043        int [] users = userManager.getUserIds();
23044        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23045        while (psit.hasNext()) {
23046            PackageSetting ps = psit.next();
23047            if (ps.pkg == null) {
23048                continue;
23049            }
23050            final String packageName = ps.pkg.packageName;
23051            // Skip over if system app
23052            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23053                continue;
23054            }
23055            if (DEBUG_CLEAN_APKS) {
23056                Slog.i(TAG, "Checking package " + packageName);
23057            }
23058            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23059            if (keep) {
23060                if (DEBUG_CLEAN_APKS) {
23061                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23062                }
23063            } else {
23064                for (int i = 0; i < users.length; i++) {
23065                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23066                        keep = true;
23067                        if (DEBUG_CLEAN_APKS) {
23068                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23069                                    + users[i]);
23070                        }
23071                        break;
23072                    }
23073                }
23074            }
23075            if (!keep) {
23076                if (DEBUG_CLEAN_APKS) {
23077                    Slog.i(TAG, "  Removing package " + packageName);
23078                }
23079                mHandler.post(new Runnable() {
23080                    public void run() {
23081                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23082                                userHandle, 0);
23083                    } //end run
23084                });
23085            }
23086        }
23087    }
23088
23089    /** Called by UserManagerService */
23090    void createNewUser(int userId, String[] disallowedPackages) {
23091        synchronized (mInstallLock) {
23092            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23093        }
23094        synchronized (mPackages) {
23095            scheduleWritePackageRestrictionsLocked(userId);
23096            scheduleWritePackageListLocked(userId);
23097            applyFactoryDefaultBrowserLPw(userId);
23098            primeDomainVerificationsLPw(userId);
23099        }
23100    }
23101
23102    void onNewUserCreated(final int userId) {
23103        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23104        // If permission review for legacy apps is required, we represent
23105        // dagerous permissions for such apps as always granted runtime
23106        // permissions to keep per user flag state whether review is needed.
23107        // Hence, if a new user is added we have to propagate dangerous
23108        // permission grants for these legacy apps.
23109        if (mPermissionReviewRequired) {
23110            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23111                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23112        }
23113    }
23114
23115    @Override
23116    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23117        mContext.enforceCallingOrSelfPermission(
23118                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23119                "Only package verification agents can read the verifier device identity");
23120
23121        synchronized (mPackages) {
23122            return mSettings.getVerifierDeviceIdentityLPw();
23123        }
23124    }
23125
23126    @Override
23127    public void setPermissionEnforced(String permission, boolean enforced) {
23128        // TODO: Now that we no longer change GID for storage, this should to away.
23129        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23130                "setPermissionEnforced");
23131        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23132            synchronized (mPackages) {
23133                if (mSettings.mReadExternalStorageEnforced == null
23134                        || mSettings.mReadExternalStorageEnforced != enforced) {
23135                    mSettings.mReadExternalStorageEnforced = enforced;
23136                    mSettings.writeLPr();
23137                }
23138            }
23139            // kill any non-foreground processes so we restart them and
23140            // grant/revoke the GID.
23141            final IActivityManager am = ActivityManager.getService();
23142            if (am != null) {
23143                final long token = Binder.clearCallingIdentity();
23144                try {
23145                    am.killProcessesBelowForeground("setPermissionEnforcement");
23146                } catch (RemoteException e) {
23147                } finally {
23148                    Binder.restoreCallingIdentity(token);
23149                }
23150            }
23151        } else {
23152            throw new IllegalArgumentException("No selective enforcement for " + permission);
23153        }
23154    }
23155
23156    @Override
23157    @Deprecated
23158    public boolean isPermissionEnforced(String permission) {
23159        return true;
23160    }
23161
23162    @Override
23163    public boolean isStorageLow() {
23164        final long token = Binder.clearCallingIdentity();
23165        try {
23166            final DeviceStorageMonitorInternal
23167                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23168            if (dsm != null) {
23169                return dsm.isMemoryLow();
23170            } else {
23171                return false;
23172            }
23173        } finally {
23174            Binder.restoreCallingIdentity(token);
23175        }
23176    }
23177
23178    @Override
23179    public IPackageInstaller getPackageInstaller() {
23180        return mInstallerService;
23181    }
23182
23183    private boolean userNeedsBadging(int userId) {
23184        int index = mUserNeedsBadging.indexOfKey(userId);
23185        if (index < 0) {
23186            final UserInfo userInfo;
23187            final long token = Binder.clearCallingIdentity();
23188            try {
23189                userInfo = sUserManager.getUserInfo(userId);
23190            } finally {
23191                Binder.restoreCallingIdentity(token);
23192            }
23193            final boolean b;
23194            if (userInfo != null && userInfo.isManagedProfile()) {
23195                b = true;
23196            } else {
23197                b = false;
23198            }
23199            mUserNeedsBadging.put(userId, b);
23200            return b;
23201        }
23202        return mUserNeedsBadging.valueAt(index);
23203    }
23204
23205    @Override
23206    public KeySet getKeySetByAlias(String packageName, String alias) {
23207        if (packageName == null || alias == null) {
23208            return null;
23209        }
23210        synchronized(mPackages) {
23211            final PackageParser.Package pkg = mPackages.get(packageName);
23212            if (pkg == null) {
23213                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23214                throw new IllegalArgumentException("Unknown package: " + packageName);
23215            }
23216            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23217            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23218        }
23219    }
23220
23221    @Override
23222    public KeySet getSigningKeySet(String packageName) {
23223        if (packageName == null) {
23224            return null;
23225        }
23226        synchronized(mPackages) {
23227            final PackageParser.Package pkg = mPackages.get(packageName);
23228            if (pkg == null) {
23229                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23230                throw new IllegalArgumentException("Unknown package: " + packageName);
23231            }
23232            if (pkg.applicationInfo.uid != Binder.getCallingUid()
23233                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
23234                throw new SecurityException("May not access signing KeySet of other apps.");
23235            }
23236            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23237            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23238        }
23239    }
23240
23241    @Override
23242    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23243        if (packageName == null || ks == null) {
23244            return false;
23245        }
23246        synchronized(mPackages) {
23247            final PackageParser.Package pkg = mPackages.get(packageName);
23248            if (pkg == null) {
23249                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23250                throw new IllegalArgumentException("Unknown package: " + packageName);
23251            }
23252            IBinder ksh = ks.getToken();
23253            if (ksh instanceof KeySetHandle) {
23254                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23255                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23256            }
23257            return false;
23258        }
23259    }
23260
23261    @Override
23262    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23263        if (packageName == null || ks == null) {
23264            return false;
23265        }
23266        synchronized(mPackages) {
23267            final PackageParser.Package pkg = mPackages.get(packageName);
23268            if (pkg == null) {
23269                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23270                throw new IllegalArgumentException("Unknown package: " + packageName);
23271            }
23272            IBinder ksh = ks.getToken();
23273            if (ksh instanceof KeySetHandle) {
23274                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23275                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23276            }
23277            return false;
23278        }
23279    }
23280
23281    private void deletePackageIfUnusedLPr(final String packageName) {
23282        PackageSetting ps = mSettings.mPackages.get(packageName);
23283        if (ps == null) {
23284            return;
23285        }
23286        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23287            // TODO Implement atomic delete if package is unused
23288            // It is currently possible that the package will be deleted even if it is installed
23289            // after this method returns.
23290            mHandler.post(new Runnable() {
23291                public void run() {
23292                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23293                            0, PackageManager.DELETE_ALL_USERS);
23294                }
23295            });
23296        }
23297    }
23298
23299    /**
23300     * Check and throw if the given before/after packages would be considered a
23301     * downgrade.
23302     */
23303    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23304            throws PackageManagerException {
23305        if (after.versionCode < before.mVersionCode) {
23306            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23307                    "Update version code " + after.versionCode + " is older than current "
23308                    + before.mVersionCode);
23309        } else if (after.versionCode == before.mVersionCode) {
23310            if (after.baseRevisionCode < before.baseRevisionCode) {
23311                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23312                        "Update base revision code " + after.baseRevisionCode
23313                        + " is older than current " + before.baseRevisionCode);
23314            }
23315
23316            if (!ArrayUtils.isEmpty(after.splitNames)) {
23317                for (int i = 0; i < after.splitNames.length; i++) {
23318                    final String splitName = after.splitNames[i];
23319                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23320                    if (j != -1) {
23321                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23322                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23323                                    "Update split " + splitName + " revision code "
23324                                    + after.splitRevisionCodes[i] + " is older than current "
23325                                    + before.splitRevisionCodes[j]);
23326                        }
23327                    }
23328                }
23329            }
23330        }
23331    }
23332
23333    private static class MoveCallbacks extends Handler {
23334        private static final int MSG_CREATED = 1;
23335        private static final int MSG_STATUS_CHANGED = 2;
23336
23337        private final RemoteCallbackList<IPackageMoveObserver>
23338                mCallbacks = new RemoteCallbackList<>();
23339
23340        private final SparseIntArray mLastStatus = new SparseIntArray();
23341
23342        public MoveCallbacks(Looper looper) {
23343            super(looper);
23344        }
23345
23346        public void register(IPackageMoveObserver callback) {
23347            mCallbacks.register(callback);
23348        }
23349
23350        public void unregister(IPackageMoveObserver callback) {
23351            mCallbacks.unregister(callback);
23352        }
23353
23354        @Override
23355        public void handleMessage(Message msg) {
23356            final SomeArgs args = (SomeArgs) msg.obj;
23357            final int n = mCallbacks.beginBroadcast();
23358            for (int i = 0; i < n; i++) {
23359                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23360                try {
23361                    invokeCallback(callback, msg.what, args);
23362                } catch (RemoteException ignored) {
23363                }
23364            }
23365            mCallbacks.finishBroadcast();
23366            args.recycle();
23367        }
23368
23369        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23370                throws RemoteException {
23371            switch (what) {
23372                case MSG_CREATED: {
23373                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23374                    break;
23375                }
23376                case MSG_STATUS_CHANGED: {
23377                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23378                    break;
23379                }
23380            }
23381        }
23382
23383        private void notifyCreated(int moveId, Bundle extras) {
23384            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23385
23386            final SomeArgs args = SomeArgs.obtain();
23387            args.argi1 = moveId;
23388            args.arg2 = extras;
23389            obtainMessage(MSG_CREATED, args).sendToTarget();
23390        }
23391
23392        private void notifyStatusChanged(int moveId, int status) {
23393            notifyStatusChanged(moveId, status, -1);
23394        }
23395
23396        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23397            Slog.v(TAG, "Move " + moveId + " status " + status);
23398
23399            final SomeArgs args = SomeArgs.obtain();
23400            args.argi1 = moveId;
23401            args.argi2 = status;
23402            args.arg3 = estMillis;
23403            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23404
23405            synchronized (mLastStatus) {
23406                mLastStatus.put(moveId, status);
23407            }
23408        }
23409    }
23410
23411    private final static class OnPermissionChangeListeners extends Handler {
23412        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23413
23414        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23415                new RemoteCallbackList<>();
23416
23417        public OnPermissionChangeListeners(Looper looper) {
23418            super(looper);
23419        }
23420
23421        @Override
23422        public void handleMessage(Message msg) {
23423            switch (msg.what) {
23424                case MSG_ON_PERMISSIONS_CHANGED: {
23425                    final int uid = msg.arg1;
23426                    handleOnPermissionsChanged(uid);
23427                } break;
23428            }
23429        }
23430
23431        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23432            mPermissionListeners.register(listener);
23433
23434        }
23435
23436        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23437            mPermissionListeners.unregister(listener);
23438        }
23439
23440        public void onPermissionsChanged(int uid) {
23441            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23442                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23443            }
23444        }
23445
23446        private void handleOnPermissionsChanged(int uid) {
23447            final int count = mPermissionListeners.beginBroadcast();
23448            try {
23449                for (int i = 0; i < count; i++) {
23450                    IOnPermissionsChangeListener callback = mPermissionListeners
23451                            .getBroadcastItem(i);
23452                    try {
23453                        callback.onPermissionsChanged(uid);
23454                    } catch (RemoteException e) {
23455                        Log.e(TAG, "Permission listener is dead", e);
23456                    }
23457                }
23458            } finally {
23459                mPermissionListeners.finishBroadcast();
23460            }
23461        }
23462    }
23463
23464    private class PackageManagerInternalImpl extends PackageManagerInternal {
23465        @Override
23466        public void setLocationPackagesProvider(PackagesProvider provider) {
23467            synchronized (mPackages) {
23468                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23469            }
23470        }
23471
23472        @Override
23473        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23474            synchronized (mPackages) {
23475                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23476            }
23477        }
23478
23479        @Override
23480        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23481            synchronized (mPackages) {
23482                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23483            }
23484        }
23485
23486        @Override
23487        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23488            synchronized (mPackages) {
23489                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23490            }
23491        }
23492
23493        @Override
23494        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23495            synchronized (mPackages) {
23496                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23497            }
23498        }
23499
23500        @Override
23501        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23502            synchronized (mPackages) {
23503                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23504            }
23505        }
23506
23507        @Override
23508        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23509            synchronized (mPackages) {
23510                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23511                        packageName, userId);
23512            }
23513        }
23514
23515        @Override
23516        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23517            synchronized (mPackages) {
23518                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23519                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23520                        packageName, userId);
23521            }
23522        }
23523
23524        @Override
23525        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23526            synchronized (mPackages) {
23527                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23528                        packageName, userId);
23529            }
23530        }
23531
23532        @Override
23533        public void setKeepUninstalledPackages(final List<String> packageList) {
23534            Preconditions.checkNotNull(packageList);
23535            List<String> removedFromList = null;
23536            synchronized (mPackages) {
23537                if (mKeepUninstalledPackages != null) {
23538                    final int packagesCount = mKeepUninstalledPackages.size();
23539                    for (int i = 0; i < packagesCount; i++) {
23540                        String oldPackage = mKeepUninstalledPackages.get(i);
23541                        if (packageList != null && packageList.contains(oldPackage)) {
23542                            continue;
23543                        }
23544                        if (removedFromList == null) {
23545                            removedFromList = new ArrayList<>();
23546                        }
23547                        removedFromList.add(oldPackage);
23548                    }
23549                }
23550                mKeepUninstalledPackages = new ArrayList<>(packageList);
23551                if (removedFromList != null) {
23552                    final int removedCount = removedFromList.size();
23553                    for (int i = 0; i < removedCount; i++) {
23554                        deletePackageIfUnusedLPr(removedFromList.get(i));
23555                    }
23556                }
23557            }
23558        }
23559
23560        @Override
23561        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23562            synchronized (mPackages) {
23563                // If we do not support permission review, done.
23564                if (!mPermissionReviewRequired) {
23565                    return false;
23566                }
23567
23568                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23569                if (packageSetting == null) {
23570                    return false;
23571                }
23572
23573                // Permission review applies only to apps not supporting the new permission model.
23574                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23575                    return false;
23576                }
23577
23578                // Legacy apps have the permission and get user consent on launch.
23579                PermissionsState permissionsState = packageSetting.getPermissionsState();
23580                return permissionsState.isPermissionReviewRequired(userId);
23581            }
23582        }
23583
23584        @Override
23585        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23586            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23587        }
23588
23589        @Override
23590        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23591                int userId) {
23592            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23593        }
23594
23595        @Override
23596        public void setDeviceAndProfileOwnerPackages(
23597                int deviceOwnerUserId, String deviceOwnerPackage,
23598                SparseArray<String> profileOwnerPackages) {
23599            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23600                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23601        }
23602
23603        @Override
23604        public boolean isPackageDataProtected(int userId, String packageName) {
23605            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23606        }
23607
23608        @Override
23609        public boolean isPackageEphemeral(int userId, String packageName) {
23610            synchronized (mPackages) {
23611                final PackageSetting ps = mSettings.mPackages.get(packageName);
23612                return ps != null ? ps.getInstantApp(userId) : false;
23613            }
23614        }
23615
23616        @Override
23617        public boolean wasPackageEverLaunched(String packageName, int userId) {
23618            synchronized (mPackages) {
23619                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23620            }
23621        }
23622
23623        @Override
23624        public void grantRuntimePermission(String packageName, String name, int userId,
23625                boolean overridePolicy) {
23626            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23627                    overridePolicy);
23628        }
23629
23630        @Override
23631        public void revokeRuntimePermission(String packageName, String name, int userId,
23632                boolean overridePolicy) {
23633            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23634                    overridePolicy);
23635        }
23636
23637        @Override
23638        public String getNameForUid(int uid) {
23639            return PackageManagerService.this.getNameForUid(uid);
23640        }
23641
23642        @Override
23643        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23644                Intent origIntent, String resolvedType, String callingPackage,
23645                Bundle verificationBundle, int userId) {
23646            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23647                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23648                    userId);
23649        }
23650
23651        @Override
23652        public void grantEphemeralAccess(int userId, Intent intent,
23653                int targetAppId, int ephemeralAppId) {
23654            synchronized (mPackages) {
23655                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23656                        targetAppId, ephemeralAppId);
23657            }
23658        }
23659
23660        @Override
23661        public boolean isInstantAppInstallerComponent(ComponentName component) {
23662            synchronized (mPackages) {
23663                return mInstantAppInstallerActivity != null
23664                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23665            }
23666        }
23667
23668        @Override
23669        public void pruneInstantApps() {
23670            synchronized (mPackages) {
23671                mInstantAppRegistry.pruneInstantAppsLPw();
23672            }
23673        }
23674
23675        @Override
23676        public String getSetupWizardPackageName() {
23677            return mSetupWizardPackage;
23678        }
23679
23680        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23681            if (policy != null) {
23682                mExternalSourcesPolicy = policy;
23683            }
23684        }
23685
23686        @Override
23687        public boolean isPackagePersistent(String packageName) {
23688            synchronized (mPackages) {
23689                PackageParser.Package pkg = mPackages.get(packageName);
23690                return pkg != null
23691                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23692                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23693                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23694                        : false;
23695            }
23696        }
23697
23698        @Override
23699        public List<PackageInfo> getOverlayPackages(int userId) {
23700            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23701            synchronized (mPackages) {
23702                for (PackageParser.Package p : mPackages.values()) {
23703                    if (p.mOverlayTarget != null) {
23704                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23705                        if (pkg != null) {
23706                            overlayPackages.add(pkg);
23707                        }
23708                    }
23709                }
23710            }
23711            return overlayPackages;
23712        }
23713
23714        @Override
23715        public List<String> getTargetPackageNames(int userId) {
23716            List<String> targetPackages = new ArrayList<>();
23717            synchronized (mPackages) {
23718                for (PackageParser.Package p : mPackages.values()) {
23719                    if (p.mOverlayTarget == null) {
23720                        targetPackages.add(p.packageName);
23721                    }
23722                }
23723            }
23724            return targetPackages;
23725        }
23726
23727        @Override
23728        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23729                @Nullable List<String> overlayPackageNames) {
23730            synchronized (mPackages) {
23731                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23732                    Slog.e(TAG, "failed to find package " + targetPackageName);
23733                    return false;
23734                }
23735
23736                ArrayList<String> paths = null;
23737                if (overlayPackageNames != null) {
23738                    final int N = overlayPackageNames.size();
23739                    paths = new ArrayList<>(N);
23740                    for (int i = 0; i < N; i++) {
23741                        final String packageName = overlayPackageNames.get(i);
23742                        final PackageParser.Package pkg = mPackages.get(packageName);
23743                        if (pkg == null) {
23744                            Slog.e(TAG, "failed to find package " + packageName);
23745                            return false;
23746                        }
23747                        paths.add(pkg.baseCodePath);
23748                    }
23749                }
23750
23751                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23752                    mEnabledOverlayPaths.get(userId);
23753                if (userSpecificOverlays == null) {
23754                    userSpecificOverlays = new ArrayMap<>();
23755                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23756                }
23757
23758                if (paths != null && paths.size() > 0) {
23759                    userSpecificOverlays.put(targetPackageName, paths);
23760                } else {
23761                    userSpecificOverlays.remove(targetPackageName);
23762                }
23763                return true;
23764            }
23765        }
23766
23767        @Override
23768        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23769                int flags, int userId) {
23770            return resolveIntentInternal(
23771                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
23772        }
23773
23774        @Override
23775        public ResolveInfo resolveService(Intent intent, String resolvedType,
23776                int flags, int userId, int callingUid) {
23777            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23778        }
23779
23780        @Override
23781        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23782            synchronized (mPackages) {
23783                mIsolatedOwners.put(isolatedUid, ownerUid);
23784            }
23785        }
23786
23787        @Override
23788        public void removeIsolatedUid(int isolatedUid) {
23789            synchronized (mPackages) {
23790                mIsolatedOwners.delete(isolatedUid);
23791            }
23792        }
23793
23794        @Override
23795        public int getUidTargetSdkVersion(int uid) {
23796            synchronized (mPackages) {
23797                return getUidTargetSdkVersionLockedLPr(uid);
23798            }
23799        }
23800    }
23801
23802    @Override
23803    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23804        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23805        synchronized (mPackages) {
23806            final long identity = Binder.clearCallingIdentity();
23807            try {
23808                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23809                        packageNames, userId);
23810            } finally {
23811                Binder.restoreCallingIdentity(identity);
23812            }
23813        }
23814    }
23815
23816    @Override
23817    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23818        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23819        synchronized (mPackages) {
23820            final long identity = Binder.clearCallingIdentity();
23821            try {
23822                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23823                        packageNames, userId);
23824            } finally {
23825                Binder.restoreCallingIdentity(identity);
23826            }
23827        }
23828    }
23829
23830    private static void enforceSystemOrPhoneCaller(String tag) {
23831        int callingUid = Binder.getCallingUid();
23832        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23833            throw new SecurityException(
23834                    "Cannot call " + tag + " from UID " + callingUid);
23835        }
23836    }
23837
23838    boolean isHistoricalPackageUsageAvailable() {
23839        return mPackageUsage.isHistoricalPackageUsageAvailable();
23840    }
23841
23842    /**
23843     * Return a <b>copy</b> of the collection of packages known to the package manager.
23844     * @return A copy of the values of mPackages.
23845     */
23846    Collection<PackageParser.Package> getPackages() {
23847        synchronized (mPackages) {
23848            return new ArrayList<>(mPackages.values());
23849        }
23850    }
23851
23852    /**
23853     * Logs process start information (including base APK hash) to the security log.
23854     * @hide
23855     */
23856    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23857            String apkFile, int pid) {
23858        if (!SecurityLog.isLoggingEnabled()) {
23859            return;
23860        }
23861        Bundle data = new Bundle();
23862        data.putLong("startTimestamp", System.currentTimeMillis());
23863        data.putString("processName", processName);
23864        data.putInt("uid", uid);
23865        data.putString("seinfo", seinfo);
23866        data.putString("apkFile", apkFile);
23867        data.putInt("pid", pid);
23868        Message msg = mProcessLoggingHandler.obtainMessage(
23869                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23870        msg.setData(data);
23871        mProcessLoggingHandler.sendMessage(msg);
23872    }
23873
23874    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23875        return mCompilerStats.getPackageStats(pkgName);
23876    }
23877
23878    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23879        return getOrCreateCompilerPackageStats(pkg.packageName);
23880    }
23881
23882    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23883        return mCompilerStats.getOrCreatePackageStats(pkgName);
23884    }
23885
23886    public void deleteCompilerPackageStats(String pkgName) {
23887        mCompilerStats.deletePackageStats(pkgName);
23888    }
23889
23890    @Override
23891    public int getInstallReason(String packageName, int userId) {
23892        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23893                true /* requireFullPermission */, false /* checkShell */,
23894                "get install reason");
23895        synchronized (mPackages) {
23896            final PackageSetting ps = mSettings.mPackages.get(packageName);
23897            if (ps != null) {
23898                return ps.getInstallReason(userId);
23899            }
23900        }
23901        return PackageManager.INSTALL_REASON_UNKNOWN;
23902    }
23903
23904    @Override
23905    public boolean canRequestPackageInstalls(String packageName, int userId) {
23906        int callingUid = Binder.getCallingUid();
23907        int uid = getPackageUid(packageName, 0, userId);
23908        if (callingUid != uid && callingUid != Process.ROOT_UID
23909                && callingUid != Process.SYSTEM_UID) {
23910            throw new SecurityException(
23911                    "Caller uid " + callingUid + " does not own package " + packageName);
23912        }
23913        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23914        if (info == null) {
23915            return false;
23916        }
23917        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23918            throw new UnsupportedOperationException(
23919                    "Operation only supported on apps targeting Android O or higher");
23920        }
23921        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23922        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23923        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23924            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23925        }
23926        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23927            return false;
23928        }
23929        if (mExternalSourcesPolicy != null) {
23930            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23931            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23932                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23933            }
23934        }
23935        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23936    }
23937
23938    @Override
23939    public ComponentName getInstantAppResolverSettingsComponent() {
23940        return mInstantAppResolverSettingsComponent;
23941    }
23942
23943    @Override
23944    public ComponentName getInstantAppInstallerComponent() {
23945        return mInstantAppInstallerActivity == null
23946                ? null : mInstantAppInstallerActivity.getComponentName();
23947    }
23948
23949    @Override
23950    public String getInstantAppAndroidId(String packageName, int userId) {
23951        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23952                "getInstantAppAndroidId");
23953        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23954                true /* requireFullPermission */, false /* checkShell */,
23955                "getInstantAppAndroidId");
23956        // Make sure the target is an Instant App.
23957        if (!isInstantApp(packageName, userId)) {
23958            return null;
23959        }
23960        synchronized (mPackages) {
23961            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23962        }
23963    }
23964}
23965
23966interface PackageSender {
23967    void sendPackageBroadcast(final String action, final String pkg,
23968        final Bundle extras, final int flags, final String targetPkg,
23969        final IIntentReceiver finishedReceiver, final int[] userIds);
23970    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
23971        int appId, int... userIds);
23972}
23973