PackageManagerService.java revision 336ae5b6161454304ef09be715505007c7a7da56
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.DeviceIdleController;
264import com.android.server.EventLogTags;
265import com.android.server.FgThread;
266import com.android.server.IntentResolver;
267import com.android.server.LocalServices;
268import com.android.server.LockGuard;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.BackgroundDexOptService;
275import com.android.server.pm.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
300import java.io.FileNotFoundException;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
398    private static final boolean DISABLE_EPHEMERAL_APPS = false;
399    private static final boolean HIDE_EPHEMERAL_APIS = false;
400
401    private static final boolean ENABLE_FREE_CACHE_V2 =
402            SystemProperties.getBoolean("fw.free_cache_v2", true);
403
404    private static final int RADIO_UID = Process.PHONE_UID;
405    private static final int LOG_UID = Process.LOG_UID;
406    private static final int NFC_UID = Process.NFC_UID;
407    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
408    private static final int SHELL_UID = Process.SHELL_UID;
409
410    // Cap the size of permission trees that 3rd party apps can define
411    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
412
413    // Suffix used during package installation when copying/moving
414    // package apks to install directory.
415    private static final String INSTALL_PACKAGE_SUFFIX = "-";
416
417    static final int SCAN_NO_DEX = 1<<1;
418    static final int SCAN_FORCE_DEX = 1<<2;
419    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
420    static final int SCAN_NEW_INSTALL = 1<<4;
421    static final int SCAN_UPDATE_TIME = 1<<5;
422    static final int SCAN_BOOTING = 1<<6;
423    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
424    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
425    static final int SCAN_REPLACING = 1<<9;
426    static final int SCAN_REQUIRE_KNOWN = 1<<10;
427    static final int SCAN_MOVE = 1<<11;
428    static final int SCAN_INITIAL = 1<<12;
429    static final int SCAN_CHECK_ONLY = 1<<13;
430    static final int SCAN_DONT_KILL_APP = 1<<14;
431    static final int SCAN_IGNORE_FROZEN = 1<<15;
432    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
433    static final int SCAN_AS_INSTANT_APP = 1<<17;
434    static final int SCAN_AS_FULL_APP = 1<<18;
435    /** Should not be with the scan flags */
436    static final int FLAGS_REMOVE_CHATTY = 1<<31;
437
438    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
439
440    private static final int[] EMPTY_INT_ARRAY = new int[0];
441
442    /**
443     * Timeout (in milliseconds) after which the watchdog should declare that
444     * our handler thread is wedged.  The usual default for such things is one
445     * minute but we sometimes do very lengthy I/O operations on this thread,
446     * such as installing multi-gigabyte applications, so ours needs to be longer.
447     */
448    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
449
450    /**
451     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
452     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
453     * settings entry if available, otherwise we use the hardcoded default.  If it's been
454     * more than this long since the last fstrim, we force one during the boot sequence.
455     *
456     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
457     * one gets run at the next available charging+idle time.  This final mandatory
458     * no-fstrim check kicks in only of the other scheduling criteria is never met.
459     */
460    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
461
462    /**
463     * Whether verification is enabled by default.
464     */
465    private static final boolean DEFAULT_VERIFY_ENABLE = true;
466
467    /**
468     * The default maximum time to wait for the verification agent to return in
469     * milliseconds.
470     */
471    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
472
473    /**
474     * The default response for package verification timeout.
475     *
476     * This can be either PackageManager.VERIFICATION_ALLOW or
477     * PackageManager.VERIFICATION_REJECT.
478     */
479    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
480
481    static final String PLATFORM_PACKAGE_NAME = "android";
482
483    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
484
485    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
486            DEFAULT_CONTAINER_PACKAGE,
487            "com.android.defcontainer.DefaultContainerService");
488
489    private static final String KILL_APP_REASON_GIDS_CHANGED =
490            "permission grant or revoke changed gids";
491
492    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
493            "permissions revoked";
494
495    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
496
497    private static final String PACKAGE_SCHEME = "package";
498
499    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
500
501    /** Permission grant: not grant the permission. */
502    private static final int GRANT_DENIED = 1;
503
504    /** Permission grant: grant the permission as an install permission. */
505    private static final int GRANT_INSTALL = 2;
506
507    /** Permission grant: grant the permission as a runtime one. */
508    private static final int GRANT_RUNTIME = 3;
509
510    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
511    private static final int GRANT_UPGRADE = 4;
512
513    /** Canonical intent used to identify what counts as a "web browser" app */
514    private static final Intent sBrowserIntent;
515    static {
516        sBrowserIntent = new Intent();
517        sBrowserIntent.setAction(Intent.ACTION_VIEW);
518        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
519        sBrowserIntent.setData(Uri.parse("http:"));
520    }
521
522    /**
523     * The set of all protected actions [i.e. those actions for which a high priority
524     * intent filter is disallowed].
525     */
526    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
527    static {
528        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
531        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
532    }
533
534    // Compilation reasons.
535    public static final int REASON_FIRST_BOOT = 0;
536    public static final int REASON_BOOT = 1;
537    public static final int REASON_INSTALL = 2;
538    public static final int REASON_BACKGROUND_DEXOPT = 3;
539    public static final int REASON_AB_OTA = 4;
540    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
541    public static final int REASON_SHARED_APK = 6;
542    public static final int REASON_FORCED_DEXOPT = 7;
543    public static final int REASON_CORE_APP = 8;
544
545    public static final int REASON_LAST = REASON_CORE_APP;
546
547    /** All dangerous permission names in the same order as the events in MetricsEvent */
548    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
549            Manifest.permission.READ_CALENDAR,
550            Manifest.permission.WRITE_CALENDAR,
551            Manifest.permission.CAMERA,
552            Manifest.permission.READ_CONTACTS,
553            Manifest.permission.WRITE_CONTACTS,
554            Manifest.permission.GET_ACCOUNTS,
555            Manifest.permission.ACCESS_FINE_LOCATION,
556            Manifest.permission.ACCESS_COARSE_LOCATION,
557            Manifest.permission.RECORD_AUDIO,
558            Manifest.permission.READ_PHONE_STATE,
559            Manifest.permission.CALL_PHONE,
560            Manifest.permission.READ_CALL_LOG,
561            Manifest.permission.WRITE_CALL_LOG,
562            Manifest.permission.ADD_VOICEMAIL,
563            Manifest.permission.USE_SIP,
564            Manifest.permission.PROCESS_OUTGOING_CALLS,
565            Manifest.permission.READ_CELL_BROADCASTS,
566            Manifest.permission.BODY_SENSORS,
567            Manifest.permission.SEND_SMS,
568            Manifest.permission.RECEIVE_SMS,
569            Manifest.permission.READ_SMS,
570            Manifest.permission.RECEIVE_WAP_PUSH,
571            Manifest.permission.RECEIVE_MMS,
572            Manifest.permission.READ_EXTERNAL_STORAGE,
573            Manifest.permission.WRITE_EXTERNAL_STORAGE,
574            Manifest.permission.READ_PHONE_NUMBER,
575            Manifest.permission.ANSWER_PHONE_CALLS);
576
577
578    /**
579     * Version number for the package parser cache. Increment this whenever the format or
580     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
581     */
582    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
583
584    /**
585     * Whether the package parser cache is enabled.
586     */
587    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
588
589    final ServiceThread mHandlerThread;
590
591    final PackageHandler mHandler;
592
593    private final ProcessLoggingHandler mProcessLoggingHandler;
594
595    /**
596     * Messages for {@link #mHandler} that need to wait for system ready before
597     * being dispatched.
598     */
599    private ArrayList<Message> mPostSystemReadyMessages;
600
601    final int mSdkVersion = Build.VERSION.SDK_INT;
602
603    final Context mContext;
604    final boolean mFactoryTest;
605    final boolean mOnlyCore;
606    final DisplayMetrics mMetrics;
607    final int mDefParseFlags;
608    final String[] mSeparateProcesses;
609    final boolean mIsUpgrade;
610    final boolean mIsPreNUpgrade;
611    final boolean mIsPreNMR1Upgrade;
612
613    @GuardedBy("mPackages")
614    private boolean mDexOptDialogShown;
615
616    /** The location for ASEC container files on internal storage. */
617    final String mAsecInternalPath;
618
619    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
620    // LOCK HELD.  Can be called with mInstallLock held.
621    @GuardedBy("mInstallLock")
622    final Installer mInstaller;
623
624    /** Directory where installed third-party apps stored */
625    final File mAppInstallDir;
626
627    /**
628     * Directory to which applications installed internally have their
629     * 32 bit native libraries copied.
630     */
631    private File mAppLib32InstallDir;
632
633    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
634    // apps.
635    final File mDrmAppPrivateInstallDir;
636
637    // ----------------------------------------------------------------
638
639    // Lock for state used when installing and doing other long running
640    // operations.  Methods that must be called with this lock held have
641    // the suffix "LI".
642    final Object mInstallLock = new Object();
643
644    // ----------------------------------------------------------------
645
646    // Keys are String (package name), values are Package.  This also serves
647    // as the lock for the global state.  Methods that must be called with
648    // this lock held have the prefix "LP".
649    @GuardedBy("mPackages")
650    final ArrayMap<String, PackageParser.Package> mPackages =
651            new ArrayMap<String, PackageParser.Package>();
652
653    final ArrayMap<String, Set<String>> mKnownCodebase =
654            new ArrayMap<String, Set<String>>();
655
656    // List of APK paths to load for each user and package. This data is never
657    // persisted by the package manager. Instead, the overlay manager will
658    // ensure the data is up-to-date in runtime.
659    @GuardedBy("mPackages")
660    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
661        new SparseArray<ArrayMap<String, ArrayList<String>>>();
662
663    /**
664     * Tracks new system packages [received in an OTA] that we expect to
665     * find updated user-installed versions. Keys are package name, values
666     * are package location.
667     */
668    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
669    /**
670     * Tracks high priority intent filters for protected actions. During boot, certain
671     * filter actions are protected and should never be allowed to have a high priority
672     * intent filter for them. However, there is one, and only one exception -- the
673     * setup wizard. It must be able to define a high priority intent filter for these
674     * actions to ensure there are no escapes from the wizard. We need to delay processing
675     * of these during boot as we need to look at all of the system packages in order
676     * to know which component is the setup wizard.
677     */
678    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
679    /**
680     * Whether or not processing protected filters should be deferred.
681     */
682    private boolean mDeferProtectedFilters = true;
683
684    /**
685     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
686     */
687    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
688    /**
689     * Whether or not system app permissions should be promoted from install to runtime.
690     */
691    boolean mPromoteSystemApps;
692
693    @GuardedBy("mPackages")
694    final Settings mSettings;
695
696    /**
697     * Set of package names that are currently "frozen", which means active
698     * surgery is being done on the code/data for that package. The platform
699     * will refuse to launch frozen packages to avoid race conditions.
700     *
701     * @see PackageFreezer
702     */
703    @GuardedBy("mPackages")
704    final ArraySet<String> mFrozenPackages = new ArraySet<>();
705
706    final ProtectedPackages mProtectedPackages;
707
708    boolean mFirstBoot;
709
710    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
711
712    // System configuration read by SystemConfig.
713    final int[] mGlobalGids;
714    final SparseArray<ArraySet<String>> mSystemPermissions;
715    @GuardedBy("mAvailableFeatures")
716    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
717
718    // If mac_permissions.xml was found for seinfo labeling.
719    boolean mFoundPolicyFile;
720
721    private final InstantAppRegistry mInstantAppRegistry;
722
723    @GuardedBy("mPackages")
724    int mChangedPackagesSequenceNumber;
725    /**
726     * List of changed [installed, removed or updated] packages.
727     * mapping from user id -> sequence number -> package name
728     */
729    @GuardedBy("mPackages")
730    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
731    /**
732     * The sequence number of the last change to a package.
733     * mapping from user id -> package name -> sequence number
734     */
735    @GuardedBy("mPackages")
736    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
737
738    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
739        @Override public boolean hasFeature(String feature) {
740            return PackageManagerService.this.hasSystemFeature(feature, 0);
741        }
742    };
743
744    public static final class SharedLibraryEntry {
745        public final String path;
746        public final String apk;
747        public final SharedLibraryInfo info;
748
749        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
750                String declaringPackageName, int declaringPackageVersionCode) {
751            path = _path;
752            apk = _apk;
753            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
754                    declaringPackageName, declaringPackageVersionCode), null);
755        }
756    }
757
758    // Currently known shared libraries.
759    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
760    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
761            new ArrayMap<>();
762
763    // All available activities, for your resolving pleasure.
764    final ActivityIntentResolver mActivities =
765            new ActivityIntentResolver();
766
767    // All available receivers, for your resolving pleasure.
768    final ActivityIntentResolver mReceivers =
769            new ActivityIntentResolver();
770
771    // All available services, for your resolving pleasure.
772    final ServiceIntentResolver mServices = new ServiceIntentResolver();
773
774    // All available providers, for your resolving pleasure.
775    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
776
777    // Mapping from provider base names (first directory in content URI codePath)
778    // to the provider information.
779    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
780            new ArrayMap<String, PackageParser.Provider>();
781
782    // Mapping from instrumentation class names to info about them.
783    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
784            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
785
786    // Mapping from permission names to info about them.
787    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
788            new ArrayMap<String, PackageParser.PermissionGroup>();
789
790    // Packages whose data we have transfered into another package, thus
791    // should no longer exist.
792    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
793
794    // Broadcast actions that are only available to the system.
795    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
796
797    /** List of packages waiting for verification. */
798    final SparseArray<PackageVerificationState> mPendingVerification
799            = new SparseArray<PackageVerificationState>();
800
801    /** Set of packages associated with each app op permission. */
802    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
803
804    final PackageInstallerService mInstallerService;
805
806    private final PackageDexOptimizer mPackageDexOptimizer;
807    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
808    // is used by other apps).
809    private final DexManager mDexManager;
810
811    private AtomicInteger mNextMoveId = new AtomicInteger();
812    private final MoveCallbacks mMoveCallbacks;
813
814    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
815
816    // Cache of users who need badging.
817    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
818
819    /** Token for keys in mPendingVerification. */
820    private int mPendingVerificationToken = 0;
821
822    volatile boolean mSystemReady;
823    volatile boolean mSafeMode;
824    volatile boolean mHasSystemUidErrors;
825
826    ApplicationInfo mAndroidApplication;
827    final ActivityInfo mResolveActivity = new ActivityInfo();
828    final ResolveInfo mResolveInfo = new ResolveInfo();
829    ComponentName mResolveComponentName;
830    PackageParser.Package mPlatformPackage;
831    ComponentName mCustomResolverComponentName;
832
833    boolean mResolverReplaced = false;
834
835    private final @Nullable ComponentName mIntentFilterVerifierComponent;
836    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
837
838    private int mIntentFilterVerificationToken = 0;
839
840    /** The service connection to the ephemeral resolver */
841    final EphemeralResolverConnection mInstantAppResolverConnection;
842
843    /** Component used to install ephemeral applications */
844    ComponentName mInstantAppInstallerComponent;
845    /** Component used to show resolver settings for Instant Apps */
846    ComponentName mInstantAppResolverSettingsComponent;
847    ActivityInfo mInstantAppInstallerActivity;
848    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
849
850    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
851            = new SparseArray<IntentFilterVerificationState>();
852
853    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
854
855    // List of packages names to keep cached, even if they are uninstalled for all users
856    private List<String> mKeepUninstalledPackages;
857
858    private UserManagerInternal mUserManagerInternal;
859
860    private DeviceIdleController.LocalService mDeviceIdleController;
861
862    private File mCacheDir;
863
864    private ArraySet<String> mPrivappPermissionsViolations;
865
866    private Future<?> mPrepareAppDataFuture;
867
868    private static class IFVerificationParams {
869        PackageParser.Package pkg;
870        boolean replacing;
871        int userId;
872        int verifierUid;
873
874        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
875                int _userId, int _verifierUid) {
876            pkg = _pkg;
877            replacing = _replacing;
878            userId = _userId;
879            replacing = _replacing;
880            verifierUid = _verifierUid;
881        }
882    }
883
884    private interface IntentFilterVerifier<T extends IntentFilter> {
885        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
886                                               T filter, String packageName);
887        void startVerifications(int userId);
888        void receiveVerificationResponse(int verificationId);
889    }
890
891    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
892        private Context mContext;
893        private ComponentName mIntentFilterVerifierComponent;
894        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
895
896        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
897            mContext = context;
898            mIntentFilterVerifierComponent = verifierComponent;
899        }
900
901        private String getDefaultScheme() {
902            return IntentFilter.SCHEME_HTTPS;
903        }
904
905        @Override
906        public void startVerifications(int userId) {
907            // Launch verifications requests
908            int count = mCurrentIntentFilterVerifications.size();
909            for (int n=0; n<count; n++) {
910                int verificationId = mCurrentIntentFilterVerifications.get(n);
911                final IntentFilterVerificationState ivs =
912                        mIntentFilterVerificationStates.get(verificationId);
913
914                String packageName = ivs.getPackageName();
915
916                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
917                final int filterCount = filters.size();
918                ArraySet<String> domainsSet = new ArraySet<>();
919                for (int m=0; m<filterCount; m++) {
920                    PackageParser.ActivityIntentInfo filter = filters.get(m);
921                    domainsSet.addAll(filter.getHostsList());
922                }
923                synchronized (mPackages) {
924                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
925                            packageName, domainsSet) != null) {
926                        scheduleWriteSettingsLocked();
927                    }
928                }
929                sendVerificationRequest(userId, verificationId, ivs);
930            }
931            mCurrentIntentFilterVerifications.clear();
932        }
933
934        private void sendVerificationRequest(int userId, int verificationId,
935                IntentFilterVerificationState ivs) {
936
937            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
938            verificationIntent.putExtra(
939                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
940                    verificationId);
941            verificationIntent.putExtra(
942                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
943                    getDefaultScheme());
944            verificationIntent.putExtra(
945                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
946                    ivs.getHostsString());
947            verificationIntent.putExtra(
948                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
949                    ivs.getPackageName());
950            verificationIntent.setComponent(mIntentFilterVerifierComponent);
951            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
952
953            UserHandle user = new UserHandle(userId);
954            mContext.sendBroadcastAsUser(verificationIntent, user);
955            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
956                    "Sending IntentFilter verification broadcast");
957        }
958
959        public void receiveVerificationResponse(int verificationId) {
960            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
961
962            final boolean verified = ivs.isVerified();
963
964            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
965            final int count = filters.size();
966            if (DEBUG_DOMAIN_VERIFICATION) {
967                Slog.i(TAG, "Received verification response " + verificationId
968                        + " for " + count + " filters, verified=" + verified);
969            }
970            for (int n=0; n<count; n++) {
971                PackageParser.ActivityIntentInfo filter = filters.get(n);
972                filter.setVerified(verified);
973
974                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
975                        + " verified with result:" + verified + " and hosts:"
976                        + ivs.getHostsString());
977            }
978
979            mIntentFilterVerificationStates.remove(verificationId);
980
981            final String packageName = ivs.getPackageName();
982            IntentFilterVerificationInfo ivi = null;
983
984            synchronized (mPackages) {
985                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
986            }
987            if (ivi == null) {
988                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
989                        + verificationId + " packageName:" + packageName);
990                return;
991            }
992            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
993                    "Updating IntentFilterVerificationInfo for package " + packageName
994                            +" verificationId:" + verificationId);
995
996            synchronized (mPackages) {
997                if (verified) {
998                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
999                } else {
1000                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1001                }
1002                scheduleWriteSettingsLocked();
1003
1004                final int userId = ivs.getUserId();
1005                if (userId != UserHandle.USER_ALL) {
1006                    final int userStatus =
1007                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1008
1009                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1010                    boolean needUpdate = false;
1011
1012                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1013                    // already been set by the User thru the Disambiguation dialog
1014                    switch (userStatus) {
1015                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1016                            if (verified) {
1017                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1018                            } else {
1019                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1020                            }
1021                            needUpdate = true;
1022                            break;
1023
1024                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1025                            if (verified) {
1026                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1027                                needUpdate = true;
1028                            }
1029                            break;
1030
1031                        default:
1032                            // Nothing to do
1033                    }
1034
1035                    if (needUpdate) {
1036                        mSettings.updateIntentFilterVerificationStatusLPw(
1037                                packageName, updatedStatus, userId);
1038                        scheduleWritePackageRestrictionsLocked(userId);
1039                    }
1040                }
1041            }
1042        }
1043
1044        @Override
1045        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1046                    ActivityIntentInfo filter, String packageName) {
1047            if (!hasValidDomains(filter)) {
1048                return false;
1049            }
1050            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1051            if (ivs == null) {
1052                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1053                        packageName);
1054            }
1055            if (DEBUG_DOMAIN_VERIFICATION) {
1056                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1057            }
1058            ivs.addFilter(filter);
1059            return true;
1060        }
1061
1062        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1063                int userId, int verificationId, String packageName) {
1064            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1065                    verifierUid, userId, packageName);
1066            ivs.setPendingState();
1067            synchronized (mPackages) {
1068                mIntentFilterVerificationStates.append(verificationId, ivs);
1069                mCurrentIntentFilterVerifications.add(verificationId);
1070            }
1071            return ivs;
1072        }
1073    }
1074
1075    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1076        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1077                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1078                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1079    }
1080
1081    // Set of pending broadcasts for aggregating enable/disable of components.
1082    static class PendingPackageBroadcasts {
1083        // for each user id, a map of <package name -> components within that package>
1084        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1085
1086        public PendingPackageBroadcasts() {
1087            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1088        }
1089
1090        public ArrayList<String> get(int userId, String packageName) {
1091            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1092            return packages.get(packageName);
1093        }
1094
1095        public void put(int userId, String packageName, ArrayList<String> components) {
1096            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1097            packages.put(packageName, components);
1098        }
1099
1100        public void remove(int userId, String packageName) {
1101            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1102            if (packages != null) {
1103                packages.remove(packageName);
1104            }
1105        }
1106
1107        public void remove(int userId) {
1108            mUidMap.remove(userId);
1109        }
1110
1111        public int userIdCount() {
1112            return mUidMap.size();
1113        }
1114
1115        public int userIdAt(int n) {
1116            return mUidMap.keyAt(n);
1117        }
1118
1119        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1120            return mUidMap.get(userId);
1121        }
1122
1123        public int size() {
1124            // total number of pending broadcast entries across all userIds
1125            int num = 0;
1126            for (int i = 0; i< mUidMap.size(); i++) {
1127                num += mUidMap.valueAt(i).size();
1128            }
1129            return num;
1130        }
1131
1132        public void clear() {
1133            mUidMap.clear();
1134        }
1135
1136        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1137            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1138            if (map == null) {
1139                map = new ArrayMap<String, ArrayList<String>>();
1140                mUidMap.put(userId, map);
1141            }
1142            return map;
1143        }
1144    }
1145    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1146
1147    // Service Connection to remote media container service to copy
1148    // package uri's from external media onto secure containers
1149    // or internal storage.
1150    private IMediaContainerService mContainerService = null;
1151
1152    static final int SEND_PENDING_BROADCAST = 1;
1153    static final int MCS_BOUND = 3;
1154    static final int END_COPY = 4;
1155    static final int INIT_COPY = 5;
1156    static final int MCS_UNBIND = 6;
1157    static final int START_CLEANING_PACKAGE = 7;
1158    static final int FIND_INSTALL_LOC = 8;
1159    static final int POST_INSTALL = 9;
1160    static final int MCS_RECONNECT = 10;
1161    static final int MCS_GIVE_UP = 11;
1162    static final int UPDATED_MEDIA_STATUS = 12;
1163    static final int WRITE_SETTINGS = 13;
1164    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1165    static final int PACKAGE_VERIFIED = 15;
1166    static final int CHECK_PENDING_VERIFICATION = 16;
1167    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1168    static final int INTENT_FILTER_VERIFIED = 18;
1169    static final int WRITE_PACKAGE_LIST = 19;
1170    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1171
1172    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1173
1174    // Delay time in millisecs
1175    static final int BROADCAST_DELAY = 10 * 1000;
1176
1177    static UserManagerService sUserManager;
1178
1179    // Stores a list of users whose package restrictions file needs to be updated
1180    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1181
1182    final private DefaultContainerConnection mDefContainerConn =
1183            new DefaultContainerConnection();
1184    class DefaultContainerConnection implements ServiceConnection {
1185        public void onServiceConnected(ComponentName name, IBinder service) {
1186            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1187            final IMediaContainerService imcs = IMediaContainerService.Stub
1188                    .asInterface(Binder.allowBlocking(service));
1189            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1190        }
1191
1192        public void onServiceDisconnected(ComponentName name) {
1193            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1194        }
1195    }
1196
1197    // Recordkeeping of restore-after-install operations that are currently in flight
1198    // between the Package Manager and the Backup Manager
1199    static class PostInstallData {
1200        public InstallArgs args;
1201        public PackageInstalledInfo res;
1202
1203        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1204            args = _a;
1205            res = _r;
1206        }
1207    }
1208
1209    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1210    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1211
1212    // XML tags for backup/restore of various bits of state
1213    private static final String TAG_PREFERRED_BACKUP = "pa";
1214    private static final String TAG_DEFAULT_APPS = "da";
1215    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1216
1217    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1218    private static final String TAG_ALL_GRANTS = "rt-grants";
1219    private static final String TAG_GRANT = "grant";
1220    private static final String ATTR_PACKAGE_NAME = "pkg";
1221
1222    private static final String TAG_PERMISSION = "perm";
1223    private static final String ATTR_PERMISSION_NAME = "name";
1224    private static final String ATTR_IS_GRANTED = "g";
1225    private static final String ATTR_USER_SET = "set";
1226    private static final String ATTR_USER_FIXED = "fixed";
1227    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1228
1229    // System/policy permission grants are not backed up
1230    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1231            FLAG_PERMISSION_POLICY_FIXED
1232            | FLAG_PERMISSION_SYSTEM_FIXED
1233            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1234
1235    // And we back up these user-adjusted states
1236    private static final int USER_RUNTIME_GRANT_MASK =
1237            FLAG_PERMISSION_USER_SET
1238            | FLAG_PERMISSION_USER_FIXED
1239            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1240
1241    final @Nullable String mRequiredVerifierPackage;
1242    final @NonNull String mRequiredInstallerPackage;
1243    final @NonNull String mRequiredUninstallerPackage;
1244    final @Nullable String mSetupWizardPackage;
1245    final @Nullable String mStorageManagerPackage;
1246    final @NonNull String mServicesSystemSharedLibraryPackageName;
1247    final @NonNull String mSharedSystemSharedLibraryPackageName;
1248
1249    final boolean mPermissionReviewRequired;
1250
1251    private final PackageUsage mPackageUsage = new PackageUsage();
1252    private final CompilerStats mCompilerStats = new CompilerStats();
1253
1254    class PackageHandler extends Handler {
1255        private boolean mBound = false;
1256        final ArrayList<HandlerParams> mPendingInstalls =
1257            new ArrayList<HandlerParams>();
1258
1259        private boolean connectToService() {
1260            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1261                    " DefaultContainerService");
1262            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1263            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1264            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1265                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1266                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1267                mBound = true;
1268                return true;
1269            }
1270            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1271            return false;
1272        }
1273
1274        private void disconnectService() {
1275            mContainerService = null;
1276            mBound = false;
1277            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1278            mContext.unbindService(mDefContainerConn);
1279            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1280        }
1281
1282        PackageHandler(Looper looper) {
1283            super(looper);
1284        }
1285
1286        public void handleMessage(Message msg) {
1287            try {
1288                doHandleMessage(msg);
1289            } finally {
1290                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1291            }
1292        }
1293
1294        void doHandleMessage(Message msg) {
1295            switch (msg.what) {
1296                case INIT_COPY: {
1297                    HandlerParams params = (HandlerParams) msg.obj;
1298                    int idx = mPendingInstalls.size();
1299                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1300                    // If a bind was already initiated we dont really
1301                    // need to do anything. The pending install
1302                    // will be processed later on.
1303                    if (!mBound) {
1304                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1305                                System.identityHashCode(mHandler));
1306                        // If this is the only one pending we might
1307                        // have to bind to the service again.
1308                        if (!connectToService()) {
1309                            Slog.e(TAG, "Failed to bind to media container service");
1310                            params.serviceError();
1311                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1312                                    System.identityHashCode(mHandler));
1313                            if (params.traceMethod != null) {
1314                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1315                                        params.traceCookie);
1316                            }
1317                            return;
1318                        } else {
1319                            // Once we bind to the service, the first
1320                            // pending request will be processed.
1321                            mPendingInstalls.add(idx, params);
1322                        }
1323                    } else {
1324                        mPendingInstalls.add(idx, params);
1325                        // Already bound to the service. Just make
1326                        // sure we trigger off processing the first request.
1327                        if (idx == 0) {
1328                            mHandler.sendEmptyMessage(MCS_BOUND);
1329                        }
1330                    }
1331                    break;
1332                }
1333                case MCS_BOUND: {
1334                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1335                    if (msg.obj != null) {
1336                        mContainerService = (IMediaContainerService) msg.obj;
1337                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1338                                System.identityHashCode(mHandler));
1339                    }
1340                    if (mContainerService == null) {
1341                        if (!mBound) {
1342                            // Something seriously wrong since we are not bound and we are not
1343                            // waiting for connection. Bail out.
1344                            Slog.e(TAG, "Cannot bind to media container service");
1345                            for (HandlerParams params : mPendingInstalls) {
1346                                // Indicate service bind error
1347                                params.serviceError();
1348                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1349                                        System.identityHashCode(params));
1350                                if (params.traceMethod != null) {
1351                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1352                                            params.traceMethod, params.traceCookie);
1353                                }
1354                                return;
1355                            }
1356                            mPendingInstalls.clear();
1357                        } else {
1358                            Slog.w(TAG, "Waiting to connect to media container service");
1359                        }
1360                    } else if (mPendingInstalls.size() > 0) {
1361                        HandlerParams params = mPendingInstalls.get(0);
1362                        if (params != null) {
1363                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1364                                    System.identityHashCode(params));
1365                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1366                            if (params.startCopy()) {
1367                                // We are done...  look for more work or to
1368                                // go idle.
1369                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1370                                        "Checking for more work or unbind...");
1371                                // Delete pending install
1372                                if (mPendingInstalls.size() > 0) {
1373                                    mPendingInstalls.remove(0);
1374                                }
1375                                if (mPendingInstalls.size() == 0) {
1376                                    if (mBound) {
1377                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1378                                                "Posting delayed MCS_UNBIND");
1379                                        removeMessages(MCS_UNBIND);
1380                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1381                                        // Unbind after a little delay, to avoid
1382                                        // continual thrashing.
1383                                        sendMessageDelayed(ubmsg, 10000);
1384                                    }
1385                                } else {
1386                                    // There are more pending requests in queue.
1387                                    // Just post MCS_BOUND message to trigger processing
1388                                    // of next pending install.
1389                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1390                                            "Posting MCS_BOUND for next work");
1391                                    mHandler.sendEmptyMessage(MCS_BOUND);
1392                                }
1393                            }
1394                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1395                        }
1396                    } else {
1397                        // Should never happen ideally.
1398                        Slog.w(TAG, "Empty queue");
1399                    }
1400                    break;
1401                }
1402                case MCS_RECONNECT: {
1403                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1404                    if (mPendingInstalls.size() > 0) {
1405                        if (mBound) {
1406                            disconnectService();
1407                        }
1408                        if (!connectToService()) {
1409                            Slog.e(TAG, "Failed to bind to media container service");
1410                            for (HandlerParams params : mPendingInstalls) {
1411                                // Indicate service bind error
1412                                params.serviceError();
1413                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1414                                        System.identityHashCode(params));
1415                            }
1416                            mPendingInstalls.clear();
1417                        }
1418                    }
1419                    break;
1420                }
1421                case MCS_UNBIND: {
1422                    // If there is no actual work left, then time to unbind.
1423                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1424
1425                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1426                        if (mBound) {
1427                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1428
1429                            disconnectService();
1430                        }
1431                    } else if (mPendingInstalls.size() > 0) {
1432                        // There are more pending requests in queue.
1433                        // Just post MCS_BOUND message to trigger processing
1434                        // of next pending install.
1435                        mHandler.sendEmptyMessage(MCS_BOUND);
1436                    }
1437
1438                    break;
1439                }
1440                case MCS_GIVE_UP: {
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1442                    HandlerParams params = mPendingInstalls.remove(0);
1443                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1444                            System.identityHashCode(params));
1445                    break;
1446                }
1447                case SEND_PENDING_BROADCAST: {
1448                    String packages[];
1449                    ArrayList<String> components[];
1450                    int size = 0;
1451                    int uids[];
1452                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1453                    synchronized (mPackages) {
1454                        if (mPendingBroadcasts == null) {
1455                            return;
1456                        }
1457                        size = mPendingBroadcasts.size();
1458                        if (size <= 0) {
1459                            // Nothing to be done. Just return
1460                            return;
1461                        }
1462                        packages = new String[size];
1463                        components = new ArrayList[size];
1464                        uids = new int[size];
1465                        int i = 0;  // filling out the above arrays
1466
1467                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1468                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1469                            Iterator<Map.Entry<String, ArrayList<String>>> it
1470                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1471                                            .entrySet().iterator();
1472                            while (it.hasNext() && i < size) {
1473                                Map.Entry<String, ArrayList<String>> ent = it.next();
1474                                packages[i] = ent.getKey();
1475                                components[i] = ent.getValue();
1476                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1477                                uids[i] = (ps != null)
1478                                        ? UserHandle.getUid(packageUserId, ps.appId)
1479                                        : -1;
1480                                i++;
1481                            }
1482                        }
1483                        size = i;
1484                        mPendingBroadcasts.clear();
1485                    }
1486                    // Send broadcasts
1487                    for (int i = 0; i < size; i++) {
1488                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1489                    }
1490                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1491                    break;
1492                }
1493                case START_CLEANING_PACKAGE: {
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1495                    final String packageName = (String)msg.obj;
1496                    final int userId = msg.arg1;
1497                    final boolean andCode = msg.arg2 != 0;
1498                    synchronized (mPackages) {
1499                        if (userId == UserHandle.USER_ALL) {
1500                            int[] users = sUserManager.getUserIds();
1501                            for (int user : users) {
1502                                mSettings.addPackageToCleanLPw(
1503                                        new PackageCleanItem(user, packageName, andCode));
1504                            }
1505                        } else {
1506                            mSettings.addPackageToCleanLPw(
1507                                    new PackageCleanItem(userId, packageName, andCode));
1508                        }
1509                    }
1510                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1511                    startCleaningPackages();
1512                } break;
1513                case POST_INSTALL: {
1514                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1515
1516                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1517                    final boolean didRestore = (msg.arg2 != 0);
1518                    mRunningInstalls.delete(msg.arg1);
1519
1520                    if (data != null) {
1521                        InstallArgs args = data.args;
1522                        PackageInstalledInfo parentRes = data.res;
1523
1524                        final boolean grantPermissions = (args.installFlags
1525                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1526                        final boolean killApp = (args.installFlags
1527                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1528                        final String[] grantedPermissions = args.installGrantPermissions;
1529
1530                        // Handle the parent package
1531                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1532                                grantedPermissions, didRestore, args.installerPackageName,
1533                                args.observer);
1534
1535                        // Handle the child packages
1536                        final int childCount = (parentRes.addedChildPackages != null)
1537                                ? parentRes.addedChildPackages.size() : 0;
1538                        for (int i = 0; i < childCount; i++) {
1539                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1540                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1541                                    grantedPermissions, false, args.installerPackageName,
1542                                    args.observer);
1543                        }
1544
1545                        // Log tracing if needed
1546                        if (args.traceMethod != null) {
1547                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1548                                    args.traceCookie);
1549                        }
1550                    } else {
1551                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1552                    }
1553
1554                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1555                } break;
1556                case UPDATED_MEDIA_STATUS: {
1557                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1558                    boolean reportStatus = msg.arg1 == 1;
1559                    boolean doGc = msg.arg2 == 1;
1560                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1561                    if (doGc) {
1562                        // Force a gc to clear up stale containers.
1563                        Runtime.getRuntime().gc();
1564                    }
1565                    if (msg.obj != null) {
1566                        @SuppressWarnings("unchecked")
1567                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1568                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1569                        // Unload containers
1570                        unloadAllContainers(args);
1571                    }
1572                    if (reportStatus) {
1573                        try {
1574                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1575                                    "Invoking StorageManagerService call back");
1576                            PackageHelper.getStorageManager().finishMediaUpdate();
1577                        } catch (RemoteException e) {
1578                            Log.e(TAG, "StorageManagerService not running?");
1579                        }
1580                    }
1581                } break;
1582                case WRITE_SETTINGS: {
1583                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1584                    synchronized (mPackages) {
1585                        removeMessages(WRITE_SETTINGS);
1586                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1587                        mSettings.writeLPr();
1588                        mDirtyUsers.clear();
1589                    }
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1591                } break;
1592                case WRITE_PACKAGE_RESTRICTIONS: {
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1594                    synchronized (mPackages) {
1595                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1596                        for (int userId : mDirtyUsers) {
1597                            mSettings.writePackageRestrictionsLPr(userId);
1598                        }
1599                        mDirtyUsers.clear();
1600                    }
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1602                } break;
1603                case WRITE_PACKAGE_LIST: {
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        removeMessages(WRITE_PACKAGE_LIST);
1607                        mSettings.writePackageListLPr(msg.arg1);
1608                    }
1609                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1610                } break;
1611                case CHECK_PENDING_VERIFICATION: {
1612                    final int verificationId = msg.arg1;
1613                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1614
1615                    if ((state != null) && !state.timeoutExtended()) {
1616                        final InstallArgs args = state.getInstallArgs();
1617                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1618
1619                        Slog.i(TAG, "Verification timed out for " + originUri);
1620                        mPendingVerification.remove(verificationId);
1621
1622                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1623
1624                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1625                            Slog.i(TAG, "Continuing with installation of " + originUri);
1626                            state.setVerifierResponse(Binder.getCallingUid(),
1627                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1628                            broadcastPackageVerified(verificationId, originUri,
1629                                    PackageManager.VERIFICATION_ALLOW,
1630                                    state.getInstallArgs().getUser());
1631                            try {
1632                                ret = args.copyApk(mContainerService, true);
1633                            } catch (RemoteException e) {
1634                                Slog.e(TAG, "Could not contact the ContainerService");
1635                            }
1636                        } else {
1637                            broadcastPackageVerified(verificationId, originUri,
1638                                    PackageManager.VERIFICATION_REJECT,
1639                                    state.getInstallArgs().getUser());
1640                        }
1641
1642                        Trace.asyncTraceEnd(
1643                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1644
1645                        processPendingInstall(args, ret);
1646                        mHandler.sendEmptyMessage(MCS_UNBIND);
1647                    }
1648                    break;
1649                }
1650                case PACKAGE_VERIFIED: {
1651                    final int verificationId = msg.arg1;
1652
1653                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1654                    if (state == null) {
1655                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1656                        break;
1657                    }
1658
1659                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1660
1661                    state.setVerifierResponse(response.callerUid, response.code);
1662
1663                    if (state.isVerificationComplete()) {
1664                        mPendingVerification.remove(verificationId);
1665
1666                        final InstallArgs args = state.getInstallArgs();
1667                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1668
1669                        int ret;
1670                        if (state.isInstallAllowed()) {
1671                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1672                            broadcastPackageVerified(verificationId, originUri,
1673                                    response.code, state.getInstallArgs().getUser());
1674                            try {
1675                                ret = args.copyApk(mContainerService, true);
1676                            } catch (RemoteException e) {
1677                                Slog.e(TAG, "Could not contact the ContainerService");
1678                            }
1679                        } else {
1680                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1681                        }
1682
1683                        Trace.asyncTraceEnd(
1684                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1685
1686                        processPendingInstall(args, ret);
1687                        mHandler.sendEmptyMessage(MCS_UNBIND);
1688                    }
1689
1690                    break;
1691                }
1692                case START_INTENT_FILTER_VERIFICATIONS: {
1693                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1694                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1695                            params.replacing, params.pkg);
1696                    break;
1697                }
1698                case INTENT_FILTER_VERIFIED: {
1699                    final int verificationId = msg.arg1;
1700
1701                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1702                            verificationId);
1703                    if (state == null) {
1704                        Slog.w(TAG, "Invalid IntentFilter verification token "
1705                                + verificationId + " received");
1706                        break;
1707                    }
1708
1709                    final int userId = state.getUserId();
1710
1711                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1712                            "Processing IntentFilter verification with token:"
1713                            + verificationId + " and userId:" + userId);
1714
1715                    final IntentFilterVerificationResponse response =
1716                            (IntentFilterVerificationResponse) msg.obj;
1717
1718                    state.setVerifierResponse(response.callerUid, response.code);
1719
1720                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1721                            "IntentFilter verification with token:" + verificationId
1722                            + " and userId:" + userId
1723                            + " is settings verifier response with response code:"
1724                            + response.code);
1725
1726                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1727                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1728                                + response.getFailedDomainsString());
1729                    }
1730
1731                    if (state.isVerificationComplete()) {
1732                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1733                    } else {
1734                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1735                                "IntentFilter verification with token:" + verificationId
1736                                + " was not said to be complete");
1737                    }
1738
1739                    break;
1740                }
1741                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1742                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1743                            mInstantAppResolverConnection,
1744                            (InstantAppRequest) msg.obj,
1745                            mInstantAppInstallerActivity,
1746                            mHandler);
1747                }
1748            }
1749        }
1750    }
1751
1752    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1753            boolean killApp, String[] grantedPermissions,
1754            boolean launchedForRestore, String installerPackage,
1755            IPackageInstallObserver2 installObserver) {
1756        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1757            // Send the removed broadcasts
1758            if (res.removedInfo != null) {
1759                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1760            }
1761
1762            // Now that we successfully installed the package, grant runtime
1763            // permissions if requested before broadcasting the install. Also
1764            // for legacy apps in permission review mode we clear the permission
1765            // review flag which is used to emulate runtime permissions for
1766            // legacy apps.
1767            if (grantPermissions) {
1768                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1769            }
1770
1771            final boolean update = res.removedInfo != null
1772                    && res.removedInfo.removedPackage != null;
1773
1774            // If this is the first time we have child packages for a disabled privileged
1775            // app that had no children, we grant requested runtime permissions to the new
1776            // children if the parent on the system image had them already granted.
1777            if (res.pkg.parentPackage != null) {
1778                synchronized (mPackages) {
1779                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1780                }
1781            }
1782
1783            synchronized (mPackages) {
1784                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1785            }
1786
1787            final String packageName = res.pkg.applicationInfo.packageName;
1788
1789            // Determine the set of users who are adding this package for
1790            // the first time vs. those who are seeing an update.
1791            int[] firstUsers = EMPTY_INT_ARRAY;
1792            int[] updateUsers = EMPTY_INT_ARRAY;
1793            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1794            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1795            for (int newUser : res.newUsers) {
1796                if (ps.getInstantApp(newUser)) {
1797                    continue;
1798                }
1799                if (allNewUsers) {
1800                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1801                    continue;
1802                }
1803                boolean isNew = true;
1804                for (int origUser : res.origUsers) {
1805                    if (origUser == newUser) {
1806                        isNew = false;
1807                        break;
1808                    }
1809                }
1810                if (isNew) {
1811                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1812                } else {
1813                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1814                }
1815            }
1816
1817            // Send installed broadcasts if the package is not a static shared lib.
1818            if (res.pkg.staticSharedLibName == null) {
1819                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1820
1821                // Send added for users that see the package for the first time
1822                // sendPackageAddedForNewUsers also deals with system apps
1823                int appId = UserHandle.getAppId(res.uid);
1824                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1825                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1826
1827                // Send added for users that don't see the package for the first time
1828                Bundle extras = new Bundle(1);
1829                extras.putInt(Intent.EXTRA_UID, res.uid);
1830                if (update) {
1831                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1832                }
1833                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1834                        extras, 0 /*flags*/, null /*targetPackage*/,
1835                        null /*finishedReceiver*/, updateUsers);
1836
1837                // Send replaced for users that don't see the package for the first time
1838                if (update) {
1839                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1840                            packageName, extras, 0 /*flags*/,
1841                            null /*targetPackage*/, null /*finishedReceiver*/,
1842                            updateUsers);
1843                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1844                            null /*package*/, null /*extras*/, 0 /*flags*/,
1845                            packageName /*targetPackage*/,
1846                            null /*finishedReceiver*/, updateUsers);
1847                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1848                    // First-install and we did a restore, so we're responsible for the
1849                    // first-launch broadcast.
1850                    if (DEBUG_BACKUP) {
1851                        Slog.i(TAG, "Post-restore of " + packageName
1852                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1853                    }
1854                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1855                }
1856
1857                // Send broadcast package appeared if forward locked/external for all users
1858                // treat asec-hosted packages like removable media on upgrade
1859                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1860                    if (DEBUG_INSTALL) {
1861                        Slog.i(TAG, "upgrading pkg " + res.pkg
1862                                + " is ASEC-hosted -> AVAILABLE");
1863                    }
1864                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1865                    ArrayList<String> pkgList = new ArrayList<>(1);
1866                    pkgList.add(packageName);
1867                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1868                }
1869            }
1870
1871            // Work that needs to happen on first install within each user
1872            if (firstUsers != null && firstUsers.length > 0) {
1873                synchronized (mPackages) {
1874                    for (int userId : firstUsers) {
1875                        // If this app is a browser and it's newly-installed for some
1876                        // users, clear any default-browser state in those users. The
1877                        // app's nature doesn't depend on the user, so we can just check
1878                        // its browser nature in any user and generalize.
1879                        if (packageIsBrowser(packageName, userId)) {
1880                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1881                        }
1882
1883                        // We may also need to apply pending (restored) runtime
1884                        // permission grants within these users.
1885                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1886                    }
1887                }
1888            }
1889
1890            // Log current value of "unknown sources" setting
1891            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1892                    getUnknownSourcesSettings());
1893
1894            // Force a gc to clear up things
1895            Runtime.getRuntime().gc();
1896
1897            // Remove the replaced package's older resources safely now
1898            // We delete after a gc for applications  on sdcard.
1899            if (res.removedInfo != null && res.removedInfo.args != null) {
1900                synchronized (mInstallLock) {
1901                    res.removedInfo.args.doPostDeleteLI(true);
1902                }
1903            }
1904
1905            // Notify DexManager that the package was installed for new users.
1906            // The updated users should already be indexed and the package code paths
1907            // should not change.
1908            // Don't notify the manager for ephemeral apps as they are not expected to
1909            // survive long enough to benefit of background optimizations.
1910            for (int userId : firstUsers) {
1911                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1912                mDexManager.notifyPackageInstalled(info, userId);
1913            }
1914        }
1915
1916        // If someone is watching installs - notify them
1917        if (installObserver != null) {
1918            try {
1919                Bundle extras = extrasForInstallResult(res);
1920                installObserver.onPackageInstalled(res.name, res.returnCode,
1921                        res.returnMsg, extras);
1922            } catch (RemoteException e) {
1923                Slog.i(TAG, "Observer no longer exists.");
1924            }
1925        }
1926    }
1927
1928    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1929            PackageParser.Package pkg) {
1930        if (pkg.parentPackage == null) {
1931            return;
1932        }
1933        if (pkg.requestedPermissions == null) {
1934            return;
1935        }
1936        final PackageSetting disabledSysParentPs = mSettings
1937                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1938        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1939                || !disabledSysParentPs.isPrivileged()
1940                || (disabledSysParentPs.childPackageNames != null
1941                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1942            return;
1943        }
1944        final int[] allUserIds = sUserManager.getUserIds();
1945        final int permCount = pkg.requestedPermissions.size();
1946        for (int i = 0; i < permCount; i++) {
1947            String permission = pkg.requestedPermissions.get(i);
1948            BasePermission bp = mSettings.mPermissions.get(permission);
1949            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1950                continue;
1951            }
1952            for (int userId : allUserIds) {
1953                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1954                        permission, userId)) {
1955                    grantRuntimePermission(pkg.packageName, permission, userId);
1956                }
1957            }
1958        }
1959    }
1960
1961    private StorageEventListener mStorageListener = new StorageEventListener() {
1962        @Override
1963        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1964            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1965                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1966                    final String volumeUuid = vol.getFsUuid();
1967
1968                    // Clean up any users or apps that were removed or recreated
1969                    // while this volume was missing
1970                    sUserManager.reconcileUsers(volumeUuid);
1971                    reconcileApps(volumeUuid);
1972
1973                    // Clean up any install sessions that expired or were
1974                    // cancelled while this volume was missing
1975                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1976
1977                    loadPrivatePackages(vol);
1978
1979                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1980                    unloadPrivatePackages(vol);
1981                }
1982            }
1983
1984            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1985                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1986                    updateExternalMediaStatus(true, false);
1987                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1988                    updateExternalMediaStatus(false, false);
1989                }
1990            }
1991        }
1992
1993        @Override
1994        public void onVolumeForgotten(String fsUuid) {
1995            if (TextUtils.isEmpty(fsUuid)) {
1996                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1997                return;
1998            }
1999
2000            // Remove any apps installed on the forgotten volume
2001            synchronized (mPackages) {
2002                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2003                for (PackageSetting ps : packages) {
2004                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2005                    deletePackageVersioned(new VersionedPackage(ps.name,
2006                            PackageManager.VERSION_CODE_HIGHEST),
2007                            new LegacyPackageDeleteObserver(null).getBinder(),
2008                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2009                    // Try very hard to release any references to this package
2010                    // so we don't risk the system server being killed due to
2011                    // open FDs
2012                    AttributeCache.instance().removePackage(ps.name);
2013                }
2014
2015                mSettings.onVolumeForgotten(fsUuid);
2016                mSettings.writeLPr();
2017            }
2018        }
2019    };
2020
2021    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2022            String[] grantedPermissions) {
2023        for (int userId : userIds) {
2024            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2025        }
2026    }
2027
2028    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2029            String[] grantedPermissions) {
2030        SettingBase sb = (SettingBase) pkg.mExtras;
2031        if (sb == null) {
2032            return;
2033        }
2034
2035        PermissionsState permissionsState = sb.getPermissionsState();
2036
2037        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2038                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2039
2040        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2041                >= Build.VERSION_CODES.M;
2042
2043        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2044
2045        for (String permission : pkg.requestedPermissions) {
2046            final BasePermission bp;
2047            synchronized (mPackages) {
2048                bp = mSettings.mPermissions.get(permission);
2049            }
2050            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2051                    && (!instantApp || bp.isInstant())
2052                    && (grantedPermissions == null
2053                           || ArrayUtils.contains(grantedPermissions, permission))) {
2054                final int flags = permissionsState.getPermissionFlags(permission, userId);
2055                if (supportsRuntimePermissions) {
2056                    // Installer cannot change immutable permissions.
2057                    if ((flags & immutableFlags) == 0) {
2058                        grantRuntimePermission(pkg.packageName, permission, userId);
2059                    }
2060                } else if (mPermissionReviewRequired) {
2061                    // In permission review mode we clear the review flag when we
2062                    // are asked to install the app with all permissions granted.
2063                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2064                        updatePermissionFlags(permission, pkg.packageName,
2065                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2066                    }
2067                }
2068            }
2069        }
2070    }
2071
2072    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2073        Bundle extras = null;
2074        switch (res.returnCode) {
2075            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2076                extras = new Bundle();
2077                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2078                        res.origPermission);
2079                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2080                        res.origPackage);
2081                break;
2082            }
2083            case PackageManager.INSTALL_SUCCEEDED: {
2084                extras = new Bundle();
2085                extras.putBoolean(Intent.EXTRA_REPLACING,
2086                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2087                break;
2088            }
2089        }
2090        return extras;
2091    }
2092
2093    void scheduleWriteSettingsLocked() {
2094        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2095            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2096        }
2097    }
2098
2099    void scheduleWritePackageListLocked(int userId) {
2100        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2101            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2102            msg.arg1 = userId;
2103            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2104        }
2105    }
2106
2107    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2108        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2109        scheduleWritePackageRestrictionsLocked(userId);
2110    }
2111
2112    void scheduleWritePackageRestrictionsLocked(int userId) {
2113        final int[] userIds = (userId == UserHandle.USER_ALL)
2114                ? sUserManager.getUserIds() : new int[]{userId};
2115        for (int nextUserId : userIds) {
2116            if (!sUserManager.exists(nextUserId)) return;
2117            mDirtyUsers.add(nextUserId);
2118            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2119                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2120            }
2121        }
2122    }
2123
2124    public static PackageManagerService main(Context context, Installer installer,
2125            boolean factoryTest, boolean onlyCore) {
2126        // Self-check for initial settings.
2127        PackageManagerServiceCompilerMapping.checkProperties();
2128
2129        PackageManagerService m = new PackageManagerService(context, installer,
2130                factoryTest, onlyCore);
2131        m.enableSystemUserPackages();
2132        ServiceManager.addService("package", m);
2133        return m;
2134    }
2135
2136    private void enableSystemUserPackages() {
2137        if (!UserManager.isSplitSystemUser()) {
2138            return;
2139        }
2140        // For system user, enable apps based on the following conditions:
2141        // - app is whitelisted or belong to one of these groups:
2142        //   -- system app which has no launcher icons
2143        //   -- system app which has INTERACT_ACROSS_USERS permission
2144        //   -- system IME app
2145        // - app is not in the blacklist
2146        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2147        Set<String> enableApps = new ArraySet<>();
2148        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2149                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2150                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2151        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2152        enableApps.addAll(wlApps);
2153        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2154                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2155        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2156        enableApps.removeAll(blApps);
2157        Log.i(TAG, "Applications installed for system user: " + enableApps);
2158        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2159                UserHandle.SYSTEM);
2160        final int allAppsSize = allAps.size();
2161        synchronized (mPackages) {
2162            for (int i = 0; i < allAppsSize; i++) {
2163                String pName = allAps.get(i);
2164                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2165                // Should not happen, but we shouldn't be failing if it does
2166                if (pkgSetting == null) {
2167                    continue;
2168                }
2169                boolean install = enableApps.contains(pName);
2170                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2171                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2172                            + " for system user");
2173                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2174                }
2175            }
2176            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2177        }
2178    }
2179
2180    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2181        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2182                Context.DISPLAY_SERVICE);
2183        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2184    }
2185
2186    /**
2187     * Requests that files preopted on a secondary system partition be copied to the data partition
2188     * if possible.  Note that the actual copying of the files is accomplished by init for security
2189     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2190     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2191     */
2192    private static void requestCopyPreoptedFiles() {
2193        final int WAIT_TIME_MS = 100;
2194        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2195        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2196            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2197            // We will wait for up to 100 seconds.
2198            final long timeStart = SystemClock.uptimeMillis();
2199            final long timeEnd = timeStart + 100 * 1000;
2200            long timeNow = timeStart;
2201            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2202                try {
2203                    Thread.sleep(WAIT_TIME_MS);
2204                } catch (InterruptedException e) {
2205                    // Do nothing
2206                }
2207                timeNow = SystemClock.uptimeMillis();
2208                if (timeNow > timeEnd) {
2209                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2210                    Slog.wtf(TAG, "cppreopt did not finish!");
2211                    break;
2212                }
2213            }
2214
2215            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2216        }
2217    }
2218
2219    public PackageManagerService(Context context, Installer installer,
2220            boolean factoryTest, boolean onlyCore) {
2221        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2222        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2223        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2224                SystemClock.uptimeMillis());
2225
2226        if (mSdkVersion <= 0) {
2227            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2228        }
2229
2230        mContext = context;
2231
2232        mPermissionReviewRequired = context.getResources().getBoolean(
2233                R.bool.config_permissionReviewRequired);
2234
2235        mFactoryTest = factoryTest;
2236        mOnlyCore = onlyCore;
2237        mMetrics = new DisplayMetrics();
2238        mSettings = new Settings(mPackages);
2239        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2240                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2241        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2242                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2243        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2248                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2249        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2250                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2251
2252        String separateProcesses = SystemProperties.get("debug.separate_processes");
2253        if (separateProcesses != null && separateProcesses.length() > 0) {
2254            if ("*".equals(separateProcesses)) {
2255                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2256                mSeparateProcesses = null;
2257                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2258            } else {
2259                mDefParseFlags = 0;
2260                mSeparateProcesses = separateProcesses.split(",");
2261                Slog.w(TAG, "Running with debug.separate_processes: "
2262                        + separateProcesses);
2263            }
2264        } else {
2265            mDefParseFlags = 0;
2266            mSeparateProcesses = null;
2267        }
2268
2269        mInstaller = installer;
2270        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2271                "*dexopt*");
2272        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2273        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2274
2275        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2276                FgThread.get().getLooper());
2277
2278        getDefaultDisplayMetrics(context, mMetrics);
2279
2280        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2281        SystemConfig systemConfig = SystemConfig.getInstance();
2282        mGlobalGids = systemConfig.getGlobalGids();
2283        mSystemPermissions = systemConfig.getSystemPermissions();
2284        mAvailableFeatures = systemConfig.getAvailableFeatures();
2285        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2286
2287        mProtectedPackages = new ProtectedPackages(mContext);
2288
2289        synchronized (mInstallLock) {
2290        // writer
2291        synchronized (mPackages) {
2292            mHandlerThread = new ServiceThread(TAG,
2293                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2294            mHandlerThread.start();
2295            mHandler = new PackageHandler(mHandlerThread.getLooper());
2296            mProcessLoggingHandler = new ProcessLoggingHandler();
2297            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2298
2299            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2300            mInstantAppRegistry = new InstantAppRegistry(this);
2301
2302            File dataDir = Environment.getDataDirectory();
2303            mAppInstallDir = new File(dataDir, "app");
2304            mAppLib32InstallDir = new File(dataDir, "app-lib");
2305            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2306            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2307            sUserManager = new UserManagerService(context, this,
2308                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2309
2310            // Propagate permission configuration in to package manager.
2311            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2312                    = systemConfig.getPermissions();
2313            for (int i=0; i<permConfig.size(); i++) {
2314                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2315                BasePermission bp = mSettings.mPermissions.get(perm.name);
2316                if (bp == null) {
2317                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2318                    mSettings.mPermissions.put(perm.name, bp);
2319                }
2320                if (perm.gids != null) {
2321                    bp.setGids(perm.gids, perm.perUser);
2322                }
2323            }
2324
2325            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2326            final int builtInLibCount = libConfig.size();
2327            for (int i = 0; i < builtInLibCount; i++) {
2328                String name = libConfig.keyAt(i);
2329                String path = libConfig.valueAt(i);
2330                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2331                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2332            }
2333
2334            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2335
2336            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2337            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2338            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2339
2340            // Clean up orphaned packages for which the code path doesn't exist
2341            // and they are an update to a system app - caused by bug/32321269
2342            final int packageSettingCount = mSettings.mPackages.size();
2343            for (int i = packageSettingCount - 1; i >= 0; i--) {
2344                PackageSetting ps = mSettings.mPackages.valueAt(i);
2345                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2346                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2347                    mSettings.mPackages.removeAt(i);
2348                    mSettings.enableSystemPackageLPw(ps.name);
2349                }
2350            }
2351
2352            if (mFirstBoot) {
2353                requestCopyPreoptedFiles();
2354            }
2355
2356            String customResolverActivity = Resources.getSystem().getString(
2357                    R.string.config_customResolverActivity);
2358            if (TextUtils.isEmpty(customResolverActivity)) {
2359                customResolverActivity = null;
2360            } else {
2361                mCustomResolverComponentName = ComponentName.unflattenFromString(
2362                        customResolverActivity);
2363            }
2364
2365            long startTime = SystemClock.uptimeMillis();
2366
2367            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2368                    startTime);
2369
2370            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2371            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2372
2373            if (bootClassPath == null) {
2374                Slog.w(TAG, "No BOOTCLASSPATH found!");
2375            }
2376
2377            if (systemServerClassPath == null) {
2378                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2379            }
2380
2381            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2382            final String[] dexCodeInstructionSets =
2383                    getDexCodeInstructionSets(
2384                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2385
2386            /**
2387             * Ensure all external libraries have had dexopt run on them.
2388             */
2389            if (mSharedLibraries.size() > 0) {
2390                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2391                // NOTE: For now, we're compiling these system "shared libraries"
2392                // (and framework jars) into all available architectures. It's possible
2393                // to compile them only when we come across an app that uses them (there's
2394                // already logic for that in scanPackageLI) but that adds some complexity.
2395                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2396                    final int libCount = mSharedLibraries.size();
2397                    for (int i = 0; i < libCount; i++) {
2398                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2399                        final int versionCount = versionedLib.size();
2400                        for (int j = 0; j < versionCount; j++) {
2401                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2402                            final String libPath = libEntry.path != null
2403                                    ? libEntry.path : libEntry.apk;
2404                            if (libPath == null) {
2405                                continue;
2406                            }
2407                            try {
2408                                // Shared libraries do not have profiles so we perform a full
2409                                // AOT compilation (if needed).
2410                                int dexoptNeeded = DexFile.getDexOptNeeded(
2411                                        libPath, dexCodeInstructionSet,
2412                                        getCompilerFilterForReason(REASON_SHARED_APK),
2413                                        false /* newProfile */);
2414                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2415                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2416                                            dexCodeInstructionSet, dexoptNeeded, null,
2417                                            DEXOPT_PUBLIC,
2418                                            getCompilerFilterForReason(REASON_SHARED_APK),
2419                                            StorageManager.UUID_PRIVATE_INTERNAL,
2420                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2421                                }
2422                            } catch (FileNotFoundException e) {
2423                                Slog.w(TAG, "Library not found: " + libPath);
2424                            } catch (IOException | InstallerException e) {
2425                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2426                                        + e.getMessage());
2427                            }
2428                        }
2429                    }
2430                }
2431                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2432            }
2433
2434            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2435
2436            final VersionInfo ver = mSettings.getInternalVersion();
2437            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2438
2439            // when upgrading from pre-M, promote system app permissions from install to runtime
2440            mPromoteSystemApps =
2441                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2442
2443            // When upgrading from pre-N, we need to handle package extraction like first boot,
2444            // as there is no profiling data available.
2445            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2446
2447            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2448
2449            // save off the names of pre-existing system packages prior to scanning; we don't
2450            // want to automatically grant runtime permissions for new system apps
2451            if (mPromoteSystemApps) {
2452                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2453                while (pkgSettingIter.hasNext()) {
2454                    PackageSetting ps = pkgSettingIter.next();
2455                    if (isSystemApp(ps)) {
2456                        mExistingSystemPackages.add(ps.name);
2457                    }
2458                }
2459            }
2460
2461            mCacheDir = preparePackageParserCache(mIsUpgrade);
2462
2463            // Set flag to monitor and not change apk file paths when
2464            // scanning install directories.
2465            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2466
2467            if (mIsUpgrade || mFirstBoot) {
2468                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2469            }
2470
2471            // Collect vendor overlay packages. (Do this before scanning any apps.)
2472            // For security and version matching reason, only consider
2473            // overlay packages if they reside in the right directory.
2474            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2475                    | PackageParser.PARSE_IS_SYSTEM
2476                    | PackageParser.PARSE_IS_SYSTEM_DIR
2477                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2478
2479            // Find base frameworks (resource packages without code).
2480            scanDirTracedLI(frameworkDir, mDefParseFlags
2481                    | PackageParser.PARSE_IS_SYSTEM
2482                    | PackageParser.PARSE_IS_SYSTEM_DIR
2483                    | PackageParser.PARSE_IS_PRIVILEGED,
2484                    scanFlags | SCAN_NO_DEX, 0);
2485
2486            // Collected privileged system packages.
2487            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2488            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2489                    | PackageParser.PARSE_IS_SYSTEM
2490                    | PackageParser.PARSE_IS_SYSTEM_DIR
2491                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2492
2493            // Collect ordinary system packages.
2494            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2495            scanDirTracedLI(systemAppDir, mDefParseFlags
2496                    | PackageParser.PARSE_IS_SYSTEM
2497                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2498
2499            // Collect all vendor packages.
2500            File vendorAppDir = new File("/vendor/app");
2501            try {
2502                vendorAppDir = vendorAppDir.getCanonicalFile();
2503            } catch (IOException e) {
2504                // failed to look up canonical path, continue with original one
2505            }
2506            scanDirTracedLI(vendorAppDir, mDefParseFlags
2507                    | PackageParser.PARSE_IS_SYSTEM
2508                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2509
2510            // Collect all OEM packages.
2511            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2512            scanDirTracedLI(oemAppDir, mDefParseFlags
2513                    | PackageParser.PARSE_IS_SYSTEM
2514                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2515
2516            // Prune any system packages that no longer exist.
2517            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2518            if (!mOnlyCore) {
2519                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2520                while (psit.hasNext()) {
2521                    PackageSetting ps = psit.next();
2522
2523                    /*
2524                     * If this is not a system app, it can't be a
2525                     * disable system app.
2526                     */
2527                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2528                        continue;
2529                    }
2530
2531                    /*
2532                     * If the package is scanned, it's not erased.
2533                     */
2534                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2535                    if (scannedPkg != null) {
2536                        /*
2537                         * If the system app is both scanned and in the
2538                         * disabled packages list, then it must have been
2539                         * added via OTA. Remove it from the currently
2540                         * scanned package so the previously user-installed
2541                         * application can be scanned.
2542                         */
2543                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2544                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2545                                    + ps.name + "; removing system app.  Last known codePath="
2546                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2547                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2548                                    + scannedPkg.mVersionCode);
2549                            removePackageLI(scannedPkg, true);
2550                            mExpectingBetter.put(ps.name, ps.codePath);
2551                        }
2552
2553                        continue;
2554                    }
2555
2556                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2557                        psit.remove();
2558                        logCriticalInfo(Log.WARN, "System package " + ps.name
2559                                + " no longer exists; it's data will be wiped");
2560                        // Actual deletion of code and data will be handled by later
2561                        // reconciliation step
2562                    } else {
2563                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2564                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2565                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2566                        }
2567                    }
2568                }
2569            }
2570
2571            //look for any incomplete package installations
2572            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2573            for (int i = 0; i < deletePkgsList.size(); i++) {
2574                // Actual deletion of code and data will be handled by later
2575                // reconciliation step
2576                final String packageName = deletePkgsList.get(i).name;
2577                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2578                synchronized (mPackages) {
2579                    mSettings.removePackageLPw(packageName);
2580                }
2581            }
2582
2583            //delete tmp files
2584            deleteTempPackageFiles();
2585
2586            // Remove any shared userIDs that have no associated packages
2587            mSettings.pruneSharedUsersLPw();
2588
2589            if (!mOnlyCore) {
2590                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2591                        SystemClock.uptimeMillis());
2592                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2593
2594                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2595                        | PackageParser.PARSE_FORWARD_LOCK,
2596                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2597
2598                /**
2599                 * Remove disable package settings for any updated system
2600                 * apps that were removed via an OTA. If they're not a
2601                 * previously-updated app, remove them completely.
2602                 * Otherwise, just revoke their system-level permissions.
2603                 */
2604                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2605                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2606                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2607
2608                    String msg;
2609                    if (deletedPkg == null) {
2610                        msg = "Updated system package " + deletedAppName
2611                                + " no longer exists; it's data will be wiped";
2612                        // Actual deletion of code and data will be handled by later
2613                        // reconciliation step
2614                    } else {
2615                        msg = "Updated system app + " + deletedAppName
2616                                + " no longer present; removing system privileges for "
2617                                + deletedAppName;
2618
2619                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2620
2621                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2622                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2623                    }
2624                    logCriticalInfo(Log.WARN, msg);
2625                }
2626
2627                /**
2628                 * Make sure all system apps that we expected to appear on
2629                 * the userdata partition actually showed up. If they never
2630                 * appeared, crawl back and revive the system version.
2631                 */
2632                for (int i = 0; i < mExpectingBetter.size(); i++) {
2633                    final String packageName = mExpectingBetter.keyAt(i);
2634                    if (!mPackages.containsKey(packageName)) {
2635                        final File scanFile = mExpectingBetter.valueAt(i);
2636
2637                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2638                                + " but never showed up; reverting to system");
2639
2640                        int reparseFlags = mDefParseFlags;
2641                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2642                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2643                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2644                                    | PackageParser.PARSE_IS_PRIVILEGED;
2645                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2646                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2647                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2648                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2649                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2650                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2651                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2652                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2653                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2654                        } else {
2655                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2656                            continue;
2657                        }
2658
2659                        mSettings.enableSystemPackageLPw(packageName);
2660
2661                        try {
2662                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2663                        } catch (PackageManagerException e) {
2664                            Slog.e(TAG, "Failed to parse original system package: "
2665                                    + e.getMessage());
2666                        }
2667                    }
2668                }
2669            }
2670            mExpectingBetter.clear();
2671
2672            // Resolve the storage manager.
2673            mStorageManagerPackage = getStorageManagerPackageName();
2674
2675            // Resolve protected action filters. Only the setup wizard is allowed to
2676            // have a high priority filter for these actions.
2677            mSetupWizardPackage = getSetupWizardPackageName();
2678            if (mProtectedFilters.size() > 0) {
2679                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2680                    Slog.i(TAG, "No setup wizard;"
2681                        + " All protected intents capped to priority 0");
2682                }
2683                for (ActivityIntentInfo filter : mProtectedFilters) {
2684                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2685                        if (DEBUG_FILTERS) {
2686                            Slog.i(TAG, "Found setup wizard;"
2687                                + " allow priority " + filter.getPriority() + ";"
2688                                + " package: " + filter.activity.info.packageName
2689                                + " activity: " + filter.activity.className
2690                                + " priority: " + filter.getPriority());
2691                        }
2692                        // skip setup wizard; allow it to keep the high priority filter
2693                        continue;
2694                    }
2695                    Slog.w(TAG, "Protected action; cap priority to 0;"
2696                            + " package: " + filter.activity.info.packageName
2697                            + " activity: " + filter.activity.className
2698                            + " origPrio: " + filter.getPriority());
2699                    filter.setPriority(0);
2700                }
2701            }
2702            mDeferProtectedFilters = false;
2703            mProtectedFilters.clear();
2704
2705            // Now that we know all of the shared libraries, update all clients to have
2706            // the correct library paths.
2707            updateAllSharedLibrariesLPw(null);
2708
2709            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2710                // NOTE: We ignore potential failures here during a system scan (like
2711                // the rest of the commands above) because there's precious little we
2712                // can do about it. A settings error is reported, though.
2713                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2714            }
2715
2716            // Now that we know all the packages we are keeping,
2717            // read and update their last usage times.
2718            mPackageUsage.read(mPackages);
2719            mCompilerStats.read();
2720
2721            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2722                    SystemClock.uptimeMillis());
2723            Slog.i(TAG, "Time to scan packages: "
2724                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2725                    + " seconds");
2726
2727            // If the platform SDK has changed since the last time we booted,
2728            // we need to re-grant app permission to catch any new ones that
2729            // appear.  This is really a hack, and means that apps can in some
2730            // cases get permissions that the user didn't initially explicitly
2731            // allow...  it would be nice to have some better way to handle
2732            // this situation.
2733            int updateFlags = UPDATE_PERMISSIONS_ALL;
2734            if (ver.sdkVersion != mSdkVersion) {
2735                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2736                        + mSdkVersion + "; regranting permissions for internal storage");
2737                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2738            }
2739            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2740            ver.sdkVersion = mSdkVersion;
2741
2742            // If this is the first boot or an update from pre-M, and it is a normal
2743            // boot, then we need to initialize the default preferred apps across
2744            // all defined users.
2745            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2746                for (UserInfo user : sUserManager.getUsers(true)) {
2747                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2748                    applyFactoryDefaultBrowserLPw(user.id);
2749                    primeDomainVerificationsLPw(user.id);
2750                }
2751            }
2752
2753            // Prepare storage for system user really early during boot,
2754            // since core system apps like SettingsProvider and SystemUI
2755            // can't wait for user to start
2756            final int storageFlags;
2757            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2758                storageFlags = StorageManager.FLAG_STORAGE_DE;
2759            } else {
2760                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2761            }
2762            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2763                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2764                    true /* onlyCoreApps */);
2765            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2766                if (deferPackages == null || deferPackages.isEmpty()) {
2767                    return;
2768                }
2769                int count = 0;
2770                for (String pkgName : deferPackages) {
2771                    PackageParser.Package pkg = null;
2772                    synchronized (mPackages) {
2773                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2774                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2775                            pkg = ps.pkg;
2776                        }
2777                    }
2778                    if (pkg != null) {
2779                        synchronized (mInstallLock) {
2780                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2781                                    true /* maybeMigrateAppData */);
2782                        }
2783                        count++;
2784                    }
2785                }
2786                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2787            }, "prepareAppData");
2788
2789            // If this is first boot after an OTA, and a normal boot, then
2790            // we need to clear code cache directories.
2791            // Note that we do *not* clear the application profiles. These remain valid
2792            // across OTAs and are used to drive profile verification (post OTA) and
2793            // profile compilation (without waiting to collect a fresh set of profiles).
2794            if (mIsUpgrade && !onlyCore) {
2795                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2796                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2797                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2798                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2799                        // No apps are running this early, so no need to freeze
2800                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2801                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2802                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2803                    }
2804                }
2805                ver.fingerprint = Build.FINGERPRINT;
2806            }
2807
2808            checkDefaultBrowser();
2809
2810            // clear only after permissions and other defaults have been updated
2811            mExistingSystemPackages.clear();
2812            mPromoteSystemApps = false;
2813
2814            // All the changes are done during package scanning.
2815            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2816
2817            // can downgrade to reader
2818            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2819            mSettings.writeLPr();
2820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2821
2822            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2823            // early on (before the package manager declares itself as early) because other
2824            // components in the system server might ask for package contexts for these apps.
2825            //
2826            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2827            // (i.e, that the data partition is unavailable).
2828            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2829                long start = System.nanoTime();
2830                List<PackageParser.Package> coreApps = new ArrayList<>();
2831                for (PackageParser.Package pkg : mPackages.values()) {
2832                    if (pkg.coreApp) {
2833                        coreApps.add(pkg);
2834                    }
2835                }
2836
2837                int[] stats = performDexOptUpgrade(coreApps, false,
2838                        getCompilerFilterForReason(REASON_CORE_APP));
2839
2840                final int elapsedTimeSeconds =
2841                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2842                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2843
2844                if (DEBUG_DEXOPT) {
2845                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2846                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2847                }
2848
2849
2850                // TODO: Should we log these stats to tron too ?
2851                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2852                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2853                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2854                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2855            }
2856
2857            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2858                    SystemClock.uptimeMillis());
2859
2860            if (!mOnlyCore) {
2861                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2862                mRequiredInstallerPackage = getRequiredInstallerLPr();
2863                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2864                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2865                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2866                        mIntentFilterVerifierComponent);
2867                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2868                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2869                        SharedLibraryInfo.VERSION_UNDEFINED);
2870                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2871                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2872                        SharedLibraryInfo.VERSION_UNDEFINED);
2873            } else {
2874                mRequiredVerifierPackage = null;
2875                mRequiredInstallerPackage = null;
2876                mRequiredUninstallerPackage = null;
2877                mIntentFilterVerifierComponent = null;
2878                mIntentFilterVerifier = null;
2879                mServicesSystemSharedLibraryPackageName = null;
2880                mSharedSystemSharedLibraryPackageName = null;
2881            }
2882
2883            mInstallerService = new PackageInstallerService(context, this);
2884            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2885            if (ephemeralResolverComponent != null) {
2886                if (DEBUG_EPHEMERAL) {
2887                    Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent);
2888                }
2889                mInstantAppResolverConnection =
2890                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2891            } else {
2892                mInstantAppResolverConnection = null;
2893            }
2894            updateInstantAppInstallerLocked();
2895            mInstantAppResolverSettingsComponent = getEphemeralResolverSettingsLPr();
2896
2897            // Read and update the usage of dex files.
2898            // Do this at the end of PM init so that all the packages have their
2899            // data directory reconciled.
2900            // At this point we know the code paths of the packages, so we can validate
2901            // the disk file and build the internal cache.
2902            // The usage file is expected to be small so loading and verifying it
2903            // should take a fairly small time compare to the other activities (e.g. package
2904            // scanning).
2905            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2906            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2907            for (int userId : currentUserIds) {
2908                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2909            }
2910            mDexManager.load(userPackages);
2911        } // synchronized (mPackages)
2912        } // synchronized (mInstallLock)
2913
2914        // Now after opening every single application zip, make sure they
2915        // are all flushed.  Not really needed, but keeps things nice and
2916        // tidy.
2917        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2918        Runtime.getRuntime().gc();
2919        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2920
2921        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2922        FallbackCategoryProvider.loadFallbacks();
2923        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2924
2925        // The initial scanning above does many calls into installd while
2926        // holding the mPackages lock, but we're mostly interested in yelling
2927        // once we have a booted system.
2928        mInstaller.setWarnIfHeld(mPackages);
2929
2930        // Expose private service for system components to use.
2931        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2932        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2933    }
2934
2935    private void updateInstantAppInstallerLocked() {
2936        final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent;
2937        final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr();
2938        ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null
2939                ? null : newInstantAppInstaller.getComponentName();
2940
2941        if (newInstantAppInstallerComponent != null
2942                && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) {
2943            if (DEBUG_EPHEMERAL) {
2944                Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent);
2945            }
2946            setUpInstantAppInstallerActivityLP(newInstantAppInstaller);
2947        } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) {
2948            Slog.d(TAG, "Unset ephemeral installer; none available");
2949        }
2950        mInstantAppInstallerComponent = newInstantAppInstallerComponent;
2951    }
2952
2953    private static File preparePackageParserCache(boolean isUpgrade) {
2954        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2955            return null;
2956        }
2957
2958        // Disable package parsing on eng builds to allow for faster incremental development.
2959        if ("eng".equals(Build.TYPE)) {
2960            return null;
2961        }
2962
2963        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2964            Slog.i(TAG, "Disabling package parser cache due to system property.");
2965            return null;
2966        }
2967
2968        // The base directory for the package parser cache lives under /data/system/.
2969        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2970                "package_cache");
2971        if (cacheBaseDir == null) {
2972            return null;
2973        }
2974
2975        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2976        // This also serves to "GC" unused entries when the package cache version changes (which
2977        // can only happen during upgrades).
2978        if (isUpgrade) {
2979            FileUtils.deleteContents(cacheBaseDir);
2980        }
2981
2982
2983        // Return the versioned package cache directory. This is something like
2984        // "/data/system/package_cache/1"
2985        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2986
2987        // The following is a workaround to aid development on non-numbered userdebug
2988        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2989        // the system partition is newer.
2990        //
2991        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2992        // that starts with "eng." to signify that this is an engineering build and not
2993        // destined for release.
2994        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2995            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2996
2997            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2998            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2999            // in general and should not be used for production changes. In this specific case,
3000            // we know that they will work.
3001            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3002            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3003                FileUtils.deleteContents(cacheBaseDir);
3004                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3005            }
3006        }
3007
3008        return cacheDir;
3009    }
3010
3011    @Override
3012    public boolean isFirstBoot() {
3013        return mFirstBoot;
3014    }
3015
3016    @Override
3017    public boolean isOnlyCoreApps() {
3018        return mOnlyCore;
3019    }
3020
3021    @Override
3022    public boolean isUpgrade() {
3023        return mIsUpgrade;
3024    }
3025
3026    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3027        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3028
3029        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3030                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3031                UserHandle.USER_SYSTEM);
3032        if (matches.size() == 1) {
3033            return matches.get(0).getComponentInfo().packageName;
3034        } else if (matches.size() == 0) {
3035            Log.e(TAG, "There should probably be a verifier, but, none were found");
3036            return null;
3037        }
3038        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3039    }
3040
3041    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3042        synchronized (mPackages) {
3043            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3044            if (libraryEntry == null) {
3045                throw new IllegalStateException("Missing required shared library:" + name);
3046            }
3047            return libraryEntry.apk;
3048        }
3049    }
3050
3051    private @NonNull String getRequiredInstallerLPr() {
3052        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3053        intent.addCategory(Intent.CATEGORY_DEFAULT);
3054        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3055
3056        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3057                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3058                UserHandle.USER_SYSTEM);
3059        if (matches.size() == 1) {
3060            ResolveInfo resolveInfo = matches.get(0);
3061            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3062                throw new RuntimeException("The installer must be a privileged app");
3063            }
3064            return matches.get(0).getComponentInfo().packageName;
3065        } else {
3066            throw new RuntimeException("There must be exactly one installer; found " + matches);
3067        }
3068    }
3069
3070    private @NonNull String getRequiredUninstallerLPr() {
3071        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3072        intent.addCategory(Intent.CATEGORY_DEFAULT);
3073        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3074
3075        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3076                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3077                UserHandle.USER_SYSTEM);
3078        if (resolveInfo == null ||
3079                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3080            throw new RuntimeException("There must be exactly one uninstaller; found "
3081                    + resolveInfo);
3082        }
3083        return resolveInfo.getComponentInfo().packageName;
3084    }
3085
3086    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3087        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3088
3089        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3090                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3091                UserHandle.USER_SYSTEM);
3092        ResolveInfo best = null;
3093        final int N = matches.size();
3094        for (int i = 0; i < N; i++) {
3095            final ResolveInfo cur = matches.get(i);
3096            final String packageName = cur.getComponentInfo().packageName;
3097            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3098                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3099                continue;
3100            }
3101
3102            if (best == null || cur.priority > best.priority) {
3103                best = cur;
3104            }
3105        }
3106
3107        if (best != null) {
3108            return best.getComponentInfo().getComponentName();
3109        } else {
3110            throw new RuntimeException("There must be at least one intent filter verifier");
3111        }
3112    }
3113
3114    private @Nullable ComponentName getEphemeralResolverLPr() {
3115        final String[] packageArray =
3116                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3117        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3118            if (DEBUG_EPHEMERAL) {
3119                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3120            }
3121            return null;
3122        }
3123
3124        final int resolveFlags =
3125                MATCH_DIRECT_BOOT_AWARE
3126                | MATCH_DIRECT_BOOT_UNAWARE
3127                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3128        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3129        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3130                resolveFlags, UserHandle.USER_SYSTEM);
3131
3132        final int N = resolvers.size();
3133        if (N == 0) {
3134            if (DEBUG_EPHEMERAL) {
3135                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3136            }
3137            return null;
3138        }
3139
3140        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3141        for (int i = 0; i < N; i++) {
3142            final ResolveInfo info = resolvers.get(i);
3143
3144            if (info.serviceInfo == null) {
3145                continue;
3146            }
3147
3148            final String packageName = info.serviceInfo.packageName;
3149            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3150                if (DEBUG_EPHEMERAL) {
3151                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3152                            + " pkg: " + packageName + ", info:" + info);
3153                }
3154                continue;
3155            }
3156
3157            if (DEBUG_EPHEMERAL) {
3158                Slog.v(TAG, "Ephemeral resolver found;"
3159                        + " pkg: " + packageName + ", info:" + info);
3160            }
3161            return new ComponentName(packageName, info.serviceInfo.name);
3162        }
3163        if (DEBUG_EPHEMERAL) {
3164            Slog.v(TAG, "Ephemeral resolver NOT found");
3165        }
3166        return null;
3167    }
3168
3169    private @Nullable ActivityInfo getEphemeralInstallerLPr() {
3170        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3171        intent.addCategory(Intent.CATEGORY_DEFAULT);
3172        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3173
3174        final int resolveFlags =
3175                MATCH_DIRECT_BOOT_AWARE
3176                | MATCH_DIRECT_BOOT_UNAWARE
3177                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3178        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3179                resolveFlags, UserHandle.USER_SYSTEM);
3180        Iterator<ResolveInfo> iter = matches.iterator();
3181        while (iter.hasNext()) {
3182            final ResolveInfo rInfo = iter.next();
3183            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3184            if (ps != null) {
3185                final PermissionsState permissionsState = ps.getPermissionsState();
3186                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3187                    continue;
3188                }
3189            }
3190            iter.remove();
3191        }
3192        if (matches.size() == 0) {
3193            return null;
3194        } else if (matches.size() == 1) {
3195            return (ActivityInfo) matches.get(0).getComponentInfo();
3196        } else {
3197            throw new RuntimeException(
3198                    "There must be at most one ephemeral installer; found " + matches);
3199        }
3200    }
3201
3202    private @Nullable ComponentName getEphemeralResolverSettingsLPr() {
3203        final Intent intent = new Intent(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3204        intent.addCategory(Intent.CATEGORY_DEFAULT);
3205        final int resolveFlags =
3206                MATCH_DIRECT_BOOT_AWARE
3207                | MATCH_DIRECT_BOOT_UNAWARE
3208                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3209        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
3210                resolveFlags, UserHandle.USER_SYSTEM);
3211        Iterator<ResolveInfo> iter = matches.iterator();
3212        while (iter.hasNext()) {
3213            final ResolveInfo rInfo = iter.next();
3214            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3215            if (ps != null) {
3216                final PermissionsState permissionsState = ps.getPermissionsState();
3217                if (permissionsState.hasPermission(Manifest.permission.ACCESS_INSTANT_APPS, 0)) {
3218                    continue;
3219                }
3220            }
3221            iter.remove();
3222        }
3223        if (matches.size() == 0) {
3224            return null;
3225        } else if (matches.size() == 1) {
3226            return matches.get(0).getComponentInfo().getComponentName();
3227        } else {
3228            throw new RuntimeException(
3229                    "There must be at most one ephemeral resolver settings; found " + matches);
3230        }
3231    }
3232
3233    private void primeDomainVerificationsLPw(int userId) {
3234        if (DEBUG_DOMAIN_VERIFICATION) {
3235            Slog.d(TAG, "Priming domain verifications in user " + userId);
3236        }
3237
3238        SystemConfig systemConfig = SystemConfig.getInstance();
3239        ArraySet<String> packages = systemConfig.getLinkedApps();
3240
3241        for (String packageName : packages) {
3242            PackageParser.Package pkg = mPackages.get(packageName);
3243            if (pkg != null) {
3244                if (!pkg.isSystemApp()) {
3245                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3246                    continue;
3247                }
3248
3249                ArraySet<String> domains = null;
3250                for (PackageParser.Activity a : pkg.activities) {
3251                    for (ActivityIntentInfo filter : a.intents) {
3252                        if (hasValidDomains(filter)) {
3253                            if (domains == null) {
3254                                domains = new ArraySet<String>();
3255                            }
3256                            domains.addAll(filter.getHostsList());
3257                        }
3258                    }
3259                }
3260
3261                if (domains != null && domains.size() > 0) {
3262                    if (DEBUG_DOMAIN_VERIFICATION) {
3263                        Slog.v(TAG, "      + " + packageName);
3264                    }
3265                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3266                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3267                    // and then 'always' in the per-user state actually used for intent resolution.
3268                    final IntentFilterVerificationInfo ivi;
3269                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3270                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3271                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3272                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3273                } else {
3274                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3275                            + "' does not handle web links");
3276                }
3277            } else {
3278                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3279            }
3280        }
3281
3282        scheduleWritePackageRestrictionsLocked(userId);
3283        scheduleWriteSettingsLocked();
3284    }
3285
3286    private void applyFactoryDefaultBrowserLPw(int userId) {
3287        // The default browser app's package name is stored in a string resource,
3288        // with a product-specific overlay used for vendor customization.
3289        String browserPkg = mContext.getResources().getString(
3290                com.android.internal.R.string.default_browser);
3291        if (!TextUtils.isEmpty(browserPkg)) {
3292            // non-empty string => required to be a known package
3293            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3294            if (ps == null) {
3295                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3296                browserPkg = null;
3297            } else {
3298                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3299            }
3300        }
3301
3302        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3303        // default.  If there's more than one, just leave everything alone.
3304        if (browserPkg == null) {
3305            calculateDefaultBrowserLPw(userId);
3306        }
3307    }
3308
3309    private void calculateDefaultBrowserLPw(int userId) {
3310        List<String> allBrowsers = resolveAllBrowserApps(userId);
3311        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3312        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3313    }
3314
3315    private List<String> resolveAllBrowserApps(int userId) {
3316        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3317        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3318                PackageManager.MATCH_ALL, userId);
3319
3320        final int count = list.size();
3321        List<String> result = new ArrayList<String>(count);
3322        for (int i=0; i<count; i++) {
3323            ResolveInfo info = list.get(i);
3324            if (info.activityInfo == null
3325                    || !info.handleAllWebDataURI
3326                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3327                    || result.contains(info.activityInfo.packageName)) {
3328                continue;
3329            }
3330            result.add(info.activityInfo.packageName);
3331        }
3332
3333        return result;
3334    }
3335
3336    private boolean packageIsBrowser(String packageName, int userId) {
3337        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3338                PackageManager.MATCH_ALL, userId);
3339        final int N = list.size();
3340        for (int i = 0; i < N; i++) {
3341            ResolveInfo info = list.get(i);
3342            if (packageName.equals(info.activityInfo.packageName)) {
3343                return true;
3344            }
3345        }
3346        return false;
3347    }
3348
3349    private void checkDefaultBrowser() {
3350        final int myUserId = UserHandle.myUserId();
3351        final String packageName = getDefaultBrowserPackageName(myUserId);
3352        if (packageName != null) {
3353            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3354            if (info == null) {
3355                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3356                synchronized (mPackages) {
3357                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3358                }
3359            }
3360        }
3361    }
3362
3363    @Override
3364    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3365            throws RemoteException {
3366        try {
3367            return super.onTransact(code, data, reply, flags);
3368        } catch (RuntimeException e) {
3369            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3370                Slog.wtf(TAG, "Package Manager Crash", e);
3371            }
3372            throw e;
3373        }
3374    }
3375
3376    static int[] appendInts(int[] cur, int[] add) {
3377        if (add == null) return cur;
3378        if (cur == null) return add;
3379        final int N = add.length;
3380        for (int i=0; i<N; i++) {
3381            cur = appendInt(cur, add[i]);
3382        }
3383        return cur;
3384    }
3385
3386    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3387        if (!sUserManager.exists(userId)) return null;
3388        if (ps == null) {
3389            return null;
3390        }
3391        final PackageParser.Package p = ps.pkg;
3392        if (p == null) {
3393            return null;
3394        }
3395        // Filter out ephemeral app metadata:
3396        //   * The system/shell/root can see metadata for any app
3397        //   * An installed app can see metadata for 1) other installed apps
3398        //     and 2) ephemeral apps that have explicitly interacted with it
3399        //   * Ephemeral apps can only see their own data and exposed installed apps
3400        //   * Holding a signature permission allows seeing instant apps
3401        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3402        if (callingAppId != Process.SYSTEM_UID
3403                && callingAppId != Process.SHELL_UID
3404                && callingAppId != Process.ROOT_UID
3405                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3406                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3407            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3408            if (instantAppPackageName != null) {
3409                // ephemeral apps can only get information on themselves or
3410                // installed apps that are exposed.
3411                if (!instantAppPackageName.equals(p.packageName)
3412                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3413                    return null;
3414                }
3415            } else {
3416                if (ps.getInstantApp(userId)) {
3417                    // only get access to the ephemeral app if we've been granted access
3418                    if (!mInstantAppRegistry.isInstantAccessGranted(
3419                            userId, callingAppId, ps.appId)) {
3420                        return null;
3421                    }
3422                }
3423            }
3424        }
3425
3426        final PermissionsState permissionsState = ps.getPermissionsState();
3427
3428        // Compute GIDs only if requested
3429        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3430                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3431        // Compute granted permissions only if package has requested permissions
3432        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3433                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3434        final PackageUserState state = ps.readUserState(userId);
3435
3436        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3437                && ps.isSystem()) {
3438            flags |= MATCH_ANY_USER;
3439        }
3440
3441        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3442                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3443
3444        if (packageInfo == null) {
3445            return null;
3446        }
3447
3448        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3449
3450        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3451                resolveExternalPackageNameLPr(p);
3452
3453        return packageInfo;
3454    }
3455
3456    @Override
3457    public void checkPackageStartable(String packageName, int userId) {
3458        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3459
3460        synchronized (mPackages) {
3461            final PackageSetting ps = mSettings.mPackages.get(packageName);
3462            if (ps == null) {
3463                throw new SecurityException("Package " + packageName + " was not found!");
3464            }
3465
3466            if (!ps.getInstalled(userId)) {
3467                throw new SecurityException(
3468                        "Package " + packageName + " was not installed for user " + userId + "!");
3469            }
3470
3471            if (mSafeMode && !ps.isSystem()) {
3472                throw new SecurityException("Package " + packageName + " not a system app!");
3473            }
3474
3475            if (mFrozenPackages.contains(packageName)) {
3476                throw new SecurityException("Package " + packageName + " is currently frozen!");
3477            }
3478
3479            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3480                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3481                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3482            }
3483        }
3484    }
3485
3486    @Override
3487    public boolean isPackageAvailable(String packageName, int userId) {
3488        if (!sUserManager.exists(userId)) return false;
3489        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3490                false /* requireFullPermission */, false /* checkShell */, "is package available");
3491        synchronized (mPackages) {
3492            PackageParser.Package p = mPackages.get(packageName);
3493            if (p != null) {
3494                final PackageSetting ps = (PackageSetting) p.mExtras;
3495                if (ps != null) {
3496                    final PackageUserState state = ps.readUserState(userId);
3497                    if (state != null) {
3498                        return PackageParser.isAvailable(state);
3499                    }
3500                }
3501            }
3502        }
3503        return false;
3504    }
3505
3506    @Override
3507    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3508        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3509                flags, userId);
3510    }
3511
3512    @Override
3513    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3514            int flags, int userId) {
3515        return getPackageInfoInternal(versionedPackage.getPackageName(),
3516                // TODO: We will change version code to long, so in the new API it is long
3517                (int) versionedPackage.getVersionCode(), flags, userId);
3518    }
3519
3520    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3521            int flags, int userId) {
3522        if (!sUserManager.exists(userId)) return null;
3523        flags = updateFlagsForPackage(flags, userId, packageName);
3524        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3525                false /* requireFullPermission */, false /* checkShell */, "get package info");
3526
3527        // reader
3528        synchronized (mPackages) {
3529            // Normalize package name to handle renamed packages and static libs
3530            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3531
3532            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3533            if (matchFactoryOnly) {
3534                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3535                if (ps != null) {
3536                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3537                        return null;
3538                    }
3539                    return generatePackageInfo(ps, flags, userId);
3540                }
3541            }
3542
3543            PackageParser.Package p = mPackages.get(packageName);
3544            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3545                return null;
3546            }
3547            if (DEBUG_PACKAGE_INFO)
3548                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3549            if (p != null) {
3550                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3551                        Binder.getCallingUid(), userId)) {
3552                    return null;
3553                }
3554                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3555            }
3556            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3557                final PackageSetting ps = mSettings.mPackages.get(packageName);
3558                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3559                    return null;
3560                }
3561                return generatePackageInfo(ps, flags, userId);
3562            }
3563        }
3564        return null;
3565    }
3566
3567
3568    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3569        // System/shell/root get to see all static libs
3570        final int appId = UserHandle.getAppId(uid);
3571        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3572                || appId == Process.ROOT_UID) {
3573            return false;
3574        }
3575
3576        // No package means no static lib as it is always on internal storage
3577        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3578            return false;
3579        }
3580
3581        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3582                ps.pkg.staticSharedLibVersion);
3583        if (libEntry == null) {
3584            return false;
3585        }
3586
3587        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3588        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3589        if (uidPackageNames == null) {
3590            return true;
3591        }
3592
3593        for (String uidPackageName : uidPackageNames) {
3594            if (ps.name.equals(uidPackageName)) {
3595                return false;
3596            }
3597            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3598            if (uidPs != null) {
3599                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3600                        libEntry.info.getName());
3601                if (index < 0) {
3602                    continue;
3603                }
3604                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3605                    return false;
3606                }
3607            }
3608        }
3609        return true;
3610    }
3611
3612    @Override
3613    public String[] currentToCanonicalPackageNames(String[] names) {
3614        String[] out = new String[names.length];
3615        // reader
3616        synchronized (mPackages) {
3617            for (int i=names.length-1; i>=0; i--) {
3618                PackageSetting ps = mSettings.mPackages.get(names[i]);
3619                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3620            }
3621        }
3622        return out;
3623    }
3624
3625    @Override
3626    public String[] canonicalToCurrentPackageNames(String[] names) {
3627        String[] out = new String[names.length];
3628        // reader
3629        synchronized (mPackages) {
3630            for (int i=names.length-1; i>=0; i--) {
3631                String cur = mSettings.getRenamedPackageLPr(names[i]);
3632                out[i] = cur != null ? cur : names[i];
3633            }
3634        }
3635        return out;
3636    }
3637
3638    @Override
3639    public int getPackageUid(String packageName, int flags, int userId) {
3640        if (!sUserManager.exists(userId)) return -1;
3641        flags = updateFlagsForPackage(flags, userId, packageName);
3642        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3643                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3644
3645        // reader
3646        synchronized (mPackages) {
3647            final PackageParser.Package p = mPackages.get(packageName);
3648            if (p != null && p.isMatch(flags)) {
3649                return UserHandle.getUid(userId, p.applicationInfo.uid);
3650            }
3651            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3652                final PackageSetting ps = mSettings.mPackages.get(packageName);
3653                if (ps != null && ps.isMatch(flags)) {
3654                    return UserHandle.getUid(userId, ps.appId);
3655                }
3656            }
3657        }
3658
3659        return -1;
3660    }
3661
3662    @Override
3663    public int[] getPackageGids(String packageName, int flags, int userId) {
3664        if (!sUserManager.exists(userId)) return null;
3665        flags = updateFlagsForPackage(flags, userId, packageName);
3666        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3667                false /* requireFullPermission */, false /* checkShell */,
3668                "getPackageGids");
3669
3670        // reader
3671        synchronized (mPackages) {
3672            final PackageParser.Package p = mPackages.get(packageName);
3673            if (p != null && p.isMatch(flags)) {
3674                PackageSetting ps = (PackageSetting) p.mExtras;
3675                // TODO: Shouldn't this be checking for package installed state for userId and
3676                // return null?
3677                return ps.getPermissionsState().computeGids(userId);
3678            }
3679            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3680                final PackageSetting ps = mSettings.mPackages.get(packageName);
3681                if (ps != null && ps.isMatch(flags)) {
3682                    return ps.getPermissionsState().computeGids(userId);
3683                }
3684            }
3685        }
3686
3687        return null;
3688    }
3689
3690    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3691        if (bp.perm != null) {
3692            return PackageParser.generatePermissionInfo(bp.perm, flags);
3693        }
3694        PermissionInfo pi = new PermissionInfo();
3695        pi.name = bp.name;
3696        pi.packageName = bp.sourcePackage;
3697        pi.nonLocalizedLabel = bp.name;
3698        pi.protectionLevel = bp.protectionLevel;
3699        return pi;
3700    }
3701
3702    @Override
3703    public PermissionInfo getPermissionInfo(String name, int flags) {
3704        // reader
3705        synchronized (mPackages) {
3706            final BasePermission p = mSettings.mPermissions.get(name);
3707            if (p != null) {
3708                return generatePermissionInfo(p, flags);
3709            }
3710            return null;
3711        }
3712    }
3713
3714    @Override
3715    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3716            int flags) {
3717        // reader
3718        synchronized (mPackages) {
3719            if (group != null && !mPermissionGroups.containsKey(group)) {
3720                // This is thrown as NameNotFoundException
3721                return null;
3722            }
3723
3724            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3725            for (BasePermission p : mSettings.mPermissions.values()) {
3726                if (group == null) {
3727                    if (p.perm == null || p.perm.info.group == null) {
3728                        out.add(generatePermissionInfo(p, flags));
3729                    }
3730                } else {
3731                    if (p.perm != null && group.equals(p.perm.info.group)) {
3732                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3733                    }
3734                }
3735            }
3736            return new ParceledListSlice<>(out);
3737        }
3738    }
3739
3740    @Override
3741    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3742        // reader
3743        synchronized (mPackages) {
3744            return PackageParser.generatePermissionGroupInfo(
3745                    mPermissionGroups.get(name), flags);
3746        }
3747    }
3748
3749    @Override
3750    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3751        // reader
3752        synchronized (mPackages) {
3753            final int N = mPermissionGroups.size();
3754            ArrayList<PermissionGroupInfo> out
3755                    = new ArrayList<PermissionGroupInfo>(N);
3756            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3757                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3758            }
3759            return new ParceledListSlice<>(out);
3760        }
3761    }
3762
3763    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3764            int uid, int userId) {
3765        if (!sUserManager.exists(userId)) return null;
3766        PackageSetting ps = mSettings.mPackages.get(packageName);
3767        if (ps != null) {
3768            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3769                return null;
3770            }
3771            if (ps.pkg == null) {
3772                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3773                if (pInfo != null) {
3774                    return pInfo.applicationInfo;
3775                }
3776                return null;
3777            }
3778            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3779                    ps.readUserState(userId), userId);
3780            if (ai != null) {
3781                rebaseEnabledOverlays(ai, userId);
3782                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3783            }
3784            return ai;
3785        }
3786        return null;
3787    }
3788
3789    @Override
3790    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3791        if (!sUserManager.exists(userId)) return null;
3792        flags = updateFlagsForApplication(flags, userId, packageName);
3793        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3794                false /* requireFullPermission */, false /* checkShell */, "get application info");
3795
3796        // writer
3797        synchronized (mPackages) {
3798            // Normalize package name to handle renamed packages and static libs
3799            packageName = resolveInternalPackageNameLPr(packageName,
3800                    PackageManager.VERSION_CODE_HIGHEST);
3801
3802            PackageParser.Package p = mPackages.get(packageName);
3803            if (DEBUG_PACKAGE_INFO) Log.v(
3804                    TAG, "getApplicationInfo " + packageName
3805                    + ": " + p);
3806            if (p != null) {
3807                PackageSetting ps = mSettings.mPackages.get(packageName);
3808                if (ps == null) return null;
3809                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3810                    return null;
3811                }
3812                // Note: isEnabledLP() does not apply here - always return info
3813                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3814                        p, flags, ps.readUserState(userId), userId);
3815                if (ai != null) {
3816                    rebaseEnabledOverlays(ai, userId);
3817                    ai.packageName = resolveExternalPackageNameLPr(p);
3818                }
3819                return ai;
3820            }
3821            if ("android".equals(packageName)||"system".equals(packageName)) {
3822                return mAndroidApplication;
3823            }
3824            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3825                // Already generates the external package name
3826                return generateApplicationInfoFromSettingsLPw(packageName,
3827                        Binder.getCallingUid(), flags, userId);
3828            }
3829        }
3830        return null;
3831    }
3832
3833    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3834        List<String> paths = new ArrayList<>();
3835        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3836            mEnabledOverlayPaths.get(userId);
3837        if (userSpecificOverlays != null) {
3838            if (!"android".equals(ai.packageName)) {
3839                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3840                if (frameworkOverlays != null) {
3841                    paths.addAll(frameworkOverlays);
3842                }
3843            }
3844
3845            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3846            if (appOverlays != null) {
3847                paths.addAll(appOverlays);
3848            }
3849        }
3850        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3851    }
3852
3853    private String normalizePackageNameLPr(String packageName) {
3854        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3855        return normalizedPackageName != null ? normalizedPackageName : packageName;
3856    }
3857
3858    @Override
3859    public void deletePreloadsFileCache() {
3860        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3861            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3862        }
3863        File dir = Environment.getDataPreloadsFileCacheDirectory();
3864        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3865        FileUtils.deleteContents(dir);
3866    }
3867
3868    @Override
3869    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3870            final IPackageDataObserver observer) {
3871        mContext.enforceCallingOrSelfPermission(
3872                android.Manifest.permission.CLEAR_APP_CACHE, null);
3873        mHandler.post(() -> {
3874            boolean success = false;
3875            try {
3876                freeStorage(volumeUuid, freeStorageSize, 0);
3877                success = true;
3878            } catch (IOException e) {
3879                Slog.w(TAG, e);
3880            }
3881            if (observer != null) {
3882                try {
3883                    observer.onRemoveCompleted(null, success);
3884                } catch (RemoteException e) {
3885                    Slog.w(TAG, e);
3886                }
3887            }
3888        });
3889    }
3890
3891    @Override
3892    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3893            final IntentSender pi) {
3894        mContext.enforceCallingOrSelfPermission(
3895                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3896        mHandler.post(() -> {
3897            boolean success = false;
3898            try {
3899                freeStorage(volumeUuid, freeStorageSize, 0);
3900                success = true;
3901            } catch (IOException e) {
3902                Slog.w(TAG, e);
3903            }
3904            if (pi != null) {
3905                try {
3906                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3907                } catch (SendIntentException e) {
3908                    Slog.w(TAG, e);
3909                }
3910            }
3911        });
3912    }
3913
3914    /**
3915     * Blocking call to clear various types of cached data across the system
3916     * until the requested bytes are available.
3917     */
3918    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3919        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3920        final File file = storage.findPathForUuid(volumeUuid);
3921        if (file.getUsableSpace() >= bytes) return;
3922
3923        if (ENABLE_FREE_CACHE_V2) {
3924            final boolean aggressive = (storageFlags
3925                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3926            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3927                    volumeUuid);
3928
3929            // 1. Pre-flight to determine if we have any chance to succeed
3930            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3931            if (internalVolume && (aggressive || SystemProperties
3932                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3933                deletePreloadsFileCache();
3934                if (file.getUsableSpace() >= bytes) return;
3935            }
3936
3937            // 3. Consider parsed APK data (aggressive only)
3938            if (internalVolume && aggressive) {
3939                FileUtils.deleteContents(mCacheDir);
3940                if (file.getUsableSpace() >= bytes) return;
3941            }
3942
3943            // 4. Consider cached app data (above quotas)
3944            try {
3945                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3946            } catch (InstallerException ignored) {
3947            }
3948            if (file.getUsableSpace() >= bytes) return;
3949
3950            // 5. Consider shared libraries with refcount=0 and age>2h
3951            // 6. Consider dexopt output (aggressive only)
3952            // 7. Consider ephemeral apps not used in last week
3953
3954            // 8. Consider cached app data (below quotas)
3955            try {
3956                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3957                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3958            } catch (InstallerException ignored) {
3959            }
3960            if (file.getUsableSpace() >= bytes) return;
3961
3962            // 9. Consider DropBox entries
3963            // 10. Consider ephemeral cookies
3964
3965        } else {
3966            try {
3967                mInstaller.freeCache(volumeUuid, bytes, 0);
3968            } catch (InstallerException ignored) {
3969            }
3970            if (file.getUsableSpace() >= bytes) return;
3971        }
3972
3973        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3974    }
3975
3976    /**
3977     * Update given flags based on encryption status of current user.
3978     */
3979    private int updateFlags(int flags, int userId) {
3980        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3981                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3982            // Caller expressed an explicit opinion about what encryption
3983            // aware/unaware components they want to see, so fall through and
3984            // give them what they want
3985        } else {
3986            // Caller expressed no opinion, so match based on user state
3987            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3988                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3989            } else {
3990                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3991            }
3992        }
3993        return flags;
3994    }
3995
3996    private UserManagerInternal getUserManagerInternal() {
3997        if (mUserManagerInternal == null) {
3998            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3999        }
4000        return mUserManagerInternal;
4001    }
4002
4003    private DeviceIdleController.LocalService getDeviceIdleController() {
4004        if (mDeviceIdleController == null) {
4005            mDeviceIdleController =
4006                    LocalServices.getService(DeviceIdleController.LocalService.class);
4007        }
4008        return mDeviceIdleController;
4009    }
4010
4011    /**
4012     * Update given flags when being used to request {@link PackageInfo}.
4013     */
4014    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4015        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4016        boolean triaged = true;
4017        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4018                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4019            // Caller is asking for component details, so they'd better be
4020            // asking for specific encryption matching behavior, or be triaged
4021            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4022                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4023                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4024                triaged = false;
4025            }
4026        }
4027        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4028                | PackageManager.MATCH_SYSTEM_ONLY
4029                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4030            triaged = false;
4031        }
4032        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4033            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4034                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4035                    + Debug.getCallers(5));
4036        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4037                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4038            // If the caller wants all packages and has a restricted profile associated with it,
4039            // then match all users. This is to make sure that launchers that need to access work
4040            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4041            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4042            flags |= PackageManager.MATCH_ANY_USER;
4043        }
4044        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4045            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4046                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4047        }
4048        return updateFlags(flags, userId);
4049    }
4050
4051    /**
4052     * Update given flags when being used to request {@link ApplicationInfo}.
4053     */
4054    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4055        return updateFlagsForPackage(flags, userId, cookie);
4056    }
4057
4058    /**
4059     * Update given flags when being used to request {@link ComponentInfo}.
4060     */
4061    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4062        if (cookie instanceof Intent) {
4063            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4064                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4065            }
4066        }
4067
4068        boolean triaged = true;
4069        // Caller is asking for component details, so they'd better be
4070        // asking for specific encryption matching behavior, or be triaged
4071        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4072                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4073                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4074            triaged = false;
4075        }
4076        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4077            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4078                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4079        }
4080
4081        return updateFlags(flags, userId);
4082    }
4083
4084    /**
4085     * Update given intent when being used to request {@link ResolveInfo}.
4086     */
4087    private Intent updateIntentForResolve(Intent intent) {
4088        if (intent.getSelector() != null) {
4089            intent = intent.getSelector();
4090        }
4091        if (DEBUG_PREFERRED) {
4092            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4093        }
4094        return intent;
4095    }
4096
4097    /**
4098     * Update given flags when being used to request {@link ResolveInfo}.
4099     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4100     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4101     * flag set. However, this flag is only honoured in three circumstances:
4102     * <ul>
4103     * <li>when called from a system process</li>
4104     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4105     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4106     * action and a {@code android.intent.category.BROWSABLE} category</li>
4107     * </ul>
4108     */
4109    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4110        // Safe mode means we shouldn't match any third-party components
4111        if (mSafeMode) {
4112            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4113        }
4114        final int callingUid = Binder.getCallingUid();
4115        if (getInstantAppPackageName(callingUid) != null) {
4116            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4117            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4118            flags |= PackageManager.MATCH_INSTANT;
4119        } else {
4120            // Otherwise, prevent leaking ephemeral components
4121            final boolean isSpecialProcess =
4122                    callingUid == Process.SYSTEM_UID
4123                    || callingUid == Process.SHELL_UID
4124                    || callingUid == 0;
4125            final boolean allowMatchInstant =
4126                    (includeInstantApp
4127                            && Intent.ACTION_VIEW.equals(intent.getAction())
4128                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4129                            && hasWebURI(intent))
4130                    || isSpecialProcess
4131                    || mContext.checkCallingOrSelfPermission(
4132                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4133            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4134            if (!allowMatchInstant) {
4135                flags &= ~PackageManager.MATCH_INSTANT;
4136            }
4137        }
4138        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4139    }
4140
4141    @Override
4142    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4143        if (!sUserManager.exists(userId)) return null;
4144        flags = updateFlagsForComponent(flags, userId, component);
4145        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4146                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4147        synchronized (mPackages) {
4148            PackageParser.Activity a = mActivities.mActivities.get(component);
4149
4150            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4151            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4152                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4153                if (ps == null) return null;
4154                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4155                        userId);
4156            }
4157            if (mResolveComponentName.equals(component)) {
4158                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4159                        new PackageUserState(), userId);
4160            }
4161        }
4162        return null;
4163    }
4164
4165    @Override
4166    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4167            String resolvedType) {
4168        synchronized (mPackages) {
4169            if (component.equals(mResolveComponentName)) {
4170                // The resolver supports EVERYTHING!
4171                return true;
4172            }
4173            PackageParser.Activity a = mActivities.mActivities.get(component);
4174            if (a == null) {
4175                return false;
4176            }
4177            for (int i=0; i<a.intents.size(); i++) {
4178                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4179                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4180                    return true;
4181                }
4182            }
4183            return false;
4184        }
4185    }
4186
4187    @Override
4188    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4189        if (!sUserManager.exists(userId)) return null;
4190        flags = updateFlagsForComponent(flags, userId, component);
4191        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4192                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4193        synchronized (mPackages) {
4194            PackageParser.Activity a = mReceivers.mActivities.get(component);
4195            if (DEBUG_PACKAGE_INFO) Log.v(
4196                TAG, "getReceiverInfo " + component + ": " + a);
4197            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4198                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4199                if (ps == null) return null;
4200                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4201                        ps.readUserState(userId), userId);
4202                if (ri != null) {
4203                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4204                }
4205                return ri;
4206            }
4207        }
4208        return null;
4209    }
4210
4211    @Override
4212    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4213        if (!sUserManager.exists(userId)) return null;
4214        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4215
4216        flags = updateFlagsForPackage(flags, userId, null);
4217
4218        final boolean canSeeStaticLibraries =
4219                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4220                        == PERMISSION_GRANTED
4221                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4222                        == PERMISSION_GRANTED
4223                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4224                        == PERMISSION_GRANTED
4225                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4226                        == PERMISSION_GRANTED;
4227
4228        synchronized (mPackages) {
4229            List<SharedLibraryInfo> result = null;
4230
4231            final int libCount = mSharedLibraries.size();
4232            for (int i = 0; i < libCount; i++) {
4233                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4234                if (versionedLib == null) {
4235                    continue;
4236                }
4237
4238                final int versionCount = versionedLib.size();
4239                for (int j = 0; j < versionCount; j++) {
4240                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4241                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4242                        break;
4243                    }
4244                    final long identity = Binder.clearCallingIdentity();
4245                    try {
4246                        // TODO: We will change version code to long, so in the new API it is long
4247                        PackageInfo packageInfo = getPackageInfoVersioned(
4248                                libInfo.getDeclaringPackage(), flags, userId);
4249                        if (packageInfo == null) {
4250                            continue;
4251                        }
4252                    } finally {
4253                        Binder.restoreCallingIdentity(identity);
4254                    }
4255
4256                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4257                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4258                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4259
4260                    if (result == null) {
4261                        result = new ArrayList<>();
4262                    }
4263                    result.add(resLibInfo);
4264                }
4265            }
4266
4267            return result != null ? new ParceledListSlice<>(result) : null;
4268        }
4269    }
4270
4271    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4272            SharedLibraryInfo libInfo, int flags, int userId) {
4273        List<VersionedPackage> versionedPackages = null;
4274        final int packageCount = mSettings.mPackages.size();
4275        for (int i = 0; i < packageCount; i++) {
4276            PackageSetting ps = mSettings.mPackages.valueAt(i);
4277
4278            if (ps == null) {
4279                continue;
4280            }
4281
4282            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4283                continue;
4284            }
4285
4286            final String libName = libInfo.getName();
4287            if (libInfo.isStatic()) {
4288                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4289                if (libIdx < 0) {
4290                    continue;
4291                }
4292                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4293                    continue;
4294                }
4295                if (versionedPackages == null) {
4296                    versionedPackages = new ArrayList<>();
4297                }
4298                // If the dependent is a static shared lib, use the public package name
4299                String dependentPackageName = ps.name;
4300                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4301                    dependentPackageName = ps.pkg.manifestPackageName;
4302                }
4303                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4304            } else if (ps.pkg != null) {
4305                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4306                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4307                    if (versionedPackages == null) {
4308                        versionedPackages = new ArrayList<>();
4309                    }
4310                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4311                }
4312            }
4313        }
4314
4315        return versionedPackages;
4316    }
4317
4318    @Override
4319    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4320        if (!sUserManager.exists(userId)) return null;
4321        flags = updateFlagsForComponent(flags, userId, component);
4322        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4323                false /* requireFullPermission */, false /* checkShell */, "get service info");
4324        synchronized (mPackages) {
4325            PackageParser.Service s = mServices.mServices.get(component);
4326            if (DEBUG_PACKAGE_INFO) Log.v(
4327                TAG, "getServiceInfo " + component + ": " + s);
4328            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4329                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4330                if (ps == null) return null;
4331                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4332                        ps.readUserState(userId), userId);
4333                if (si != null) {
4334                    rebaseEnabledOverlays(si.applicationInfo, userId);
4335                }
4336                return si;
4337            }
4338        }
4339        return null;
4340    }
4341
4342    @Override
4343    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4344        if (!sUserManager.exists(userId)) return null;
4345        flags = updateFlagsForComponent(flags, userId, component);
4346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4347                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4348        synchronized (mPackages) {
4349            PackageParser.Provider p = mProviders.mProviders.get(component);
4350            if (DEBUG_PACKAGE_INFO) Log.v(
4351                TAG, "getProviderInfo " + component + ": " + p);
4352            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4353                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4354                if (ps == null) return null;
4355                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4356                        ps.readUserState(userId), userId);
4357                if (pi != null) {
4358                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4359                }
4360                return pi;
4361            }
4362        }
4363        return null;
4364    }
4365
4366    @Override
4367    public String[] getSystemSharedLibraryNames() {
4368        synchronized (mPackages) {
4369            Set<String> libs = null;
4370            final int libCount = mSharedLibraries.size();
4371            for (int i = 0; i < libCount; i++) {
4372                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4373                if (versionedLib == null) {
4374                    continue;
4375                }
4376                final int versionCount = versionedLib.size();
4377                for (int j = 0; j < versionCount; j++) {
4378                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4379                    if (!libEntry.info.isStatic()) {
4380                        if (libs == null) {
4381                            libs = new ArraySet<>();
4382                        }
4383                        libs.add(libEntry.info.getName());
4384                        break;
4385                    }
4386                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4387                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4388                            UserHandle.getUserId(Binder.getCallingUid()))) {
4389                        if (libs == null) {
4390                            libs = new ArraySet<>();
4391                        }
4392                        libs.add(libEntry.info.getName());
4393                        break;
4394                    }
4395                }
4396            }
4397
4398            if (libs != null) {
4399                String[] libsArray = new String[libs.size()];
4400                libs.toArray(libsArray);
4401                return libsArray;
4402            }
4403
4404            return null;
4405        }
4406    }
4407
4408    @Override
4409    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4410        synchronized (mPackages) {
4411            return mServicesSystemSharedLibraryPackageName;
4412        }
4413    }
4414
4415    @Override
4416    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4417        synchronized (mPackages) {
4418            return mSharedSystemSharedLibraryPackageName;
4419        }
4420    }
4421
4422    private void updateSequenceNumberLP(String packageName, int[] userList) {
4423        for (int i = userList.length - 1; i >= 0; --i) {
4424            final int userId = userList[i];
4425            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4426            if (changedPackages == null) {
4427                changedPackages = new SparseArray<>();
4428                mChangedPackages.put(userId, changedPackages);
4429            }
4430            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4431            if (sequenceNumbers == null) {
4432                sequenceNumbers = new HashMap<>();
4433                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4434            }
4435            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4436            if (sequenceNumber != null) {
4437                changedPackages.remove(sequenceNumber);
4438            }
4439            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4440            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4441        }
4442        mChangedPackagesSequenceNumber++;
4443    }
4444
4445    @Override
4446    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4447        synchronized (mPackages) {
4448            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4449                return null;
4450            }
4451            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4452            if (changedPackages == null) {
4453                return null;
4454            }
4455            final List<String> packageNames =
4456                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4457            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4458                final String packageName = changedPackages.get(i);
4459                if (packageName != null) {
4460                    packageNames.add(packageName);
4461                }
4462            }
4463            return packageNames.isEmpty()
4464                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4465        }
4466    }
4467
4468    @Override
4469    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4470        ArrayList<FeatureInfo> res;
4471        synchronized (mAvailableFeatures) {
4472            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4473            res.addAll(mAvailableFeatures.values());
4474        }
4475        final FeatureInfo fi = new FeatureInfo();
4476        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4477                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4478        res.add(fi);
4479
4480        return new ParceledListSlice<>(res);
4481    }
4482
4483    @Override
4484    public boolean hasSystemFeature(String name, int version) {
4485        synchronized (mAvailableFeatures) {
4486            final FeatureInfo feat = mAvailableFeatures.get(name);
4487            if (feat == null) {
4488                return false;
4489            } else {
4490                return feat.version >= version;
4491            }
4492        }
4493    }
4494
4495    @Override
4496    public int checkPermission(String permName, String pkgName, int userId) {
4497        if (!sUserManager.exists(userId)) {
4498            return PackageManager.PERMISSION_DENIED;
4499        }
4500
4501        synchronized (mPackages) {
4502            final PackageParser.Package p = mPackages.get(pkgName);
4503            if (p != null && p.mExtras != null) {
4504                final PackageSetting ps = (PackageSetting) p.mExtras;
4505                final PermissionsState permissionsState = ps.getPermissionsState();
4506                if (permissionsState.hasPermission(permName, userId)) {
4507                    return PackageManager.PERMISSION_GRANTED;
4508                }
4509                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4510                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4511                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4512                    return PackageManager.PERMISSION_GRANTED;
4513                }
4514            }
4515        }
4516
4517        return PackageManager.PERMISSION_DENIED;
4518    }
4519
4520    @Override
4521    public int checkUidPermission(String permName, int uid) {
4522        final int userId = UserHandle.getUserId(uid);
4523
4524        if (!sUserManager.exists(userId)) {
4525            return PackageManager.PERMISSION_DENIED;
4526        }
4527
4528        synchronized (mPackages) {
4529            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4530            if (obj != null) {
4531                final SettingBase ps = (SettingBase) obj;
4532                final PermissionsState permissionsState = ps.getPermissionsState();
4533                if (permissionsState.hasPermission(permName, userId)) {
4534                    return PackageManager.PERMISSION_GRANTED;
4535                }
4536                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4537                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4538                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4539                    return PackageManager.PERMISSION_GRANTED;
4540                }
4541            } else {
4542                ArraySet<String> perms = mSystemPermissions.get(uid);
4543                if (perms != null) {
4544                    if (perms.contains(permName)) {
4545                        return PackageManager.PERMISSION_GRANTED;
4546                    }
4547                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4548                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4549                        return PackageManager.PERMISSION_GRANTED;
4550                    }
4551                }
4552            }
4553        }
4554
4555        return PackageManager.PERMISSION_DENIED;
4556    }
4557
4558    @Override
4559    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4560        if (UserHandle.getCallingUserId() != userId) {
4561            mContext.enforceCallingPermission(
4562                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4563                    "isPermissionRevokedByPolicy for user " + userId);
4564        }
4565
4566        if (checkPermission(permission, packageName, userId)
4567                == PackageManager.PERMISSION_GRANTED) {
4568            return false;
4569        }
4570
4571        final long identity = Binder.clearCallingIdentity();
4572        try {
4573            final int flags = getPermissionFlags(permission, packageName, userId);
4574            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4575        } finally {
4576            Binder.restoreCallingIdentity(identity);
4577        }
4578    }
4579
4580    @Override
4581    public String getPermissionControllerPackageName() {
4582        synchronized (mPackages) {
4583            return mRequiredInstallerPackage;
4584        }
4585    }
4586
4587    /**
4588     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4589     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4590     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4591     * @param message the message to log on security exception
4592     */
4593    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4594            boolean checkShell, String message) {
4595        if (userId < 0) {
4596            throw new IllegalArgumentException("Invalid userId " + userId);
4597        }
4598        if (checkShell) {
4599            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4600        }
4601        if (userId == UserHandle.getUserId(callingUid)) return;
4602        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4603            if (requireFullPermission) {
4604                mContext.enforceCallingOrSelfPermission(
4605                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4606            } else {
4607                try {
4608                    mContext.enforceCallingOrSelfPermission(
4609                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4610                } catch (SecurityException se) {
4611                    mContext.enforceCallingOrSelfPermission(
4612                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4613                }
4614            }
4615        }
4616    }
4617
4618    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4619        if (callingUid == Process.SHELL_UID) {
4620            if (userHandle >= 0
4621                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4622                throw new SecurityException("Shell does not have permission to access user "
4623                        + userHandle);
4624            } else if (userHandle < 0) {
4625                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4626                        + Debug.getCallers(3));
4627            }
4628        }
4629    }
4630
4631    private BasePermission findPermissionTreeLP(String permName) {
4632        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4633            if (permName.startsWith(bp.name) &&
4634                    permName.length() > bp.name.length() &&
4635                    permName.charAt(bp.name.length()) == '.') {
4636                return bp;
4637            }
4638        }
4639        return null;
4640    }
4641
4642    private BasePermission checkPermissionTreeLP(String permName) {
4643        if (permName != null) {
4644            BasePermission bp = findPermissionTreeLP(permName);
4645            if (bp != null) {
4646                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4647                    return bp;
4648                }
4649                throw new SecurityException("Calling uid "
4650                        + Binder.getCallingUid()
4651                        + " is not allowed to add to permission tree "
4652                        + bp.name + " owned by uid " + bp.uid);
4653            }
4654        }
4655        throw new SecurityException("No permission tree found for " + permName);
4656    }
4657
4658    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4659        if (s1 == null) {
4660            return s2 == null;
4661        }
4662        if (s2 == null) {
4663            return false;
4664        }
4665        if (s1.getClass() != s2.getClass()) {
4666            return false;
4667        }
4668        return s1.equals(s2);
4669    }
4670
4671    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4672        if (pi1.icon != pi2.icon) return false;
4673        if (pi1.logo != pi2.logo) return false;
4674        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4675        if (!compareStrings(pi1.name, pi2.name)) return false;
4676        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4677        // We'll take care of setting this one.
4678        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4679        // These are not currently stored in settings.
4680        //if (!compareStrings(pi1.group, pi2.group)) return false;
4681        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4682        //if (pi1.labelRes != pi2.labelRes) return false;
4683        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4684        return true;
4685    }
4686
4687    int permissionInfoFootprint(PermissionInfo info) {
4688        int size = info.name.length();
4689        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4690        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4691        return size;
4692    }
4693
4694    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4695        int size = 0;
4696        for (BasePermission perm : mSettings.mPermissions.values()) {
4697            if (perm.uid == tree.uid) {
4698                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4699            }
4700        }
4701        return size;
4702    }
4703
4704    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4705        // We calculate the max size of permissions defined by this uid and throw
4706        // if that plus the size of 'info' would exceed our stated maximum.
4707        if (tree.uid != Process.SYSTEM_UID) {
4708            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4709            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4710                throw new SecurityException("Permission tree size cap exceeded");
4711            }
4712        }
4713    }
4714
4715    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4716        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4717            throw new SecurityException("Label must be specified in permission");
4718        }
4719        BasePermission tree = checkPermissionTreeLP(info.name);
4720        BasePermission bp = mSettings.mPermissions.get(info.name);
4721        boolean added = bp == null;
4722        boolean changed = true;
4723        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4724        if (added) {
4725            enforcePermissionCapLocked(info, tree);
4726            bp = new BasePermission(info.name, tree.sourcePackage,
4727                    BasePermission.TYPE_DYNAMIC);
4728        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4729            throw new SecurityException(
4730                    "Not allowed to modify non-dynamic permission "
4731                    + info.name);
4732        } else {
4733            if (bp.protectionLevel == fixedLevel
4734                    && bp.perm.owner.equals(tree.perm.owner)
4735                    && bp.uid == tree.uid
4736                    && comparePermissionInfos(bp.perm.info, info)) {
4737                changed = false;
4738            }
4739        }
4740        bp.protectionLevel = fixedLevel;
4741        info = new PermissionInfo(info);
4742        info.protectionLevel = fixedLevel;
4743        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4744        bp.perm.info.packageName = tree.perm.info.packageName;
4745        bp.uid = tree.uid;
4746        if (added) {
4747            mSettings.mPermissions.put(info.name, bp);
4748        }
4749        if (changed) {
4750            if (!async) {
4751                mSettings.writeLPr();
4752            } else {
4753                scheduleWriteSettingsLocked();
4754            }
4755        }
4756        return added;
4757    }
4758
4759    @Override
4760    public boolean addPermission(PermissionInfo info) {
4761        synchronized (mPackages) {
4762            return addPermissionLocked(info, false);
4763        }
4764    }
4765
4766    @Override
4767    public boolean addPermissionAsync(PermissionInfo info) {
4768        synchronized (mPackages) {
4769            return addPermissionLocked(info, true);
4770        }
4771    }
4772
4773    @Override
4774    public void removePermission(String name) {
4775        synchronized (mPackages) {
4776            checkPermissionTreeLP(name);
4777            BasePermission bp = mSettings.mPermissions.get(name);
4778            if (bp != null) {
4779                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4780                    throw new SecurityException(
4781                            "Not allowed to modify non-dynamic permission "
4782                            + name);
4783                }
4784                mSettings.mPermissions.remove(name);
4785                mSettings.writeLPr();
4786            }
4787        }
4788    }
4789
4790    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4791            BasePermission bp) {
4792        int index = pkg.requestedPermissions.indexOf(bp.name);
4793        if (index == -1) {
4794            throw new SecurityException("Package " + pkg.packageName
4795                    + " has not requested permission " + bp.name);
4796        }
4797        if (!bp.isRuntime() && !bp.isDevelopment()) {
4798            throw new SecurityException("Permission " + bp.name
4799                    + " is not a changeable permission type");
4800        }
4801    }
4802
4803    @Override
4804    public void grantRuntimePermission(String packageName, String name, final int userId) {
4805        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4806    }
4807
4808    private void grantRuntimePermission(String packageName, String name, final int userId,
4809            boolean overridePolicy) {
4810        if (!sUserManager.exists(userId)) {
4811            Log.e(TAG, "No such user:" + userId);
4812            return;
4813        }
4814
4815        mContext.enforceCallingOrSelfPermission(
4816                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4817                "grantRuntimePermission");
4818
4819        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4820                true /* requireFullPermission */, true /* checkShell */,
4821                "grantRuntimePermission");
4822
4823        final int uid;
4824        final SettingBase sb;
4825
4826        synchronized (mPackages) {
4827            final PackageParser.Package pkg = mPackages.get(packageName);
4828            if (pkg == null) {
4829                throw new IllegalArgumentException("Unknown package: " + packageName);
4830            }
4831
4832            final BasePermission bp = mSettings.mPermissions.get(name);
4833            if (bp == null) {
4834                throw new IllegalArgumentException("Unknown permission: " + name);
4835            }
4836
4837            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4838
4839            // If a permission review is required for legacy apps we represent
4840            // their permissions as always granted runtime ones since we need
4841            // to keep the review required permission flag per user while an
4842            // install permission's state is shared across all users.
4843            if (mPermissionReviewRequired
4844                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4845                    && bp.isRuntime()) {
4846                return;
4847            }
4848
4849            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4850            sb = (SettingBase) pkg.mExtras;
4851            if (sb == null) {
4852                throw new IllegalArgumentException("Unknown package: " + packageName);
4853            }
4854
4855            final PermissionsState permissionsState = sb.getPermissionsState();
4856
4857            final int flags = permissionsState.getPermissionFlags(name, userId);
4858            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4859                throw new SecurityException("Cannot grant system fixed permission "
4860                        + name + " for package " + packageName);
4861            }
4862            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4863                throw new SecurityException("Cannot grant policy fixed permission "
4864                        + name + " for package " + packageName);
4865            }
4866
4867            if (bp.isDevelopment()) {
4868                // Development permissions must be handled specially, since they are not
4869                // normal runtime permissions.  For now they apply to all users.
4870                if (permissionsState.grantInstallPermission(bp) !=
4871                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4872                    scheduleWriteSettingsLocked();
4873                }
4874                return;
4875            }
4876
4877            final PackageSetting ps = mSettings.mPackages.get(packageName);
4878            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4879                throw new SecurityException("Cannot grant non-ephemeral permission"
4880                        + name + " for package " + packageName);
4881            }
4882
4883            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4884                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4885                return;
4886            }
4887
4888            final int result = permissionsState.grantRuntimePermission(bp, userId);
4889            switch (result) {
4890                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4891                    return;
4892                }
4893
4894                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4895                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4896                    mHandler.post(new Runnable() {
4897                        @Override
4898                        public void run() {
4899                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4900                        }
4901                    });
4902                }
4903                break;
4904            }
4905
4906            if (bp.isRuntime()) {
4907                logPermissionGranted(mContext, name, packageName);
4908            }
4909
4910            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4911
4912            // Not critical if that is lost - app has to request again.
4913            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4914        }
4915
4916        // Only need to do this if user is initialized. Otherwise it's a new user
4917        // and there are no processes running as the user yet and there's no need
4918        // to make an expensive call to remount processes for the changed permissions.
4919        if (READ_EXTERNAL_STORAGE.equals(name)
4920                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4921            final long token = Binder.clearCallingIdentity();
4922            try {
4923                if (sUserManager.isInitialized(userId)) {
4924                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4925                            StorageManagerInternal.class);
4926                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4927                }
4928            } finally {
4929                Binder.restoreCallingIdentity(token);
4930            }
4931        }
4932    }
4933
4934    @Override
4935    public void revokeRuntimePermission(String packageName, String name, int userId) {
4936        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4937    }
4938
4939    private void revokeRuntimePermission(String packageName, String name, int userId,
4940            boolean overridePolicy) {
4941        if (!sUserManager.exists(userId)) {
4942            Log.e(TAG, "No such user:" + userId);
4943            return;
4944        }
4945
4946        mContext.enforceCallingOrSelfPermission(
4947                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4948                "revokeRuntimePermission");
4949
4950        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4951                true /* requireFullPermission */, true /* checkShell */,
4952                "revokeRuntimePermission");
4953
4954        final int appId;
4955
4956        synchronized (mPackages) {
4957            final PackageParser.Package pkg = mPackages.get(packageName);
4958            if (pkg == null) {
4959                throw new IllegalArgumentException("Unknown package: " + packageName);
4960            }
4961
4962            final BasePermission bp = mSettings.mPermissions.get(name);
4963            if (bp == null) {
4964                throw new IllegalArgumentException("Unknown permission: " + name);
4965            }
4966
4967            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4968
4969            // If a permission review is required for legacy apps we represent
4970            // their permissions as always granted runtime ones since we need
4971            // to keep the review required permission flag per user while an
4972            // install permission's state is shared across all users.
4973            if (mPermissionReviewRequired
4974                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4975                    && bp.isRuntime()) {
4976                return;
4977            }
4978
4979            SettingBase sb = (SettingBase) pkg.mExtras;
4980            if (sb == null) {
4981                throw new IllegalArgumentException("Unknown package: " + packageName);
4982            }
4983
4984            final PermissionsState permissionsState = sb.getPermissionsState();
4985
4986            final int flags = permissionsState.getPermissionFlags(name, userId);
4987            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4988                throw new SecurityException("Cannot revoke system fixed permission "
4989                        + name + " for package " + packageName);
4990            }
4991            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4992                throw new SecurityException("Cannot revoke policy fixed permission "
4993                        + name + " for package " + packageName);
4994            }
4995
4996            if (bp.isDevelopment()) {
4997                // Development permissions must be handled specially, since they are not
4998                // normal runtime permissions.  For now they apply to all users.
4999                if (permissionsState.revokeInstallPermission(bp) !=
5000                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5001                    scheduleWriteSettingsLocked();
5002                }
5003                return;
5004            }
5005
5006            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5007                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5008                return;
5009            }
5010
5011            if (bp.isRuntime()) {
5012                logPermissionRevoked(mContext, name, packageName);
5013            }
5014
5015            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5016
5017            // Critical, after this call app should never have the permission.
5018            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5019
5020            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5021        }
5022
5023        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5024    }
5025
5026    /**
5027     * Get the first event id for the permission.
5028     *
5029     * <p>There are four events for each permission: <ul>
5030     *     <li>Request permission: first id + 0</li>
5031     *     <li>Grant permission: first id + 1</li>
5032     *     <li>Request for permission denied: first id + 2</li>
5033     *     <li>Revoke permission: first id + 3</li>
5034     * </ul></p>
5035     *
5036     * @param name name of the permission
5037     *
5038     * @return The first event id for the permission
5039     */
5040    private static int getBaseEventId(@NonNull String name) {
5041        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5042
5043        if (eventIdIndex == -1) {
5044            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5045                    || "user".equals(Build.TYPE)) {
5046                Log.i(TAG, "Unknown permission " + name);
5047
5048                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5049            } else {
5050                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5051                //
5052                // Also update
5053                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5054                // - metrics_constants.proto
5055                throw new IllegalStateException("Unknown permission " + name);
5056            }
5057        }
5058
5059        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5060    }
5061
5062    /**
5063     * Log that a permission was revoked.
5064     *
5065     * @param context Context of the caller
5066     * @param name name of the permission
5067     * @param packageName package permission if for
5068     */
5069    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5070            @NonNull String packageName) {
5071        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5072    }
5073
5074    /**
5075     * Log that a permission request was granted.
5076     *
5077     * @param context Context of the caller
5078     * @param name name of the permission
5079     * @param packageName package permission if for
5080     */
5081    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5082            @NonNull String packageName) {
5083        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5084    }
5085
5086    @Override
5087    public void resetRuntimePermissions() {
5088        mContext.enforceCallingOrSelfPermission(
5089                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5090                "revokeRuntimePermission");
5091
5092        int callingUid = Binder.getCallingUid();
5093        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5094            mContext.enforceCallingOrSelfPermission(
5095                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5096                    "resetRuntimePermissions");
5097        }
5098
5099        synchronized (mPackages) {
5100            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5101            for (int userId : UserManagerService.getInstance().getUserIds()) {
5102                final int packageCount = mPackages.size();
5103                for (int i = 0; i < packageCount; i++) {
5104                    PackageParser.Package pkg = mPackages.valueAt(i);
5105                    if (!(pkg.mExtras instanceof PackageSetting)) {
5106                        continue;
5107                    }
5108                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5109                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5110                }
5111            }
5112        }
5113    }
5114
5115    @Override
5116    public int getPermissionFlags(String name, String packageName, int userId) {
5117        if (!sUserManager.exists(userId)) {
5118            return 0;
5119        }
5120
5121        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5122
5123        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5124                true /* requireFullPermission */, false /* checkShell */,
5125                "getPermissionFlags");
5126
5127        synchronized (mPackages) {
5128            final PackageParser.Package pkg = mPackages.get(packageName);
5129            if (pkg == null) {
5130                return 0;
5131            }
5132
5133            final BasePermission bp = mSettings.mPermissions.get(name);
5134            if (bp == null) {
5135                return 0;
5136            }
5137
5138            SettingBase sb = (SettingBase) pkg.mExtras;
5139            if (sb == null) {
5140                return 0;
5141            }
5142
5143            PermissionsState permissionsState = sb.getPermissionsState();
5144            return permissionsState.getPermissionFlags(name, userId);
5145        }
5146    }
5147
5148    @Override
5149    public void updatePermissionFlags(String name, String packageName, int flagMask,
5150            int flagValues, int userId) {
5151        if (!sUserManager.exists(userId)) {
5152            return;
5153        }
5154
5155        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5156
5157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5158                true /* requireFullPermission */, true /* checkShell */,
5159                "updatePermissionFlags");
5160
5161        // Only the system can change these flags and nothing else.
5162        if (getCallingUid() != Process.SYSTEM_UID) {
5163            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5164            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5165            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5166            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5167            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5168        }
5169
5170        synchronized (mPackages) {
5171            final PackageParser.Package pkg = mPackages.get(packageName);
5172            if (pkg == null) {
5173                throw new IllegalArgumentException("Unknown package: " + packageName);
5174            }
5175
5176            final BasePermission bp = mSettings.mPermissions.get(name);
5177            if (bp == null) {
5178                throw new IllegalArgumentException("Unknown permission: " + name);
5179            }
5180
5181            SettingBase sb = (SettingBase) pkg.mExtras;
5182            if (sb == null) {
5183                throw new IllegalArgumentException("Unknown package: " + packageName);
5184            }
5185
5186            PermissionsState permissionsState = sb.getPermissionsState();
5187
5188            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5189
5190            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5191                // Install and runtime permissions are stored in different places,
5192                // so figure out what permission changed and persist the change.
5193                if (permissionsState.getInstallPermissionState(name) != null) {
5194                    scheduleWriteSettingsLocked();
5195                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5196                        || hadState) {
5197                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5198                }
5199            }
5200        }
5201    }
5202
5203    /**
5204     * Update the permission flags for all packages and runtime permissions of a user in order
5205     * to allow device or profile owner to remove POLICY_FIXED.
5206     */
5207    @Override
5208    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5209        if (!sUserManager.exists(userId)) {
5210            return;
5211        }
5212
5213        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5214
5215        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5216                true /* requireFullPermission */, true /* checkShell */,
5217                "updatePermissionFlagsForAllApps");
5218
5219        // Only the system can change system fixed flags.
5220        if (getCallingUid() != Process.SYSTEM_UID) {
5221            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5222            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5223        }
5224
5225        synchronized (mPackages) {
5226            boolean changed = false;
5227            final int packageCount = mPackages.size();
5228            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5229                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5230                SettingBase sb = (SettingBase) pkg.mExtras;
5231                if (sb == null) {
5232                    continue;
5233                }
5234                PermissionsState permissionsState = sb.getPermissionsState();
5235                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5236                        userId, flagMask, flagValues);
5237            }
5238            if (changed) {
5239                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5240            }
5241        }
5242    }
5243
5244    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5245        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5246                != PackageManager.PERMISSION_GRANTED
5247            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5248                != PackageManager.PERMISSION_GRANTED) {
5249            throw new SecurityException(message + " requires "
5250                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5251                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5252        }
5253    }
5254
5255    @Override
5256    public boolean shouldShowRequestPermissionRationale(String permissionName,
5257            String packageName, int userId) {
5258        if (UserHandle.getCallingUserId() != userId) {
5259            mContext.enforceCallingPermission(
5260                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5261                    "canShowRequestPermissionRationale for user " + userId);
5262        }
5263
5264        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5265        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5266            return false;
5267        }
5268
5269        if (checkPermission(permissionName, packageName, userId)
5270                == PackageManager.PERMISSION_GRANTED) {
5271            return false;
5272        }
5273
5274        final int flags;
5275
5276        final long identity = Binder.clearCallingIdentity();
5277        try {
5278            flags = getPermissionFlags(permissionName,
5279                    packageName, userId);
5280        } finally {
5281            Binder.restoreCallingIdentity(identity);
5282        }
5283
5284        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5285                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5286                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5287
5288        if ((flags & fixedFlags) != 0) {
5289            return false;
5290        }
5291
5292        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5293    }
5294
5295    @Override
5296    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5297        mContext.enforceCallingOrSelfPermission(
5298                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5299                "addOnPermissionsChangeListener");
5300
5301        synchronized (mPackages) {
5302            mOnPermissionChangeListeners.addListenerLocked(listener);
5303        }
5304    }
5305
5306    @Override
5307    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5308        synchronized (mPackages) {
5309            mOnPermissionChangeListeners.removeListenerLocked(listener);
5310        }
5311    }
5312
5313    @Override
5314    public boolean isProtectedBroadcast(String actionName) {
5315        synchronized (mPackages) {
5316            if (mProtectedBroadcasts.contains(actionName)) {
5317                return true;
5318            } else if (actionName != null) {
5319                // TODO: remove these terrible hacks
5320                if (actionName.startsWith("android.net.netmon.lingerExpired")
5321                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5322                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5323                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5324                    return true;
5325                }
5326            }
5327        }
5328        return false;
5329    }
5330
5331    @Override
5332    public int checkSignatures(String pkg1, String pkg2) {
5333        synchronized (mPackages) {
5334            final PackageParser.Package p1 = mPackages.get(pkg1);
5335            final PackageParser.Package p2 = mPackages.get(pkg2);
5336            if (p1 == null || p1.mExtras == null
5337                    || p2 == null || p2.mExtras == null) {
5338                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5339            }
5340            return compareSignatures(p1.mSignatures, p2.mSignatures);
5341        }
5342    }
5343
5344    @Override
5345    public int checkUidSignatures(int uid1, int uid2) {
5346        // Map to base uids.
5347        uid1 = UserHandle.getAppId(uid1);
5348        uid2 = UserHandle.getAppId(uid2);
5349        // reader
5350        synchronized (mPackages) {
5351            Signature[] s1;
5352            Signature[] s2;
5353            Object obj = mSettings.getUserIdLPr(uid1);
5354            if (obj != null) {
5355                if (obj instanceof SharedUserSetting) {
5356                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5357                } else if (obj instanceof PackageSetting) {
5358                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5359                } else {
5360                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5361                }
5362            } else {
5363                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5364            }
5365            obj = mSettings.getUserIdLPr(uid2);
5366            if (obj != null) {
5367                if (obj instanceof SharedUserSetting) {
5368                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5369                } else if (obj instanceof PackageSetting) {
5370                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5371                } else {
5372                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5373                }
5374            } else {
5375                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5376            }
5377            return compareSignatures(s1, s2);
5378        }
5379    }
5380
5381    /**
5382     * This method should typically only be used when granting or revoking
5383     * permissions, since the app may immediately restart after this call.
5384     * <p>
5385     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5386     * guard your work against the app being relaunched.
5387     */
5388    private void killUid(int appId, int userId, String reason) {
5389        final long identity = Binder.clearCallingIdentity();
5390        try {
5391            IActivityManager am = ActivityManager.getService();
5392            if (am != null) {
5393                try {
5394                    am.killUid(appId, userId, reason);
5395                } catch (RemoteException e) {
5396                    /* ignore - same process */
5397                }
5398            }
5399        } finally {
5400            Binder.restoreCallingIdentity(identity);
5401        }
5402    }
5403
5404    /**
5405     * Compares two sets of signatures. Returns:
5406     * <br />
5407     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5408     * <br />
5409     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5410     * <br />
5411     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5412     * <br />
5413     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5414     * <br />
5415     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5416     */
5417    static int compareSignatures(Signature[] s1, Signature[] s2) {
5418        if (s1 == null) {
5419            return s2 == null
5420                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5421                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5422        }
5423
5424        if (s2 == null) {
5425            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5426        }
5427
5428        if (s1.length != s2.length) {
5429            return PackageManager.SIGNATURE_NO_MATCH;
5430        }
5431
5432        // Since both signature sets are of size 1, we can compare without HashSets.
5433        if (s1.length == 1) {
5434            return s1[0].equals(s2[0]) ?
5435                    PackageManager.SIGNATURE_MATCH :
5436                    PackageManager.SIGNATURE_NO_MATCH;
5437        }
5438
5439        ArraySet<Signature> set1 = new ArraySet<Signature>();
5440        for (Signature sig : s1) {
5441            set1.add(sig);
5442        }
5443        ArraySet<Signature> set2 = new ArraySet<Signature>();
5444        for (Signature sig : s2) {
5445            set2.add(sig);
5446        }
5447        // Make sure s2 contains all signatures in s1.
5448        if (set1.equals(set2)) {
5449            return PackageManager.SIGNATURE_MATCH;
5450        }
5451        return PackageManager.SIGNATURE_NO_MATCH;
5452    }
5453
5454    /**
5455     * If the database version for this type of package (internal storage or
5456     * external storage) is less than the version where package signatures
5457     * were updated, return true.
5458     */
5459    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5460        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5461        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5462    }
5463
5464    /**
5465     * Used for backward compatibility to make sure any packages with
5466     * certificate chains get upgraded to the new style. {@code existingSigs}
5467     * will be in the old format (since they were stored on disk from before the
5468     * system upgrade) and {@code scannedSigs} will be in the newer format.
5469     */
5470    private int compareSignaturesCompat(PackageSignatures existingSigs,
5471            PackageParser.Package scannedPkg) {
5472        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5473            return PackageManager.SIGNATURE_NO_MATCH;
5474        }
5475
5476        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5477        for (Signature sig : existingSigs.mSignatures) {
5478            existingSet.add(sig);
5479        }
5480        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5481        for (Signature sig : scannedPkg.mSignatures) {
5482            try {
5483                Signature[] chainSignatures = sig.getChainSignatures();
5484                for (Signature chainSig : chainSignatures) {
5485                    scannedCompatSet.add(chainSig);
5486                }
5487            } catch (CertificateEncodingException e) {
5488                scannedCompatSet.add(sig);
5489            }
5490        }
5491        /*
5492         * Make sure the expanded scanned set contains all signatures in the
5493         * existing one.
5494         */
5495        if (scannedCompatSet.equals(existingSet)) {
5496            // Migrate the old signatures to the new scheme.
5497            existingSigs.assignSignatures(scannedPkg.mSignatures);
5498            // The new KeySets will be re-added later in the scanning process.
5499            synchronized (mPackages) {
5500                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5501            }
5502            return PackageManager.SIGNATURE_MATCH;
5503        }
5504        return PackageManager.SIGNATURE_NO_MATCH;
5505    }
5506
5507    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5508        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5509        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5510    }
5511
5512    private int compareSignaturesRecover(PackageSignatures existingSigs,
5513            PackageParser.Package scannedPkg) {
5514        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5515            return PackageManager.SIGNATURE_NO_MATCH;
5516        }
5517
5518        String msg = null;
5519        try {
5520            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5521                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5522                        + scannedPkg.packageName);
5523                return PackageManager.SIGNATURE_MATCH;
5524            }
5525        } catch (CertificateException e) {
5526            msg = e.getMessage();
5527        }
5528
5529        logCriticalInfo(Log.INFO,
5530                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5531        return PackageManager.SIGNATURE_NO_MATCH;
5532    }
5533
5534    @Override
5535    public List<String> getAllPackages() {
5536        synchronized (mPackages) {
5537            return new ArrayList<String>(mPackages.keySet());
5538        }
5539    }
5540
5541    @Override
5542    public String[] getPackagesForUid(int uid) {
5543        final int userId = UserHandle.getUserId(uid);
5544        uid = UserHandle.getAppId(uid);
5545        // reader
5546        synchronized (mPackages) {
5547            Object obj = mSettings.getUserIdLPr(uid);
5548            if (obj instanceof SharedUserSetting) {
5549                final SharedUserSetting sus = (SharedUserSetting) obj;
5550                final int N = sus.packages.size();
5551                String[] res = new String[N];
5552                final Iterator<PackageSetting> it = sus.packages.iterator();
5553                int i = 0;
5554                while (it.hasNext()) {
5555                    PackageSetting ps = it.next();
5556                    if (ps.getInstalled(userId)) {
5557                        res[i++] = ps.name;
5558                    } else {
5559                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5560                    }
5561                }
5562                return res;
5563            } else if (obj instanceof PackageSetting) {
5564                final PackageSetting ps = (PackageSetting) obj;
5565                if (ps.getInstalled(userId)) {
5566                    return new String[]{ps.name};
5567                }
5568            }
5569        }
5570        return null;
5571    }
5572
5573    @Override
5574    public String getNameForUid(int uid) {
5575        // reader
5576        synchronized (mPackages) {
5577            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5578            if (obj instanceof SharedUserSetting) {
5579                final SharedUserSetting sus = (SharedUserSetting) obj;
5580                return sus.name + ":" + sus.userId;
5581            } else if (obj instanceof PackageSetting) {
5582                final PackageSetting ps = (PackageSetting) obj;
5583                return ps.name;
5584            }
5585        }
5586        return null;
5587    }
5588
5589    @Override
5590    public int getUidForSharedUser(String sharedUserName) {
5591        if(sharedUserName == null) {
5592            return -1;
5593        }
5594        // reader
5595        synchronized (mPackages) {
5596            SharedUserSetting suid;
5597            try {
5598                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5599                if (suid != null) {
5600                    return suid.userId;
5601                }
5602            } catch (PackageManagerException ignore) {
5603                // can't happen, but, still need to catch it
5604            }
5605            return -1;
5606        }
5607    }
5608
5609    @Override
5610    public int getFlagsForUid(int uid) {
5611        synchronized (mPackages) {
5612            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5613            if (obj instanceof SharedUserSetting) {
5614                final SharedUserSetting sus = (SharedUserSetting) obj;
5615                return sus.pkgFlags;
5616            } else if (obj instanceof PackageSetting) {
5617                final PackageSetting ps = (PackageSetting) obj;
5618                return ps.pkgFlags;
5619            }
5620        }
5621        return 0;
5622    }
5623
5624    @Override
5625    public int getPrivateFlagsForUid(int uid) {
5626        synchronized (mPackages) {
5627            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5628            if (obj instanceof SharedUserSetting) {
5629                final SharedUserSetting sus = (SharedUserSetting) obj;
5630                return sus.pkgPrivateFlags;
5631            } else if (obj instanceof PackageSetting) {
5632                final PackageSetting ps = (PackageSetting) obj;
5633                return ps.pkgPrivateFlags;
5634            }
5635        }
5636        return 0;
5637    }
5638
5639    @Override
5640    public boolean isUidPrivileged(int uid) {
5641        uid = UserHandle.getAppId(uid);
5642        // reader
5643        synchronized (mPackages) {
5644            Object obj = mSettings.getUserIdLPr(uid);
5645            if (obj instanceof SharedUserSetting) {
5646                final SharedUserSetting sus = (SharedUserSetting) obj;
5647                final Iterator<PackageSetting> it = sus.packages.iterator();
5648                while (it.hasNext()) {
5649                    if (it.next().isPrivileged()) {
5650                        return true;
5651                    }
5652                }
5653            } else if (obj instanceof PackageSetting) {
5654                final PackageSetting ps = (PackageSetting) obj;
5655                return ps.isPrivileged();
5656            }
5657        }
5658        return false;
5659    }
5660
5661    @Override
5662    public String[] getAppOpPermissionPackages(String permissionName) {
5663        synchronized (mPackages) {
5664            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5665            if (pkgs == null) {
5666                return null;
5667            }
5668            return pkgs.toArray(new String[pkgs.size()]);
5669        }
5670    }
5671
5672    @Override
5673    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5674            int flags, int userId) {
5675        return resolveIntentInternal(
5676                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5677    }
5678
5679    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5680            int flags, int userId, boolean includeInstantApp) {
5681        try {
5682            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5683
5684            if (!sUserManager.exists(userId)) return null;
5685            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5686            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5687                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5688
5689            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5690            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5691                    flags, userId, includeInstantApp);
5692            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5693
5694            final ResolveInfo bestChoice =
5695                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5696            return bestChoice;
5697        } finally {
5698            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5699        }
5700    }
5701
5702    @Override
5703    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5704        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5705            throw new SecurityException(
5706                    "findPersistentPreferredActivity can only be run by the system");
5707        }
5708        if (!sUserManager.exists(userId)) {
5709            return null;
5710        }
5711        intent = updateIntentForResolve(intent);
5712        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5713        final int flags = updateFlagsForResolve(0, userId, intent, false);
5714        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5715                userId);
5716        synchronized (mPackages) {
5717            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5718                    userId);
5719        }
5720    }
5721
5722    @Override
5723    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5724            IntentFilter filter, int match, ComponentName activity) {
5725        final int userId = UserHandle.getCallingUserId();
5726        if (DEBUG_PREFERRED) {
5727            Log.v(TAG, "setLastChosenActivity intent=" + intent
5728                + " resolvedType=" + resolvedType
5729                + " flags=" + flags
5730                + " filter=" + filter
5731                + " match=" + match
5732                + " activity=" + activity);
5733            filter.dump(new PrintStreamPrinter(System.out), "    ");
5734        }
5735        intent.setComponent(null);
5736        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5737                userId);
5738        // Find any earlier preferred or last chosen entries and nuke them
5739        findPreferredActivity(intent, resolvedType,
5740                flags, query, 0, false, true, false, userId);
5741        // Add the new activity as the last chosen for this filter
5742        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5743                "Setting last chosen");
5744    }
5745
5746    @Override
5747    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5748        final int userId = UserHandle.getCallingUserId();
5749        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5750        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5751                userId);
5752        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5753                false, false, false, userId);
5754    }
5755
5756    /**
5757     * Returns whether or not instant apps have been disabled remotely.
5758     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5759     * held. Otherwise we run the risk of deadlock.
5760     */
5761    private boolean isEphemeralDisabled() {
5762        // ephemeral apps have been disabled across the board
5763        if (DISABLE_EPHEMERAL_APPS) {
5764            return true;
5765        }
5766        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5767        if (!mSystemReady) {
5768            return true;
5769        }
5770        // we can't get a content resolver until the system is ready; these checks must happen last
5771        final ContentResolver resolver = mContext.getContentResolver();
5772        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5773            return true;
5774        }
5775        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5776    }
5777
5778    private boolean isEphemeralAllowed(
5779            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5780            boolean skipPackageCheck) {
5781        final int callingUser = UserHandle.getCallingUserId();
5782        if (callingUser != UserHandle.USER_SYSTEM) {
5783            return false;
5784        }
5785        if (mInstantAppResolverConnection == null) {
5786            return false;
5787        }
5788        if (mInstantAppInstallerComponent == null) {
5789            return false;
5790        }
5791        if (intent.getComponent() != null) {
5792            return false;
5793        }
5794        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5795            return false;
5796        }
5797        if (!skipPackageCheck && intent.getPackage() != null) {
5798            return false;
5799        }
5800        final boolean isWebUri = hasWebURI(intent);
5801        if (!isWebUri || intent.getData().getHost() == null) {
5802            return false;
5803        }
5804        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5805        // Or if there's already an ephemeral app installed that handles the action
5806        synchronized (mPackages) {
5807            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5808            for (int n = 0; n < count; n++) {
5809                ResolveInfo info = resolvedActivities.get(n);
5810                String packageName = info.activityInfo.packageName;
5811                PackageSetting ps = mSettings.mPackages.get(packageName);
5812                if (ps != null) {
5813                    // Try to get the status from User settings first
5814                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5815                    int status = (int) (packedStatus >> 32);
5816                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5817                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5818                        if (DEBUG_EPHEMERAL) {
5819                            Slog.v(TAG, "DENY ephemeral apps;"
5820                                + " pkg: " + packageName + ", status: " + status);
5821                        }
5822                        return false;
5823                    }
5824                    if (ps.getInstantApp(userId)) {
5825                        return false;
5826                    }
5827                }
5828            }
5829        }
5830        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5831        return true;
5832    }
5833
5834    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5835            Intent origIntent, String resolvedType, String callingPackage,
5836            int userId) {
5837        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5838                new InstantAppRequest(responseObj, origIntent, resolvedType,
5839                        callingPackage, userId));
5840        mHandler.sendMessage(msg);
5841    }
5842
5843    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5844            int flags, List<ResolveInfo> query, int userId) {
5845        if (query != null) {
5846            final int N = query.size();
5847            if (N == 1) {
5848                return query.get(0);
5849            } else if (N > 1) {
5850                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5851                // If there is more than one activity with the same priority,
5852                // then let the user decide between them.
5853                ResolveInfo r0 = query.get(0);
5854                ResolveInfo r1 = query.get(1);
5855                if (DEBUG_INTENT_MATCHING || debug) {
5856                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5857                            + r1.activityInfo.name + "=" + r1.priority);
5858                }
5859                // If the first activity has a higher priority, or a different
5860                // default, then it is always desirable to pick it.
5861                if (r0.priority != r1.priority
5862                        || r0.preferredOrder != r1.preferredOrder
5863                        || r0.isDefault != r1.isDefault) {
5864                    return query.get(0);
5865                }
5866                // If we have saved a preference for a preferred activity for
5867                // this Intent, use that.
5868                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5869                        flags, query, r0.priority, true, false, debug, userId);
5870                if (ri != null) {
5871                    return ri;
5872                }
5873                // If we have an ephemeral app, use it
5874                for (int i = 0; i < N; i++) {
5875                    ri = query.get(i);
5876                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5877                        return ri;
5878                    }
5879                }
5880                ri = new ResolveInfo(mResolveInfo);
5881                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5882                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5883                // If all of the options come from the same package, show the application's
5884                // label and icon instead of the generic resolver's.
5885                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5886                // and then throw away the ResolveInfo itself, meaning that the caller loses
5887                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5888                // a fallback for this case; we only set the target package's resources on
5889                // the ResolveInfo, not the ActivityInfo.
5890                final String intentPackage = intent.getPackage();
5891                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5892                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5893                    ri.resolvePackageName = intentPackage;
5894                    if (userNeedsBadging(userId)) {
5895                        ri.noResourceId = true;
5896                    } else {
5897                        ri.icon = appi.icon;
5898                    }
5899                    ri.iconResourceId = appi.icon;
5900                    ri.labelRes = appi.labelRes;
5901                }
5902                ri.activityInfo.applicationInfo = new ApplicationInfo(
5903                        ri.activityInfo.applicationInfo);
5904                if (userId != 0) {
5905                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5906                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5907                }
5908                // Make sure that the resolver is displayable in car mode
5909                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5910                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5911                return ri;
5912            }
5913        }
5914        return null;
5915    }
5916
5917    /**
5918     * Return true if the given list is not empty and all of its contents have
5919     * an activityInfo with the given package name.
5920     */
5921    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5922        if (ArrayUtils.isEmpty(list)) {
5923            return false;
5924        }
5925        for (int i = 0, N = list.size(); i < N; i++) {
5926            final ResolveInfo ri = list.get(i);
5927            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5928            if (ai == null || !packageName.equals(ai.packageName)) {
5929                return false;
5930            }
5931        }
5932        return true;
5933    }
5934
5935    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5936            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5937        final int N = query.size();
5938        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5939                .get(userId);
5940        // Get the list of persistent preferred activities that handle the intent
5941        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5942        List<PersistentPreferredActivity> pprefs = ppir != null
5943                ? ppir.queryIntent(intent, resolvedType,
5944                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5945                        userId)
5946                : null;
5947        if (pprefs != null && pprefs.size() > 0) {
5948            final int M = pprefs.size();
5949            for (int i=0; i<M; i++) {
5950                final PersistentPreferredActivity ppa = pprefs.get(i);
5951                if (DEBUG_PREFERRED || debug) {
5952                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5953                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5954                            + "\n  component=" + ppa.mComponent);
5955                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5956                }
5957                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5958                        flags | MATCH_DISABLED_COMPONENTS, userId);
5959                if (DEBUG_PREFERRED || debug) {
5960                    Slog.v(TAG, "Found persistent preferred activity:");
5961                    if (ai != null) {
5962                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5963                    } else {
5964                        Slog.v(TAG, "  null");
5965                    }
5966                }
5967                if (ai == null) {
5968                    // This previously registered persistent preferred activity
5969                    // component is no longer known. Ignore it and do NOT remove it.
5970                    continue;
5971                }
5972                for (int j=0; j<N; j++) {
5973                    final ResolveInfo ri = query.get(j);
5974                    if (!ri.activityInfo.applicationInfo.packageName
5975                            .equals(ai.applicationInfo.packageName)) {
5976                        continue;
5977                    }
5978                    if (!ri.activityInfo.name.equals(ai.name)) {
5979                        continue;
5980                    }
5981                    //  Found a persistent preference that can handle the intent.
5982                    if (DEBUG_PREFERRED || debug) {
5983                        Slog.v(TAG, "Returning persistent preferred activity: " +
5984                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5985                    }
5986                    return ri;
5987                }
5988            }
5989        }
5990        return null;
5991    }
5992
5993    // TODO: handle preferred activities missing while user has amnesia
5994    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5995            List<ResolveInfo> query, int priority, boolean always,
5996            boolean removeMatches, boolean debug, int userId) {
5997        if (!sUserManager.exists(userId)) return null;
5998        flags = updateFlagsForResolve(flags, userId, intent, false);
5999        intent = updateIntentForResolve(intent);
6000        // writer
6001        synchronized (mPackages) {
6002            // Try to find a matching persistent preferred activity.
6003            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6004                    debug, userId);
6005
6006            // If a persistent preferred activity matched, use it.
6007            if (pri != null) {
6008                return pri;
6009            }
6010
6011            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6012            // Get the list of preferred activities that handle the intent
6013            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6014            List<PreferredActivity> prefs = pir != null
6015                    ? pir.queryIntent(intent, resolvedType,
6016                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6017                            userId)
6018                    : null;
6019            if (prefs != null && prefs.size() > 0) {
6020                boolean changed = false;
6021                try {
6022                    // First figure out how good the original match set is.
6023                    // We will only allow preferred activities that came
6024                    // from the same match quality.
6025                    int match = 0;
6026
6027                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6028
6029                    final int N = query.size();
6030                    for (int j=0; j<N; j++) {
6031                        final ResolveInfo ri = query.get(j);
6032                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6033                                + ": 0x" + Integer.toHexString(match));
6034                        if (ri.match > match) {
6035                            match = ri.match;
6036                        }
6037                    }
6038
6039                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6040                            + Integer.toHexString(match));
6041
6042                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6043                    final int M = prefs.size();
6044                    for (int i=0; i<M; i++) {
6045                        final PreferredActivity pa = prefs.get(i);
6046                        if (DEBUG_PREFERRED || debug) {
6047                            Slog.v(TAG, "Checking PreferredActivity ds="
6048                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6049                                    + "\n  component=" + pa.mPref.mComponent);
6050                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6051                        }
6052                        if (pa.mPref.mMatch != match) {
6053                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6054                                    + Integer.toHexString(pa.mPref.mMatch));
6055                            continue;
6056                        }
6057                        // If it's not an "always" type preferred activity and that's what we're
6058                        // looking for, skip it.
6059                        if (always && !pa.mPref.mAlways) {
6060                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6061                            continue;
6062                        }
6063                        final ActivityInfo ai = getActivityInfo(
6064                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6065                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6066                                userId);
6067                        if (DEBUG_PREFERRED || debug) {
6068                            Slog.v(TAG, "Found preferred activity:");
6069                            if (ai != null) {
6070                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6071                            } else {
6072                                Slog.v(TAG, "  null");
6073                            }
6074                        }
6075                        if (ai == null) {
6076                            // This previously registered preferred activity
6077                            // component is no longer known.  Most likely an update
6078                            // to the app was installed and in the new version this
6079                            // component no longer exists.  Clean it up by removing
6080                            // it from the preferred activities list, and skip it.
6081                            Slog.w(TAG, "Removing dangling preferred activity: "
6082                                    + pa.mPref.mComponent);
6083                            pir.removeFilter(pa);
6084                            changed = true;
6085                            continue;
6086                        }
6087                        for (int j=0; j<N; j++) {
6088                            final ResolveInfo ri = query.get(j);
6089                            if (!ri.activityInfo.applicationInfo.packageName
6090                                    .equals(ai.applicationInfo.packageName)) {
6091                                continue;
6092                            }
6093                            if (!ri.activityInfo.name.equals(ai.name)) {
6094                                continue;
6095                            }
6096
6097                            if (removeMatches) {
6098                                pir.removeFilter(pa);
6099                                changed = true;
6100                                if (DEBUG_PREFERRED) {
6101                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6102                                }
6103                                break;
6104                            }
6105
6106                            // Okay we found a previously set preferred or last chosen app.
6107                            // If the result set is different from when this
6108                            // was created, we need to clear it and re-ask the
6109                            // user their preference, if we're looking for an "always" type entry.
6110                            if (always && !pa.mPref.sameSet(query)) {
6111                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6112                                        + intent + " type " + resolvedType);
6113                                if (DEBUG_PREFERRED) {
6114                                    Slog.v(TAG, "Removing preferred activity since set changed "
6115                                            + pa.mPref.mComponent);
6116                                }
6117                                pir.removeFilter(pa);
6118                                // Re-add the filter as a "last chosen" entry (!always)
6119                                PreferredActivity lastChosen = new PreferredActivity(
6120                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6121                                pir.addFilter(lastChosen);
6122                                changed = true;
6123                                return null;
6124                            }
6125
6126                            // Yay! Either the set matched or we're looking for the last chosen
6127                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6128                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6129                            return ri;
6130                        }
6131                    }
6132                } finally {
6133                    if (changed) {
6134                        if (DEBUG_PREFERRED) {
6135                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6136                        }
6137                        scheduleWritePackageRestrictionsLocked(userId);
6138                    }
6139                }
6140            }
6141        }
6142        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6143        return null;
6144    }
6145
6146    /*
6147     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6148     */
6149    @Override
6150    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6151            int targetUserId) {
6152        mContext.enforceCallingOrSelfPermission(
6153                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6154        List<CrossProfileIntentFilter> matches =
6155                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6156        if (matches != null) {
6157            int size = matches.size();
6158            for (int i = 0; i < size; i++) {
6159                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6160            }
6161        }
6162        if (hasWebURI(intent)) {
6163            // cross-profile app linking works only towards the parent.
6164            final UserInfo parent = getProfileParent(sourceUserId);
6165            synchronized(mPackages) {
6166                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6167                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6168                        intent, resolvedType, flags, sourceUserId, parent.id);
6169                return xpDomainInfo != null;
6170            }
6171        }
6172        return false;
6173    }
6174
6175    private UserInfo getProfileParent(int userId) {
6176        final long identity = Binder.clearCallingIdentity();
6177        try {
6178            return sUserManager.getProfileParent(userId);
6179        } finally {
6180            Binder.restoreCallingIdentity(identity);
6181        }
6182    }
6183
6184    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6185            String resolvedType, int userId) {
6186        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6187        if (resolver != null) {
6188            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6189        }
6190        return null;
6191    }
6192
6193    @Override
6194    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6195            String resolvedType, int flags, int userId) {
6196        try {
6197            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6198
6199            return new ParceledListSlice<>(
6200                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6201        } finally {
6202            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6203        }
6204    }
6205
6206    /**
6207     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6208     * instant, returns {@code null}.
6209     */
6210    private String getInstantAppPackageName(int callingUid) {
6211        final int appId = UserHandle.getAppId(callingUid);
6212        synchronized (mPackages) {
6213            final Object obj = mSettings.getUserIdLPr(appId);
6214            if (obj instanceof PackageSetting) {
6215                final PackageSetting ps = (PackageSetting) obj;
6216                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6217                return isInstantApp ? ps.pkg.packageName : null;
6218            }
6219        }
6220        return null;
6221    }
6222
6223    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6224            String resolvedType, int flags, int userId) {
6225        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6226    }
6227
6228    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6229            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6230        if (!sUserManager.exists(userId)) return Collections.emptyList();
6231        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6232        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6233        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6234                false /* requireFullPermission */, false /* checkShell */,
6235                "query intent activities");
6236        ComponentName comp = intent.getComponent();
6237        if (comp == null) {
6238            if (intent.getSelector() != null) {
6239                intent = intent.getSelector();
6240                comp = intent.getComponent();
6241            }
6242        }
6243
6244        if (comp != null) {
6245            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6246            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6247            if (ai != null) {
6248                // When specifying an explicit component, we prevent the activity from being
6249                // used when either 1) the calling package is normal and the activity is within
6250                // an ephemeral application or 2) the calling package is ephemeral and the
6251                // activity is not visible to ephemeral applications.
6252                final boolean matchInstantApp =
6253                        (flags & PackageManager.MATCH_INSTANT) != 0;
6254                final boolean matchVisibleToInstantAppOnly =
6255                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6256                final boolean isCallerInstantApp =
6257                        instantAppPkgName != null;
6258                final boolean isTargetSameInstantApp =
6259                        comp.getPackageName().equals(instantAppPkgName);
6260                final boolean isTargetInstantApp =
6261                        (ai.applicationInfo.privateFlags
6262                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6263                final boolean isTargetHiddenFromInstantApp =
6264                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6265                final boolean blockResolution =
6266                        !isTargetSameInstantApp
6267                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6268                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6269                                        && isTargetHiddenFromInstantApp));
6270                if (!blockResolution) {
6271                    final ResolveInfo ri = new ResolveInfo();
6272                    ri.activityInfo = ai;
6273                    list.add(ri);
6274                }
6275            }
6276            return applyPostResolutionFilter(list, instantAppPkgName);
6277        }
6278
6279        // reader
6280        boolean sortResult = false;
6281        boolean addEphemeral = false;
6282        List<ResolveInfo> result;
6283        final String pkgName = intent.getPackage();
6284        final boolean ephemeralDisabled = isEphemeralDisabled();
6285        synchronized (mPackages) {
6286            if (pkgName == null) {
6287                List<CrossProfileIntentFilter> matchingFilters =
6288                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6289                // Check for results that need to skip the current profile.
6290                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6291                        resolvedType, flags, userId);
6292                if (xpResolveInfo != null) {
6293                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6294                    xpResult.add(xpResolveInfo);
6295                    return applyPostResolutionFilter(
6296                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6297                }
6298
6299                // Check for results in the current profile.
6300                result = filterIfNotSystemUser(mActivities.queryIntent(
6301                        intent, resolvedType, flags, userId), userId);
6302                addEphemeral = !ephemeralDisabled
6303                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6304
6305                // Check for cross profile results.
6306                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6307                xpResolveInfo = queryCrossProfileIntents(
6308                        matchingFilters, intent, resolvedType, flags, userId,
6309                        hasNonNegativePriorityResult);
6310                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6311                    boolean isVisibleToUser = filterIfNotSystemUser(
6312                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6313                    if (isVisibleToUser) {
6314                        result.add(xpResolveInfo);
6315                        sortResult = true;
6316                    }
6317                }
6318                if (hasWebURI(intent)) {
6319                    CrossProfileDomainInfo xpDomainInfo = null;
6320                    final UserInfo parent = getProfileParent(userId);
6321                    if (parent != null) {
6322                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6323                                flags, userId, parent.id);
6324                    }
6325                    if (xpDomainInfo != null) {
6326                        if (xpResolveInfo != null) {
6327                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6328                            // in the result.
6329                            result.remove(xpResolveInfo);
6330                        }
6331                        if (result.size() == 0 && !addEphemeral) {
6332                            // No result in current profile, but found candidate in parent user.
6333                            // And we are not going to add emphemeral app, so we can return the
6334                            // result straight away.
6335                            result.add(xpDomainInfo.resolveInfo);
6336                            return applyPostResolutionFilter(result, instantAppPkgName);
6337                        }
6338                    } else if (result.size() <= 1 && !addEphemeral) {
6339                        // No result in parent user and <= 1 result in current profile, and we
6340                        // are not going to add emphemeral app, so we can return the result without
6341                        // further processing.
6342                        return applyPostResolutionFilter(result, instantAppPkgName);
6343                    }
6344                    // We have more than one candidate (combining results from current and parent
6345                    // profile), so we need filtering and sorting.
6346                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6347                            intent, flags, result, xpDomainInfo, userId);
6348                    sortResult = true;
6349                }
6350            } else {
6351                final PackageParser.Package pkg = mPackages.get(pkgName);
6352                if (pkg != null) {
6353                    return applyPostResolutionFilter(filterIfNotSystemUser(
6354                            mActivities.queryIntentForPackage(
6355                                    intent, resolvedType, flags, pkg.activities, userId),
6356                            userId), instantAppPkgName);
6357                } else {
6358                    // the caller wants to resolve for a particular package; however, there
6359                    // were no installed results, so, try to find an ephemeral result
6360                    addEphemeral =  !ephemeralDisabled
6361                            && isEphemeralAllowed(
6362                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6363                    result = new ArrayList<ResolveInfo>();
6364                }
6365            }
6366        }
6367        if (addEphemeral) {
6368            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6369            final InstantAppRequest requestObject = new InstantAppRequest(
6370                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6371                    null /*callingPackage*/, userId);
6372            final AuxiliaryResolveInfo auxiliaryResponse =
6373                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6374                            mContext, mInstantAppResolverConnection, requestObject);
6375            if (auxiliaryResponse != null) {
6376                if (DEBUG_EPHEMERAL) {
6377                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6378                }
6379                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6380                ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity);
6381                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6382                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6383                // make sure this resolver is the default
6384                ephemeralInstaller.isDefault = true;
6385                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6386                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6387                // add a non-generic filter
6388                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6389                ephemeralInstaller.filter.addDataPath(
6390                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6391                ephemeralInstaller.instantAppAvailable = true;
6392                result.add(ephemeralInstaller);
6393            }
6394            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6395        }
6396        if (sortResult) {
6397            Collections.sort(result, mResolvePrioritySorter);
6398        }
6399        return applyPostResolutionFilter(result, instantAppPkgName);
6400    }
6401
6402    private static class CrossProfileDomainInfo {
6403        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6404        ResolveInfo resolveInfo;
6405        /* Best domain verification status of the activities found in the other profile */
6406        int bestDomainVerificationStatus;
6407    }
6408
6409    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6410            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6411        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6412                sourceUserId)) {
6413            return null;
6414        }
6415        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6416                resolvedType, flags, parentUserId);
6417
6418        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6419            return null;
6420        }
6421        CrossProfileDomainInfo result = null;
6422        int size = resultTargetUser.size();
6423        for (int i = 0; i < size; i++) {
6424            ResolveInfo riTargetUser = resultTargetUser.get(i);
6425            // Intent filter verification is only for filters that specify a host. So don't return
6426            // those that handle all web uris.
6427            if (riTargetUser.handleAllWebDataURI) {
6428                continue;
6429            }
6430            String packageName = riTargetUser.activityInfo.packageName;
6431            PackageSetting ps = mSettings.mPackages.get(packageName);
6432            if (ps == null) {
6433                continue;
6434            }
6435            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6436            int status = (int)(verificationState >> 32);
6437            if (result == null) {
6438                result = new CrossProfileDomainInfo();
6439                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6440                        sourceUserId, parentUserId);
6441                result.bestDomainVerificationStatus = status;
6442            } else {
6443                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6444                        result.bestDomainVerificationStatus);
6445            }
6446        }
6447        // Don't consider matches with status NEVER across profiles.
6448        if (result != null && result.bestDomainVerificationStatus
6449                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6450            return null;
6451        }
6452        return result;
6453    }
6454
6455    /**
6456     * Verification statuses are ordered from the worse to the best, except for
6457     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6458     */
6459    private int bestDomainVerificationStatus(int status1, int status2) {
6460        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6461            return status2;
6462        }
6463        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6464            return status1;
6465        }
6466        return (int) MathUtils.max(status1, status2);
6467    }
6468
6469    private boolean isUserEnabled(int userId) {
6470        long callingId = Binder.clearCallingIdentity();
6471        try {
6472            UserInfo userInfo = sUserManager.getUserInfo(userId);
6473            return userInfo != null && userInfo.isEnabled();
6474        } finally {
6475            Binder.restoreCallingIdentity(callingId);
6476        }
6477    }
6478
6479    /**
6480     * Filter out activities with systemUserOnly flag set, when current user is not System.
6481     *
6482     * @return filtered list
6483     */
6484    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6485        if (userId == UserHandle.USER_SYSTEM) {
6486            return resolveInfos;
6487        }
6488        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6489            ResolveInfo info = resolveInfos.get(i);
6490            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6491                resolveInfos.remove(i);
6492            }
6493        }
6494        return resolveInfos;
6495    }
6496
6497    /**
6498     * Filters out ephemeral activities.
6499     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6500     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6501     *
6502     * @param resolveInfos The pre-filtered list of resolved activities
6503     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6504     *          is performed.
6505     * @return A filtered list of resolved activities.
6506     */
6507    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6508            String ephemeralPkgName) {
6509        // TODO: When adding on-demand split support for non-instant apps, remove this check
6510        // and always apply post filtering
6511        if (ephemeralPkgName == null) {
6512            return resolveInfos;
6513        }
6514        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6515            final ResolveInfo info = resolveInfos.get(i);
6516            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6517            // allow activities that are defined in the provided package
6518            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6519                if (info.activityInfo.splitName != null
6520                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6521                                info.activityInfo.splitName)) {
6522                    // requested activity is defined in a split that hasn't been installed yet.
6523                    // add the installer to the resolve list
6524                    if (DEBUG_EPHEMERAL) {
6525                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6526                    }
6527                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6528                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6529                            info.activityInfo.packageName, info.activityInfo.splitName,
6530                            info.activityInfo.applicationInfo.versionCode);
6531                    // make sure this resolver is the default
6532                    installerInfo.isDefault = true;
6533                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6534                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6535                    // add a non-generic filter
6536                    installerInfo.filter = new IntentFilter();
6537                    // load resources from the correct package
6538                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6539                    resolveInfos.set(i, installerInfo);
6540                }
6541                continue;
6542            }
6543            // allow activities that have been explicitly exposed to ephemeral apps
6544            if (!isEphemeralApp
6545                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6546                continue;
6547            }
6548            resolveInfos.remove(i);
6549        }
6550        return resolveInfos;
6551    }
6552
6553    /**
6554     * @param resolveInfos list of resolve infos in descending priority order
6555     * @return if the list contains a resolve info with non-negative priority
6556     */
6557    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6558        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6559    }
6560
6561    private static boolean hasWebURI(Intent intent) {
6562        if (intent.getData() == null) {
6563            return false;
6564        }
6565        final String scheme = intent.getScheme();
6566        if (TextUtils.isEmpty(scheme)) {
6567            return false;
6568        }
6569        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6570    }
6571
6572    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6573            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6574            int userId) {
6575        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6576
6577        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6578            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6579                    candidates.size());
6580        }
6581
6582        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6583        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6584        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6585        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6586        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6587        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6588
6589        synchronized (mPackages) {
6590            final int count = candidates.size();
6591            // First, try to use linked apps. Partition the candidates into four lists:
6592            // one for the final results, one for the "do not use ever", one for "undefined status"
6593            // and finally one for "browser app type".
6594            for (int n=0; n<count; n++) {
6595                ResolveInfo info = candidates.get(n);
6596                String packageName = info.activityInfo.packageName;
6597                PackageSetting ps = mSettings.mPackages.get(packageName);
6598                if (ps != null) {
6599                    // Add to the special match all list (Browser use case)
6600                    if (info.handleAllWebDataURI) {
6601                        matchAllList.add(info);
6602                        continue;
6603                    }
6604                    // Try to get the status from User settings first
6605                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6606                    int status = (int)(packedStatus >> 32);
6607                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6608                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6609                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6610                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6611                                    + " : linkgen=" + linkGeneration);
6612                        }
6613                        // Use link-enabled generation as preferredOrder, i.e.
6614                        // prefer newly-enabled over earlier-enabled.
6615                        info.preferredOrder = linkGeneration;
6616                        alwaysList.add(info);
6617                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6618                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6619                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6620                        }
6621                        neverList.add(info);
6622                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6623                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6624                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6625                        }
6626                        alwaysAskList.add(info);
6627                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6628                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6629                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6630                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6631                        }
6632                        undefinedList.add(info);
6633                    }
6634                }
6635            }
6636
6637            // We'll want to include browser possibilities in a few cases
6638            boolean includeBrowser = false;
6639
6640            // First try to add the "always" resolution(s) for the current user, if any
6641            if (alwaysList.size() > 0) {
6642                result.addAll(alwaysList);
6643            } else {
6644                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6645                result.addAll(undefinedList);
6646                // Maybe add one for the other profile.
6647                if (xpDomainInfo != null && (
6648                        xpDomainInfo.bestDomainVerificationStatus
6649                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6650                    result.add(xpDomainInfo.resolveInfo);
6651                }
6652                includeBrowser = true;
6653            }
6654
6655            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6656            // If there were 'always' entries their preferred order has been set, so we also
6657            // back that off to make the alternatives equivalent
6658            if (alwaysAskList.size() > 0) {
6659                for (ResolveInfo i : result) {
6660                    i.preferredOrder = 0;
6661                }
6662                result.addAll(alwaysAskList);
6663                includeBrowser = true;
6664            }
6665
6666            if (includeBrowser) {
6667                // Also add browsers (all of them or only the default one)
6668                if (DEBUG_DOMAIN_VERIFICATION) {
6669                    Slog.v(TAG, "   ...including browsers in candidate set");
6670                }
6671                if ((matchFlags & MATCH_ALL) != 0) {
6672                    result.addAll(matchAllList);
6673                } else {
6674                    // Browser/generic handling case.  If there's a default browser, go straight
6675                    // to that (but only if there is no other higher-priority match).
6676                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6677                    int maxMatchPrio = 0;
6678                    ResolveInfo defaultBrowserMatch = null;
6679                    final int numCandidates = matchAllList.size();
6680                    for (int n = 0; n < numCandidates; n++) {
6681                        ResolveInfo info = matchAllList.get(n);
6682                        // track the highest overall match priority...
6683                        if (info.priority > maxMatchPrio) {
6684                            maxMatchPrio = info.priority;
6685                        }
6686                        // ...and the highest-priority default browser match
6687                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6688                            if (defaultBrowserMatch == null
6689                                    || (defaultBrowserMatch.priority < info.priority)) {
6690                                if (debug) {
6691                                    Slog.v(TAG, "Considering default browser match " + info);
6692                                }
6693                                defaultBrowserMatch = info;
6694                            }
6695                        }
6696                    }
6697                    if (defaultBrowserMatch != null
6698                            && defaultBrowserMatch.priority >= maxMatchPrio
6699                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6700                    {
6701                        if (debug) {
6702                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6703                        }
6704                        result.add(defaultBrowserMatch);
6705                    } else {
6706                        result.addAll(matchAllList);
6707                    }
6708                }
6709
6710                // If there is nothing selected, add all candidates and remove the ones that the user
6711                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6712                if (result.size() == 0) {
6713                    result.addAll(candidates);
6714                    result.removeAll(neverList);
6715                }
6716            }
6717        }
6718        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6719            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6720                    result.size());
6721            for (ResolveInfo info : result) {
6722                Slog.v(TAG, "  + " + info.activityInfo);
6723            }
6724        }
6725        return result;
6726    }
6727
6728    // Returns a packed value as a long:
6729    //
6730    // high 'int'-sized word: link status: undefined/ask/never/always.
6731    // low 'int'-sized word: relative priority among 'always' results.
6732    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6733        long result = ps.getDomainVerificationStatusForUser(userId);
6734        // if none available, get the master status
6735        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6736            if (ps.getIntentFilterVerificationInfo() != null) {
6737                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6738            }
6739        }
6740        return result;
6741    }
6742
6743    private ResolveInfo querySkipCurrentProfileIntents(
6744            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6745            int flags, int sourceUserId) {
6746        if (matchingFilters != null) {
6747            int size = matchingFilters.size();
6748            for (int i = 0; i < size; i ++) {
6749                CrossProfileIntentFilter filter = matchingFilters.get(i);
6750                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6751                    // Checking if there are activities in the target user that can handle the
6752                    // intent.
6753                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6754                            resolvedType, flags, sourceUserId);
6755                    if (resolveInfo != null) {
6756                        return resolveInfo;
6757                    }
6758                }
6759            }
6760        }
6761        return null;
6762    }
6763
6764    // Return matching ResolveInfo in target user if any.
6765    private ResolveInfo queryCrossProfileIntents(
6766            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6767            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6768        if (matchingFilters != null) {
6769            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6770            // match the same intent. For performance reasons, it is better not to
6771            // run queryIntent twice for the same userId
6772            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6773            int size = matchingFilters.size();
6774            for (int i = 0; i < size; i++) {
6775                CrossProfileIntentFilter filter = matchingFilters.get(i);
6776                int targetUserId = filter.getTargetUserId();
6777                boolean skipCurrentProfile =
6778                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6779                boolean skipCurrentProfileIfNoMatchFound =
6780                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6781                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6782                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6783                    // Checking if there are activities in the target user that can handle the
6784                    // intent.
6785                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6786                            resolvedType, flags, sourceUserId);
6787                    if (resolveInfo != null) return resolveInfo;
6788                    alreadyTriedUserIds.put(targetUserId, true);
6789                }
6790            }
6791        }
6792        return null;
6793    }
6794
6795    /**
6796     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6797     * will forward the intent to the filter's target user.
6798     * Otherwise, returns null.
6799     */
6800    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6801            String resolvedType, int flags, int sourceUserId) {
6802        int targetUserId = filter.getTargetUserId();
6803        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6804                resolvedType, flags, targetUserId);
6805        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6806            // If all the matches in the target profile are suspended, return null.
6807            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6808                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6809                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6810                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6811                            targetUserId);
6812                }
6813            }
6814        }
6815        return null;
6816    }
6817
6818    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6819            int sourceUserId, int targetUserId) {
6820        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6821        long ident = Binder.clearCallingIdentity();
6822        boolean targetIsProfile;
6823        try {
6824            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6825        } finally {
6826            Binder.restoreCallingIdentity(ident);
6827        }
6828        String className;
6829        if (targetIsProfile) {
6830            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6831        } else {
6832            className = FORWARD_INTENT_TO_PARENT;
6833        }
6834        ComponentName forwardingActivityComponentName = new ComponentName(
6835                mAndroidApplication.packageName, className);
6836        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6837                sourceUserId);
6838        if (!targetIsProfile) {
6839            forwardingActivityInfo.showUserIcon = targetUserId;
6840            forwardingResolveInfo.noResourceId = true;
6841        }
6842        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6843        forwardingResolveInfo.priority = 0;
6844        forwardingResolveInfo.preferredOrder = 0;
6845        forwardingResolveInfo.match = 0;
6846        forwardingResolveInfo.isDefault = true;
6847        forwardingResolveInfo.filter = filter;
6848        forwardingResolveInfo.targetUserId = targetUserId;
6849        return forwardingResolveInfo;
6850    }
6851
6852    @Override
6853    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6854            Intent[] specifics, String[] specificTypes, Intent intent,
6855            String resolvedType, int flags, int userId) {
6856        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6857                specificTypes, intent, resolvedType, flags, userId));
6858    }
6859
6860    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6861            Intent[] specifics, String[] specificTypes, Intent intent,
6862            String resolvedType, int flags, int userId) {
6863        if (!sUserManager.exists(userId)) return Collections.emptyList();
6864        flags = updateFlagsForResolve(flags, userId, intent, false);
6865        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6866                false /* requireFullPermission */, false /* checkShell */,
6867                "query intent activity options");
6868        final String resultsAction = intent.getAction();
6869
6870        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6871                | PackageManager.GET_RESOLVED_FILTER, userId);
6872
6873        if (DEBUG_INTENT_MATCHING) {
6874            Log.v(TAG, "Query " + intent + ": " + results);
6875        }
6876
6877        int specificsPos = 0;
6878        int N;
6879
6880        // todo: note that the algorithm used here is O(N^2).  This
6881        // isn't a problem in our current environment, but if we start running
6882        // into situations where we have more than 5 or 10 matches then this
6883        // should probably be changed to something smarter...
6884
6885        // First we go through and resolve each of the specific items
6886        // that were supplied, taking care of removing any corresponding
6887        // duplicate items in the generic resolve list.
6888        if (specifics != null) {
6889            for (int i=0; i<specifics.length; i++) {
6890                final Intent sintent = specifics[i];
6891                if (sintent == null) {
6892                    continue;
6893                }
6894
6895                if (DEBUG_INTENT_MATCHING) {
6896                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6897                }
6898
6899                String action = sintent.getAction();
6900                if (resultsAction != null && resultsAction.equals(action)) {
6901                    // If this action was explicitly requested, then don't
6902                    // remove things that have it.
6903                    action = null;
6904                }
6905
6906                ResolveInfo ri = null;
6907                ActivityInfo ai = null;
6908
6909                ComponentName comp = sintent.getComponent();
6910                if (comp == null) {
6911                    ri = resolveIntent(
6912                        sintent,
6913                        specificTypes != null ? specificTypes[i] : null,
6914                            flags, userId);
6915                    if (ri == null) {
6916                        continue;
6917                    }
6918                    if (ri == mResolveInfo) {
6919                        // ACK!  Must do something better with this.
6920                    }
6921                    ai = ri.activityInfo;
6922                    comp = new ComponentName(ai.applicationInfo.packageName,
6923                            ai.name);
6924                } else {
6925                    ai = getActivityInfo(comp, flags, userId);
6926                    if (ai == null) {
6927                        continue;
6928                    }
6929                }
6930
6931                // Look for any generic query activities that are duplicates
6932                // of this specific one, and remove them from the results.
6933                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6934                N = results.size();
6935                int j;
6936                for (j=specificsPos; j<N; j++) {
6937                    ResolveInfo sri = results.get(j);
6938                    if ((sri.activityInfo.name.equals(comp.getClassName())
6939                            && sri.activityInfo.applicationInfo.packageName.equals(
6940                                    comp.getPackageName()))
6941                        || (action != null && sri.filter.matchAction(action))) {
6942                        results.remove(j);
6943                        if (DEBUG_INTENT_MATCHING) Log.v(
6944                            TAG, "Removing duplicate item from " + j
6945                            + " due to specific " + specificsPos);
6946                        if (ri == null) {
6947                            ri = sri;
6948                        }
6949                        j--;
6950                        N--;
6951                    }
6952                }
6953
6954                // Add this specific item to its proper place.
6955                if (ri == null) {
6956                    ri = new ResolveInfo();
6957                    ri.activityInfo = ai;
6958                }
6959                results.add(specificsPos, ri);
6960                ri.specificIndex = i;
6961                specificsPos++;
6962            }
6963        }
6964
6965        // Now we go through the remaining generic results and remove any
6966        // duplicate actions that are found here.
6967        N = results.size();
6968        for (int i=specificsPos; i<N-1; i++) {
6969            final ResolveInfo rii = results.get(i);
6970            if (rii.filter == null) {
6971                continue;
6972            }
6973
6974            // Iterate over all of the actions of this result's intent
6975            // filter...  typically this should be just one.
6976            final Iterator<String> it = rii.filter.actionsIterator();
6977            if (it == null) {
6978                continue;
6979            }
6980            while (it.hasNext()) {
6981                final String action = it.next();
6982                if (resultsAction != null && resultsAction.equals(action)) {
6983                    // If this action was explicitly requested, then don't
6984                    // remove things that have it.
6985                    continue;
6986                }
6987                for (int j=i+1; j<N; j++) {
6988                    final ResolveInfo rij = results.get(j);
6989                    if (rij.filter != null && rij.filter.hasAction(action)) {
6990                        results.remove(j);
6991                        if (DEBUG_INTENT_MATCHING) Log.v(
6992                            TAG, "Removing duplicate item from " + j
6993                            + " due to action " + action + " at " + i);
6994                        j--;
6995                        N--;
6996                    }
6997                }
6998            }
6999
7000            // If the caller didn't request filter information, drop it now
7001            // so we don't have to marshall/unmarshall it.
7002            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7003                rii.filter = null;
7004            }
7005        }
7006
7007        // Filter out the caller activity if so requested.
7008        if (caller != null) {
7009            N = results.size();
7010            for (int i=0; i<N; i++) {
7011                ActivityInfo ainfo = results.get(i).activityInfo;
7012                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7013                        && caller.getClassName().equals(ainfo.name)) {
7014                    results.remove(i);
7015                    break;
7016                }
7017            }
7018        }
7019
7020        // If the caller didn't request filter information,
7021        // drop them now so we don't have to
7022        // marshall/unmarshall it.
7023        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7024            N = results.size();
7025            for (int i=0; i<N; i++) {
7026                results.get(i).filter = null;
7027            }
7028        }
7029
7030        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7031        return results;
7032    }
7033
7034    @Override
7035    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7036            String resolvedType, int flags, int userId) {
7037        return new ParceledListSlice<>(
7038                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7039    }
7040
7041    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7042            String resolvedType, int flags, int userId) {
7043        if (!sUserManager.exists(userId)) return Collections.emptyList();
7044        flags = updateFlagsForResolve(flags, userId, intent, false);
7045        ComponentName comp = intent.getComponent();
7046        if (comp == null) {
7047            if (intent.getSelector() != null) {
7048                intent = intent.getSelector();
7049                comp = intent.getComponent();
7050            }
7051        }
7052        if (comp != null) {
7053            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7054            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7055            if (ai != null) {
7056                ResolveInfo ri = new ResolveInfo();
7057                ri.activityInfo = ai;
7058                list.add(ri);
7059            }
7060            return list;
7061        }
7062
7063        // reader
7064        synchronized (mPackages) {
7065            String pkgName = intent.getPackage();
7066            if (pkgName == null) {
7067                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7068            }
7069            final PackageParser.Package pkg = mPackages.get(pkgName);
7070            if (pkg != null) {
7071                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7072                        userId);
7073            }
7074            return Collections.emptyList();
7075        }
7076    }
7077
7078    @Override
7079    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7080        if (!sUserManager.exists(userId)) return null;
7081        flags = updateFlagsForResolve(flags, userId, intent, false);
7082        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7083        if (query != null) {
7084            if (query.size() >= 1) {
7085                // If there is more than one service with the same priority,
7086                // just arbitrarily pick the first one.
7087                return query.get(0);
7088            }
7089        }
7090        return null;
7091    }
7092
7093    @Override
7094    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7095            String resolvedType, int flags, int userId) {
7096        return new ParceledListSlice<>(
7097                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7098    }
7099
7100    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7101            String resolvedType, int flags, int userId) {
7102        if (!sUserManager.exists(userId)) return Collections.emptyList();
7103        flags = updateFlagsForResolve(flags, userId, intent, false);
7104        ComponentName comp = intent.getComponent();
7105        if (comp == null) {
7106            if (intent.getSelector() != null) {
7107                intent = intent.getSelector();
7108                comp = intent.getComponent();
7109            }
7110        }
7111        if (comp != null) {
7112            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7113            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7114            if (si != null) {
7115                final ResolveInfo ri = new ResolveInfo();
7116                ri.serviceInfo = si;
7117                list.add(ri);
7118            }
7119            return list;
7120        }
7121
7122        // reader
7123        synchronized (mPackages) {
7124            String pkgName = intent.getPackage();
7125            if (pkgName == null) {
7126                return mServices.queryIntent(intent, resolvedType, flags, userId);
7127            }
7128            final PackageParser.Package pkg = mPackages.get(pkgName);
7129            if (pkg != null) {
7130                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7131                        userId);
7132            }
7133            return Collections.emptyList();
7134        }
7135    }
7136
7137    @Override
7138    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7139            String resolvedType, int flags, int userId) {
7140        return new ParceledListSlice<>(
7141                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7142    }
7143
7144    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7145            Intent intent, String resolvedType, int flags, int userId) {
7146        if (!sUserManager.exists(userId)) return Collections.emptyList();
7147        flags = updateFlagsForResolve(flags, userId, intent, false);
7148        ComponentName comp = intent.getComponent();
7149        if (comp == null) {
7150            if (intent.getSelector() != null) {
7151                intent = intent.getSelector();
7152                comp = intent.getComponent();
7153            }
7154        }
7155        if (comp != null) {
7156            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7157            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7158            if (pi != null) {
7159                final ResolveInfo ri = new ResolveInfo();
7160                ri.providerInfo = pi;
7161                list.add(ri);
7162            }
7163            return list;
7164        }
7165
7166        // reader
7167        synchronized (mPackages) {
7168            String pkgName = intent.getPackage();
7169            if (pkgName == null) {
7170                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7171            }
7172            final PackageParser.Package pkg = mPackages.get(pkgName);
7173            if (pkg != null) {
7174                return mProviders.queryIntentForPackage(
7175                        intent, resolvedType, flags, pkg.providers, userId);
7176            }
7177            return Collections.emptyList();
7178        }
7179    }
7180
7181    @Override
7182    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7183        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7184        flags = updateFlagsForPackage(flags, userId, null);
7185        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7186        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7187                true /* requireFullPermission */, false /* checkShell */,
7188                "get installed packages");
7189
7190        // writer
7191        synchronized (mPackages) {
7192            ArrayList<PackageInfo> list;
7193            if (listUninstalled) {
7194                list = new ArrayList<>(mSettings.mPackages.size());
7195                for (PackageSetting ps : mSettings.mPackages.values()) {
7196                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7197                        continue;
7198                    }
7199                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7200                    if (pi != null) {
7201                        list.add(pi);
7202                    }
7203                }
7204            } else {
7205                list = new ArrayList<>(mPackages.size());
7206                for (PackageParser.Package p : mPackages.values()) {
7207                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7208                            Binder.getCallingUid(), userId)) {
7209                        continue;
7210                    }
7211                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7212                            p.mExtras, flags, userId);
7213                    if (pi != null) {
7214                        list.add(pi);
7215                    }
7216                }
7217            }
7218
7219            return new ParceledListSlice<>(list);
7220        }
7221    }
7222
7223    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7224            String[] permissions, boolean[] tmp, int flags, int userId) {
7225        int numMatch = 0;
7226        final PermissionsState permissionsState = ps.getPermissionsState();
7227        for (int i=0; i<permissions.length; i++) {
7228            final String permission = permissions[i];
7229            if (permissionsState.hasPermission(permission, userId)) {
7230                tmp[i] = true;
7231                numMatch++;
7232            } else {
7233                tmp[i] = false;
7234            }
7235        }
7236        if (numMatch == 0) {
7237            return;
7238        }
7239        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7240
7241        // The above might return null in cases of uninstalled apps or install-state
7242        // skew across users/profiles.
7243        if (pi != null) {
7244            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7245                if (numMatch == permissions.length) {
7246                    pi.requestedPermissions = permissions;
7247                } else {
7248                    pi.requestedPermissions = new String[numMatch];
7249                    numMatch = 0;
7250                    for (int i=0; i<permissions.length; i++) {
7251                        if (tmp[i]) {
7252                            pi.requestedPermissions[numMatch] = permissions[i];
7253                            numMatch++;
7254                        }
7255                    }
7256                }
7257            }
7258            list.add(pi);
7259        }
7260    }
7261
7262    @Override
7263    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7264            String[] permissions, int flags, int userId) {
7265        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7266        flags = updateFlagsForPackage(flags, userId, permissions);
7267        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7268                true /* requireFullPermission */, false /* checkShell */,
7269                "get packages holding permissions");
7270        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7271
7272        // writer
7273        synchronized (mPackages) {
7274            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7275            boolean[] tmpBools = new boolean[permissions.length];
7276            if (listUninstalled) {
7277                for (PackageSetting ps : mSettings.mPackages.values()) {
7278                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7279                            userId);
7280                }
7281            } else {
7282                for (PackageParser.Package pkg : mPackages.values()) {
7283                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7284                    if (ps != null) {
7285                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7286                                userId);
7287                    }
7288                }
7289            }
7290
7291            return new ParceledListSlice<PackageInfo>(list);
7292        }
7293    }
7294
7295    @Override
7296    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7297        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7298        flags = updateFlagsForApplication(flags, userId, null);
7299        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7300
7301        // writer
7302        synchronized (mPackages) {
7303            ArrayList<ApplicationInfo> list;
7304            if (listUninstalled) {
7305                list = new ArrayList<>(mSettings.mPackages.size());
7306                for (PackageSetting ps : mSettings.mPackages.values()) {
7307                    ApplicationInfo ai;
7308                    int effectiveFlags = flags;
7309                    if (ps.isSystem()) {
7310                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7311                    }
7312                    if (ps.pkg != null) {
7313                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7314                            continue;
7315                        }
7316                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7317                                ps.readUserState(userId), userId);
7318                        if (ai != null) {
7319                            rebaseEnabledOverlays(ai, userId);
7320                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7321                        }
7322                    } else {
7323                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7324                        // and already converts to externally visible package name
7325                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7326                                Binder.getCallingUid(), effectiveFlags, userId);
7327                    }
7328                    if (ai != null) {
7329                        list.add(ai);
7330                    }
7331                }
7332            } else {
7333                list = new ArrayList<>(mPackages.size());
7334                for (PackageParser.Package p : mPackages.values()) {
7335                    if (p.mExtras != null) {
7336                        PackageSetting ps = (PackageSetting) p.mExtras;
7337                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7338                            continue;
7339                        }
7340                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7341                                ps.readUserState(userId), userId);
7342                        if (ai != null) {
7343                            rebaseEnabledOverlays(ai, userId);
7344                            ai.packageName = resolveExternalPackageNameLPr(p);
7345                            list.add(ai);
7346                        }
7347                    }
7348                }
7349            }
7350
7351            return new ParceledListSlice<>(list);
7352        }
7353    }
7354
7355    @Override
7356    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7357        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7358            return null;
7359        }
7360
7361        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7362                "getEphemeralApplications");
7363        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7364                true /* requireFullPermission */, false /* checkShell */,
7365                "getEphemeralApplications");
7366        synchronized (mPackages) {
7367            List<InstantAppInfo> instantApps = mInstantAppRegistry
7368                    .getInstantAppsLPr(userId);
7369            if (instantApps != null) {
7370                return new ParceledListSlice<>(instantApps);
7371            }
7372        }
7373        return null;
7374    }
7375
7376    @Override
7377    public boolean isInstantApp(String packageName, int userId) {
7378        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7379                true /* requireFullPermission */, false /* checkShell */,
7380                "isInstantApp");
7381        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7382            return false;
7383        }
7384
7385        synchronized (mPackages) {
7386            final PackageSetting ps = mSettings.mPackages.get(packageName);
7387            final boolean returnAllowed =
7388                    ps != null
7389                    && (isCallerSameApp(packageName)
7390                            || mContext.checkCallingOrSelfPermission(
7391                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7392                                            == PERMISSION_GRANTED
7393                            || mInstantAppRegistry.isInstantAccessGranted(
7394                                    userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId));
7395            if (returnAllowed) {
7396                return ps.getInstantApp(userId);
7397            }
7398        }
7399        return false;
7400    }
7401
7402    @Override
7403    public byte[] getInstantAppCookie(String packageName, int userId) {
7404        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7405            return null;
7406        }
7407
7408        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7409                true /* requireFullPermission */, false /* checkShell */,
7410                "getInstantAppCookie");
7411        if (!isCallerSameApp(packageName)) {
7412            return null;
7413        }
7414        synchronized (mPackages) {
7415            return mInstantAppRegistry.getInstantAppCookieLPw(
7416                    packageName, userId);
7417        }
7418    }
7419
7420    @Override
7421    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7422        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7423            return true;
7424        }
7425
7426        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7427                true /* requireFullPermission */, true /* checkShell */,
7428                "setInstantAppCookie");
7429        if (!isCallerSameApp(packageName)) {
7430            return false;
7431        }
7432        synchronized (mPackages) {
7433            return mInstantAppRegistry.setInstantAppCookieLPw(
7434                    packageName, cookie, userId);
7435        }
7436    }
7437
7438    @Override
7439    public Bitmap getInstantAppIcon(String packageName, int userId) {
7440        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7441            return null;
7442        }
7443
7444        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7445                "getInstantAppIcon");
7446
7447        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7448                true /* requireFullPermission */, false /* checkShell */,
7449                "getInstantAppIcon");
7450
7451        synchronized (mPackages) {
7452            return mInstantAppRegistry.getInstantAppIconLPw(
7453                    packageName, userId);
7454        }
7455    }
7456
7457    private boolean isCallerSameApp(String packageName) {
7458        PackageParser.Package pkg = mPackages.get(packageName);
7459        return pkg != null
7460                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7461    }
7462
7463    @Override
7464    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7465        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7466    }
7467
7468    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7469        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7470
7471        // reader
7472        synchronized (mPackages) {
7473            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7474            final int userId = UserHandle.getCallingUserId();
7475            while (i.hasNext()) {
7476                final PackageParser.Package p = i.next();
7477                if (p.applicationInfo == null) continue;
7478
7479                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7480                        && !p.applicationInfo.isDirectBootAware();
7481                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7482                        && p.applicationInfo.isDirectBootAware();
7483
7484                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7485                        && (!mSafeMode || isSystemApp(p))
7486                        && (matchesUnaware || matchesAware)) {
7487                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7488                    if (ps != null) {
7489                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7490                                ps.readUserState(userId), userId);
7491                        if (ai != null) {
7492                            rebaseEnabledOverlays(ai, userId);
7493                            finalList.add(ai);
7494                        }
7495                    }
7496                }
7497            }
7498        }
7499
7500        return finalList;
7501    }
7502
7503    @Override
7504    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7505        if (!sUserManager.exists(userId)) return null;
7506        flags = updateFlagsForComponent(flags, userId, name);
7507        // reader
7508        synchronized (mPackages) {
7509            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7510            PackageSetting ps = provider != null
7511                    ? mSettings.mPackages.get(provider.owner.packageName)
7512                    : null;
7513            return ps != null
7514                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7515                    ? PackageParser.generateProviderInfo(provider, flags,
7516                            ps.readUserState(userId), userId)
7517                    : null;
7518        }
7519    }
7520
7521    /**
7522     * @deprecated
7523     */
7524    @Deprecated
7525    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7526        // reader
7527        synchronized (mPackages) {
7528            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7529                    .entrySet().iterator();
7530            final int userId = UserHandle.getCallingUserId();
7531            while (i.hasNext()) {
7532                Map.Entry<String, PackageParser.Provider> entry = i.next();
7533                PackageParser.Provider p = entry.getValue();
7534                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7535
7536                if (ps != null && p.syncable
7537                        && (!mSafeMode || (p.info.applicationInfo.flags
7538                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7539                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7540                            ps.readUserState(userId), userId);
7541                    if (info != null) {
7542                        outNames.add(entry.getKey());
7543                        outInfo.add(info);
7544                    }
7545                }
7546            }
7547        }
7548    }
7549
7550    @Override
7551    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7552            int uid, int flags, String metaDataKey) {
7553        final int userId = processName != null ? UserHandle.getUserId(uid)
7554                : UserHandle.getCallingUserId();
7555        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7556        flags = updateFlagsForComponent(flags, userId, processName);
7557
7558        ArrayList<ProviderInfo> finalList = null;
7559        // reader
7560        synchronized (mPackages) {
7561            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7562            while (i.hasNext()) {
7563                final PackageParser.Provider p = i.next();
7564                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7565                if (ps != null && p.info.authority != null
7566                        && (processName == null
7567                                || (p.info.processName.equals(processName)
7568                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7569                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7570
7571                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7572                    // parameter.
7573                    if (metaDataKey != null
7574                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7575                        continue;
7576                    }
7577
7578                    if (finalList == null) {
7579                        finalList = new ArrayList<ProviderInfo>(3);
7580                    }
7581                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7582                            ps.readUserState(userId), userId);
7583                    if (info != null) {
7584                        finalList.add(info);
7585                    }
7586                }
7587            }
7588        }
7589
7590        if (finalList != null) {
7591            Collections.sort(finalList, mProviderInitOrderSorter);
7592            return new ParceledListSlice<ProviderInfo>(finalList);
7593        }
7594
7595        return ParceledListSlice.emptyList();
7596    }
7597
7598    @Override
7599    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7600        // reader
7601        synchronized (mPackages) {
7602            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7603            return PackageParser.generateInstrumentationInfo(i, flags);
7604        }
7605    }
7606
7607    @Override
7608    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7609            String targetPackage, int flags) {
7610        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7611    }
7612
7613    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7614            int flags) {
7615        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7616
7617        // reader
7618        synchronized (mPackages) {
7619            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7620            while (i.hasNext()) {
7621                final PackageParser.Instrumentation p = i.next();
7622                if (targetPackage == null
7623                        || targetPackage.equals(p.info.targetPackage)) {
7624                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7625                            flags);
7626                    if (ii != null) {
7627                        finalList.add(ii);
7628                    }
7629                }
7630            }
7631        }
7632
7633        return finalList;
7634    }
7635
7636    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7637        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7638        try {
7639            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7640        } finally {
7641            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7642        }
7643    }
7644
7645    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7646        final File[] files = dir.listFiles();
7647        if (ArrayUtils.isEmpty(files)) {
7648            Log.d(TAG, "No files in app dir " + dir);
7649            return;
7650        }
7651
7652        if (DEBUG_PACKAGE_SCANNING) {
7653            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7654                    + " flags=0x" + Integer.toHexString(parseFlags));
7655        }
7656        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7657                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7658
7659        // Submit files for parsing in parallel
7660        int fileCount = 0;
7661        for (File file : files) {
7662            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7663                    && !PackageInstallerService.isStageName(file.getName());
7664            if (!isPackage) {
7665                // Ignore entries which are not packages
7666                continue;
7667            }
7668            parallelPackageParser.submit(file, parseFlags);
7669            fileCount++;
7670        }
7671
7672        // Process results one by one
7673        for (; fileCount > 0; fileCount--) {
7674            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7675            Throwable throwable = parseResult.throwable;
7676            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7677
7678            if (throwable == null) {
7679                // Static shared libraries have synthetic package names
7680                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7681                    renameStaticSharedLibraryPackage(parseResult.pkg);
7682                }
7683                try {
7684                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7685                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7686                                currentTime, null);
7687                    }
7688                } catch (PackageManagerException e) {
7689                    errorCode = e.error;
7690                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7691                }
7692            } else if (throwable instanceof PackageParser.PackageParserException) {
7693                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7694                        throwable;
7695                errorCode = e.error;
7696                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7697            } else {
7698                throw new IllegalStateException("Unexpected exception occurred while parsing "
7699                        + parseResult.scanFile, throwable);
7700            }
7701
7702            // Delete invalid userdata apps
7703            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7704                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7705                logCriticalInfo(Log.WARN,
7706                        "Deleting invalid package at " + parseResult.scanFile);
7707                removeCodePathLI(parseResult.scanFile);
7708            }
7709        }
7710        parallelPackageParser.close();
7711    }
7712
7713    private static File getSettingsProblemFile() {
7714        File dataDir = Environment.getDataDirectory();
7715        File systemDir = new File(dataDir, "system");
7716        File fname = new File(systemDir, "uiderrors.txt");
7717        return fname;
7718    }
7719
7720    static void reportSettingsProblem(int priority, String msg) {
7721        logCriticalInfo(priority, msg);
7722    }
7723
7724    public static void logCriticalInfo(int priority, String msg) {
7725        Slog.println(priority, TAG, msg);
7726        EventLogTags.writePmCriticalInfo(msg);
7727        try {
7728            File fname = getSettingsProblemFile();
7729            FileOutputStream out = new FileOutputStream(fname, true);
7730            PrintWriter pw = new FastPrintWriter(out);
7731            SimpleDateFormat formatter = new SimpleDateFormat();
7732            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7733            pw.println(dateString + ": " + msg);
7734            pw.close();
7735            FileUtils.setPermissions(
7736                    fname.toString(),
7737                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7738                    -1, -1);
7739        } catch (java.io.IOException e) {
7740        }
7741    }
7742
7743    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7744        if (srcFile.isDirectory()) {
7745            final File baseFile = new File(pkg.baseCodePath);
7746            long maxModifiedTime = baseFile.lastModified();
7747            if (pkg.splitCodePaths != null) {
7748                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7749                    final File splitFile = new File(pkg.splitCodePaths[i]);
7750                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7751                }
7752            }
7753            return maxModifiedTime;
7754        }
7755        return srcFile.lastModified();
7756    }
7757
7758    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7759            final int policyFlags) throws PackageManagerException {
7760        // When upgrading from pre-N MR1, verify the package time stamp using the package
7761        // directory and not the APK file.
7762        final long lastModifiedTime = mIsPreNMR1Upgrade
7763                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7764        if (ps != null
7765                && ps.codePath.equals(srcFile)
7766                && ps.timeStamp == lastModifiedTime
7767                && !isCompatSignatureUpdateNeeded(pkg)
7768                && !isRecoverSignatureUpdateNeeded(pkg)) {
7769            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7770            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7771            ArraySet<PublicKey> signingKs;
7772            synchronized (mPackages) {
7773                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7774            }
7775            if (ps.signatures.mSignatures != null
7776                    && ps.signatures.mSignatures.length != 0
7777                    && signingKs != null) {
7778                // Optimization: reuse the existing cached certificates
7779                // if the package appears to be unchanged.
7780                pkg.mSignatures = ps.signatures.mSignatures;
7781                pkg.mSigningKeys = signingKs;
7782                return;
7783            }
7784
7785            Slog.w(TAG, "PackageSetting for " + ps.name
7786                    + " is missing signatures.  Collecting certs again to recover them.");
7787        } else {
7788            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7789        }
7790
7791        try {
7792            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7793            PackageParser.collectCertificates(pkg, policyFlags);
7794        } catch (PackageParserException e) {
7795            throw PackageManagerException.from(e);
7796        } finally {
7797            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7798        }
7799    }
7800
7801    /**
7802     *  Traces a package scan.
7803     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7804     */
7805    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7806            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7807        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7808        try {
7809            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7810        } finally {
7811            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7812        }
7813    }
7814
7815    /**
7816     *  Scans a package and returns the newly parsed package.
7817     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7818     */
7819    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7820            long currentTime, UserHandle user) throws PackageManagerException {
7821        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7822        PackageParser pp = new PackageParser();
7823        pp.setSeparateProcesses(mSeparateProcesses);
7824        pp.setOnlyCoreApps(mOnlyCore);
7825        pp.setDisplayMetrics(mMetrics);
7826        pp.setCallback(mPackageParserCallback);
7827
7828        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7829            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7830        }
7831
7832        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7833        final PackageParser.Package pkg;
7834        try {
7835            pkg = pp.parsePackage(scanFile, parseFlags);
7836        } catch (PackageParserException e) {
7837            throw PackageManagerException.from(e);
7838        } finally {
7839            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7840        }
7841
7842        // Static shared libraries have synthetic package names
7843        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7844            renameStaticSharedLibraryPackage(pkg);
7845        }
7846
7847        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7848    }
7849
7850    /**
7851     *  Scans a package and returns the newly parsed package.
7852     *  @throws PackageManagerException on a parse error.
7853     */
7854    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7855            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7856            throws PackageManagerException {
7857        // If the package has children and this is the first dive in the function
7858        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7859        // packages (parent and children) would be successfully scanned before the
7860        // actual scan since scanning mutates internal state and we want to atomically
7861        // install the package and its children.
7862        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7863            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7864                scanFlags |= SCAN_CHECK_ONLY;
7865            }
7866        } else {
7867            scanFlags &= ~SCAN_CHECK_ONLY;
7868        }
7869
7870        // Scan the parent
7871        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7872                scanFlags, currentTime, user);
7873
7874        // Scan the children
7875        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7876        for (int i = 0; i < childCount; i++) {
7877            PackageParser.Package childPackage = pkg.childPackages.get(i);
7878            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7879                    currentTime, user);
7880        }
7881
7882
7883        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7884            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7885        }
7886
7887        return scannedPkg;
7888    }
7889
7890    /**
7891     *  Scans a package and returns the newly parsed package.
7892     *  @throws PackageManagerException on a parse error.
7893     */
7894    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7895            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7896            throws PackageManagerException {
7897        PackageSetting ps = null;
7898        PackageSetting updatedPkg;
7899        // reader
7900        synchronized (mPackages) {
7901            // Look to see if we already know about this package.
7902            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7903            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7904                // This package has been renamed to its original name.  Let's
7905                // use that.
7906                ps = mSettings.getPackageLPr(oldName);
7907            }
7908            // If there was no original package, see one for the real package name.
7909            if (ps == null) {
7910                ps = mSettings.getPackageLPr(pkg.packageName);
7911            }
7912            // Check to see if this package could be hiding/updating a system
7913            // package.  Must look for it either under the original or real
7914            // package name depending on our state.
7915            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7916            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7917
7918            // If this is a package we don't know about on the system partition, we
7919            // may need to remove disabled child packages on the system partition
7920            // or may need to not add child packages if the parent apk is updated
7921            // on the data partition and no longer defines this child package.
7922            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7923                // If this is a parent package for an updated system app and this system
7924                // app got an OTA update which no longer defines some of the child packages
7925                // we have to prune them from the disabled system packages.
7926                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7927                if (disabledPs != null) {
7928                    final int scannedChildCount = (pkg.childPackages != null)
7929                            ? pkg.childPackages.size() : 0;
7930                    final int disabledChildCount = disabledPs.childPackageNames != null
7931                            ? disabledPs.childPackageNames.size() : 0;
7932                    for (int i = 0; i < disabledChildCount; i++) {
7933                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7934                        boolean disabledPackageAvailable = false;
7935                        for (int j = 0; j < scannedChildCount; j++) {
7936                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7937                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7938                                disabledPackageAvailable = true;
7939                                break;
7940                            }
7941                         }
7942                         if (!disabledPackageAvailable) {
7943                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7944                         }
7945                    }
7946                }
7947            }
7948        }
7949
7950        boolean updatedPkgBetter = false;
7951        // First check if this is a system package that may involve an update
7952        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7953            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7954            // it needs to drop FLAG_PRIVILEGED.
7955            if (locationIsPrivileged(scanFile)) {
7956                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7957            } else {
7958                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7959            }
7960
7961            if (ps != null && !ps.codePath.equals(scanFile)) {
7962                // The path has changed from what was last scanned...  check the
7963                // version of the new path against what we have stored to determine
7964                // what to do.
7965                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7966                if (pkg.mVersionCode <= ps.versionCode) {
7967                    // The system package has been updated and the code path does not match
7968                    // Ignore entry. Skip it.
7969                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7970                            + " ignored: updated version " + ps.versionCode
7971                            + " better than this " + pkg.mVersionCode);
7972                    if (!updatedPkg.codePath.equals(scanFile)) {
7973                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7974                                + ps.name + " changing from " + updatedPkg.codePathString
7975                                + " to " + scanFile);
7976                        updatedPkg.codePath = scanFile;
7977                        updatedPkg.codePathString = scanFile.toString();
7978                        updatedPkg.resourcePath = scanFile;
7979                        updatedPkg.resourcePathString = scanFile.toString();
7980                    }
7981                    updatedPkg.pkg = pkg;
7982                    updatedPkg.versionCode = pkg.mVersionCode;
7983
7984                    // Update the disabled system child packages to point to the package too.
7985                    final int childCount = updatedPkg.childPackageNames != null
7986                            ? updatedPkg.childPackageNames.size() : 0;
7987                    for (int i = 0; i < childCount; i++) {
7988                        String childPackageName = updatedPkg.childPackageNames.get(i);
7989                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7990                                childPackageName);
7991                        if (updatedChildPkg != null) {
7992                            updatedChildPkg.pkg = pkg;
7993                            updatedChildPkg.versionCode = pkg.mVersionCode;
7994                        }
7995                    }
7996
7997                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7998                            + scanFile + " ignored: updated version " + ps.versionCode
7999                            + " better than this " + pkg.mVersionCode);
8000                } else {
8001                    // The current app on the system partition is better than
8002                    // what we have updated to on the data partition; switch
8003                    // back to the system partition version.
8004                    // At this point, its safely assumed that package installation for
8005                    // apps in system partition will go through. If not there won't be a working
8006                    // version of the app
8007                    // writer
8008                    synchronized (mPackages) {
8009                        // Just remove the loaded entries from package lists.
8010                        mPackages.remove(ps.name);
8011                    }
8012
8013                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8014                            + " reverting from " + ps.codePathString
8015                            + ": new version " + pkg.mVersionCode
8016                            + " better than installed " + ps.versionCode);
8017
8018                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8019                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8020                    synchronized (mInstallLock) {
8021                        args.cleanUpResourcesLI();
8022                    }
8023                    synchronized (mPackages) {
8024                        mSettings.enableSystemPackageLPw(ps.name);
8025                    }
8026                    updatedPkgBetter = true;
8027                }
8028            }
8029        }
8030
8031        if (updatedPkg != null) {
8032            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8033            // initially
8034            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8035
8036            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8037            // flag set initially
8038            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8039                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8040            }
8041        }
8042
8043        // Verify certificates against what was last scanned
8044        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8045
8046        /*
8047         * A new system app appeared, but we already had a non-system one of the
8048         * same name installed earlier.
8049         */
8050        boolean shouldHideSystemApp = false;
8051        if (updatedPkg == null && ps != null
8052                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8053            /*
8054             * Check to make sure the signatures match first. If they don't,
8055             * wipe the installed application and its data.
8056             */
8057            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8058                    != PackageManager.SIGNATURE_MATCH) {
8059                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8060                        + " signatures don't match existing userdata copy; removing");
8061                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8062                        "scanPackageInternalLI")) {
8063                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8064                }
8065                ps = null;
8066            } else {
8067                /*
8068                 * If the newly-added system app is an older version than the
8069                 * already installed version, hide it. It will be scanned later
8070                 * and re-added like an update.
8071                 */
8072                if (pkg.mVersionCode <= ps.versionCode) {
8073                    shouldHideSystemApp = true;
8074                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8075                            + " but new version " + pkg.mVersionCode + " better than installed "
8076                            + ps.versionCode + "; hiding system");
8077                } else {
8078                    /*
8079                     * The newly found system app is a newer version that the
8080                     * one previously installed. Simply remove the
8081                     * already-installed application and replace it with our own
8082                     * while keeping the application data.
8083                     */
8084                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8085                            + " reverting from " + ps.codePathString + ": new version "
8086                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8087                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8088                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8089                    synchronized (mInstallLock) {
8090                        args.cleanUpResourcesLI();
8091                    }
8092                }
8093            }
8094        }
8095
8096        // The apk is forward locked (not public) if its code and resources
8097        // are kept in different files. (except for app in either system or
8098        // vendor path).
8099        // TODO grab this value from PackageSettings
8100        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8101            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8102                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8103            }
8104        }
8105
8106        // TODO: extend to support forward-locked splits
8107        String resourcePath = null;
8108        String baseResourcePath = null;
8109        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8110            if (ps != null && ps.resourcePathString != null) {
8111                resourcePath = ps.resourcePathString;
8112                baseResourcePath = ps.resourcePathString;
8113            } else {
8114                // Should not happen at all. Just log an error.
8115                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8116            }
8117        } else {
8118            resourcePath = pkg.codePath;
8119            baseResourcePath = pkg.baseCodePath;
8120        }
8121
8122        // Set application objects path explicitly.
8123        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8124        pkg.setApplicationInfoCodePath(pkg.codePath);
8125        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8126        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8127        pkg.setApplicationInfoResourcePath(resourcePath);
8128        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8129        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8130
8131        final int userId = ((user == null) ? 0 : user.getIdentifier());
8132        if (ps != null && ps.getInstantApp(userId)) {
8133            scanFlags |= SCAN_AS_INSTANT_APP;
8134        }
8135
8136        // Note that we invoke the following method only if we are about to unpack an application
8137        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8138                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8139
8140        /*
8141         * If the system app should be overridden by a previously installed
8142         * data, hide the system app now and let the /data/app scan pick it up
8143         * again.
8144         */
8145        if (shouldHideSystemApp) {
8146            synchronized (mPackages) {
8147                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8148            }
8149        }
8150
8151        return scannedPkg;
8152    }
8153
8154    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8155        // Derive the new package synthetic package name
8156        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8157                + pkg.staticSharedLibVersion);
8158    }
8159
8160    private static String fixProcessName(String defProcessName,
8161            String processName) {
8162        if (processName == null) {
8163            return defProcessName;
8164        }
8165        return processName;
8166    }
8167
8168    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8169            throws PackageManagerException {
8170        if (pkgSetting.signatures.mSignatures != null) {
8171            // Already existing package. Make sure signatures match
8172            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8173                    == PackageManager.SIGNATURE_MATCH;
8174            if (!match) {
8175                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8176                        == PackageManager.SIGNATURE_MATCH;
8177            }
8178            if (!match) {
8179                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8180                        == PackageManager.SIGNATURE_MATCH;
8181            }
8182            if (!match) {
8183                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8184                        + pkg.packageName + " signatures do not match the "
8185                        + "previously installed version; ignoring!");
8186            }
8187        }
8188
8189        // Check for shared user signatures
8190        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8191            // Already existing package. Make sure signatures match
8192            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8193                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8194            if (!match) {
8195                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8196                        == PackageManager.SIGNATURE_MATCH;
8197            }
8198            if (!match) {
8199                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8200                        == PackageManager.SIGNATURE_MATCH;
8201            }
8202            if (!match) {
8203                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8204                        "Package " + pkg.packageName
8205                        + " has no signatures that match those in shared user "
8206                        + pkgSetting.sharedUser.name + "; ignoring!");
8207            }
8208        }
8209    }
8210
8211    /**
8212     * Enforces that only the system UID or root's UID can call a method exposed
8213     * via Binder.
8214     *
8215     * @param message used as message if SecurityException is thrown
8216     * @throws SecurityException if the caller is not system or root
8217     */
8218    private static final void enforceSystemOrRoot(String message) {
8219        final int uid = Binder.getCallingUid();
8220        if (uid != Process.SYSTEM_UID && uid != 0) {
8221            throw new SecurityException(message);
8222        }
8223    }
8224
8225    @Override
8226    public void performFstrimIfNeeded() {
8227        enforceSystemOrRoot("Only the system can request fstrim");
8228
8229        // Before everything else, see whether we need to fstrim.
8230        try {
8231            IStorageManager sm = PackageHelper.getStorageManager();
8232            if (sm != null) {
8233                boolean doTrim = false;
8234                final long interval = android.provider.Settings.Global.getLong(
8235                        mContext.getContentResolver(),
8236                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8237                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8238                if (interval > 0) {
8239                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8240                    if (timeSinceLast > interval) {
8241                        doTrim = true;
8242                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8243                                + "; running immediately");
8244                    }
8245                }
8246                if (doTrim) {
8247                    final boolean dexOptDialogShown;
8248                    synchronized (mPackages) {
8249                        dexOptDialogShown = mDexOptDialogShown;
8250                    }
8251                    if (!isFirstBoot() && dexOptDialogShown) {
8252                        try {
8253                            ActivityManager.getService().showBootMessage(
8254                                    mContext.getResources().getString(
8255                                            R.string.android_upgrading_fstrim), true);
8256                        } catch (RemoteException e) {
8257                        }
8258                    }
8259                    sm.runMaintenance();
8260                }
8261            } else {
8262                Slog.e(TAG, "storageManager service unavailable!");
8263            }
8264        } catch (RemoteException e) {
8265            // Can't happen; StorageManagerService is local
8266        }
8267    }
8268
8269    @Override
8270    public void updatePackagesIfNeeded() {
8271        enforceSystemOrRoot("Only the system can request package update");
8272
8273        // We need to re-extract after an OTA.
8274        boolean causeUpgrade = isUpgrade();
8275
8276        // First boot or factory reset.
8277        // Note: we also handle devices that are upgrading to N right now as if it is their
8278        //       first boot, as they do not have profile data.
8279        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8280
8281        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8282        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8283
8284        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8285            return;
8286        }
8287
8288        List<PackageParser.Package> pkgs;
8289        synchronized (mPackages) {
8290            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8291        }
8292
8293        final long startTime = System.nanoTime();
8294        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8295                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8296
8297        final int elapsedTimeSeconds =
8298                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8299
8300        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8301        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8302        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8303        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8304        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8305    }
8306
8307    /**
8308     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8309     * containing statistics about the invocation. The array consists of three elements,
8310     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8311     * and {@code numberOfPackagesFailed}.
8312     */
8313    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8314            String compilerFilter) {
8315
8316        int numberOfPackagesVisited = 0;
8317        int numberOfPackagesOptimized = 0;
8318        int numberOfPackagesSkipped = 0;
8319        int numberOfPackagesFailed = 0;
8320        final int numberOfPackagesToDexopt = pkgs.size();
8321
8322        for (PackageParser.Package pkg : pkgs) {
8323            numberOfPackagesVisited++;
8324
8325            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8326                if (DEBUG_DEXOPT) {
8327                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8328                }
8329                numberOfPackagesSkipped++;
8330                continue;
8331            }
8332
8333            if (DEBUG_DEXOPT) {
8334                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8335                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8336            }
8337
8338            if (showDialog) {
8339                try {
8340                    ActivityManager.getService().showBootMessage(
8341                            mContext.getResources().getString(R.string.android_upgrading_apk,
8342                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8343                } catch (RemoteException e) {
8344                }
8345                synchronized (mPackages) {
8346                    mDexOptDialogShown = true;
8347                }
8348            }
8349
8350            // If the OTA updates a system app which was previously preopted to a non-preopted state
8351            // the app might end up being verified at runtime. That's because by default the apps
8352            // are verify-profile but for preopted apps there's no profile.
8353            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8354            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8355            // filter (by default interpret-only).
8356            // Note that at this stage unused apps are already filtered.
8357            if (isSystemApp(pkg) &&
8358                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8359                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8360                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8361            }
8362
8363            // checkProfiles is false to avoid merging profiles during boot which
8364            // might interfere with background compilation (b/28612421).
8365            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8366            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8367            // trade-off worth doing to save boot time work.
8368            int dexOptStatus = performDexOptTraced(pkg.packageName,
8369                    false /* checkProfiles */,
8370                    compilerFilter,
8371                    false /* force */);
8372            switch (dexOptStatus) {
8373                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8374                    numberOfPackagesOptimized++;
8375                    break;
8376                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8377                    numberOfPackagesSkipped++;
8378                    break;
8379                case PackageDexOptimizer.DEX_OPT_FAILED:
8380                    numberOfPackagesFailed++;
8381                    break;
8382                default:
8383                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8384                    break;
8385            }
8386        }
8387
8388        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8389                numberOfPackagesFailed };
8390    }
8391
8392    @Override
8393    public void notifyPackageUse(String packageName, int reason) {
8394        synchronized (mPackages) {
8395            PackageParser.Package p = mPackages.get(packageName);
8396            if (p == null) {
8397                return;
8398            }
8399            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8400        }
8401    }
8402
8403    @Override
8404    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8405        int userId = UserHandle.getCallingUserId();
8406        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8407        if (ai == null) {
8408            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8409                + loadingPackageName + ", user=" + userId);
8410            return;
8411        }
8412        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8413    }
8414
8415    // TODO: this is not used nor needed. Delete it.
8416    @Override
8417    public boolean performDexOptIfNeeded(String packageName) {
8418        int dexOptStatus = performDexOptTraced(packageName,
8419                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8420        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8421    }
8422
8423    @Override
8424    public boolean performDexOpt(String packageName,
8425            boolean checkProfiles, int compileReason, boolean force) {
8426        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8427                getCompilerFilterForReason(compileReason), force);
8428        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8429    }
8430
8431    @Override
8432    public boolean performDexOptMode(String packageName,
8433            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8434        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8435                targetCompilerFilter, force);
8436        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8437    }
8438
8439    private int performDexOptTraced(String packageName,
8440                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8441        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8442        try {
8443            return performDexOptInternal(packageName, checkProfiles,
8444                    targetCompilerFilter, force);
8445        } finally {
8446            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8447        }
8448    }
8449
8450    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8451    // if the package can now be considered up to date for the given filter.
8452    private int performDexOptInternal(String packageName,
8453                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8454        PackageParser.Package p;
8455        synchronized (mPackages) {
8456            p = mPackages.get(packageName);
8457            if (p == null) {
8458                // Package could not be found. Report failure.
8459                return PackageDexOptimizer.DEX_OPT_FAILED;
8460            }
8461            mPackageUsage.maybeWriteAsync(mPackages);
8462            mCompilerStats.maybeWriteAsync();
8463        }
8464        long callingId = Binder.clearCallingIdentity();
8465        try {
8466            synchronized (mInstallLock) {
8467                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8468                        targetCompilerFilter, force);
8469            }
8470        } finally {
8471            Binder.restoreCallingIdentity(callingId);
8472        }
8473    }
8474
8475    public ArraySet<String> getOptimizablePackages() {
8476        ArraySet<String> pkgs = new ArraySet<String>();
8477        synchronized (mPackages) {
8478            for (PackageParser.Package p : mPackages.values()) {
8479                if (PackageDexOptimizer.canOptimizePackage(p)) {
8480                    pkgs.add(p.packageName);
8481                }
8482            }
8483        }
8484        return pkgs;
8485    }
8486
8487    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8488            boolean checkProfiles, String targetCompilerFilter,
8489            boolean force) {
8490        // Select the dex optimizer based on the force parameter.
8491        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8492        //       allocate an object here.
8493        PackageDexOptimizer pdo = force
8494                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8495                : mPackageDexOptimizer;
8496
8497        // Optimize all dependencies first. Note: we ignore the return value and march on
8498        // on errors.
8499        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8500        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8501        if (!deps.isEmpty()) {
8502            for (PackageParser.Package depPackage : deps) {
8503                // TODO: Analyze and investigate if we (should) profile libraries.
8504                // Currently this will do a full compilation of the library by default.
8505                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8506                        false /* checkProfiles */,
8507                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8508                        getOrCreateCompilerPackageStats(depPackage),
8509                        mDexManager.isUsedByOtherApps(p.packageName));
8510            }
8511        }
8512        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8513                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8514                mDexManager.isUsedByOtherApps(p.packageName));
8515    }
8516
8517    // Performs dexopt on the used secondary dex files belonging to the given package.
8518    // Returns true if all dex files were process successfully (which could mean either dexopt or
8519    // skip). Returns false if any of the files caused errors.
8520    @Override
8521    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8522            boolean force) {
8523        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8524    }
8525
8526    public boolean performDexOptSecondary(String packageName, int compileReason,
8527            boolean force) {
8528        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8529    }
8530
8531    /**
8532     * Reconcile the information we have about the secondary dex files belonging to
8533     * {@code packagName} and the actual dex files. For all dex files that were
8534     * deleted, update the internal records and delete the generated oat files.
8535     */
8536    @Override
8537    public void reconcileSecondaryDexFiles(String packageName) {
8538        mDexManager.reconcileSecondaryDexFiles(packageName);
8539    }
8540
8541    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8542    // a reference there.
8543    /*package*/ DexManager getDexManager() {
8544        return mDexManager;
8545    }
8546
8547    /**
8548     * Execute the background dexopt job immediately.
8549     */
8550    @Override
8551    public boolean runBackgroundDexoptJob() {
8552        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8553    }
8554
8555    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8556        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8557                || p.usesStaticLibraries != null) {
8558            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8559            Set<String> collectedNames = new HashSet<>();
8560            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8561
8562            retValue.remove(p);
8563
8564            return retValue;
8565        } else {
8566            return Collections.emptyList();
8567        }
8568    }
8569
8570    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8571            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8572        if (!collectedNames.contains(p.packageName)) {
8573            collectedNames.add(p.packageName);
8574            collected.add(p);
8575
8576            if (p.usesLibraries != null) {
8577                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8578                        null, collected, collectedNames);
8579            }
8580            if (p.usesOptionalLibraries != null) {
8581                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8582                        null, collected, collectedNames);
8583            }
8584            if (p.usesStaticLibraries != null) {
8585                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8586                        p.usesStaticLibrariesVersions, collected, collectedNames);
8587            }
8588        }
8589    }
8590
8591    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8592            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8593        final int libNameCount = libs.size();
8594        for (int i = 0; i < libNameCount; i++) {
8595            String libName = libs.get(i);
8596            int version = (versions != null && versions.length == libNameCount)
8597                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8598            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8599            if (libPkg != null) {
8600                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8601            }
8602        }
8603    }
8604
8605    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8606        synchronized (mPackages) {
8607            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8608            if (libEntry != null) {
8609                return mPackages.get(libEntry.apk);
8610            }
8611            return null;
8612        }
8613    }
8614
8615    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8616        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8617        if (versionedLib == null) {
8618            return null;
8619        }
8620        return versionedLib.get(version);
8621    }
8622
8623    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8624        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8625                pkg.staticSharedLibName);
8626        if (versionedLib == null) {
8627            return null;
8628        }
8629        int previousLibVersion = -1;
8630        final int versionCount = versionedLib.size();
8631        for (int i = 0; i < versionCount; i++) {
8632            final int libVersion = versionedLib.keyAt(i);
8633            if (libVersion < pkg.staticSharedLibVersion) {
8634                previousLibVersion = Math.max(previousLibVersion, libVersion);
8635            }
8636        }
8637        if (previousLibVersion >= 0) {
8638            return versionedLib.get(previousLibVersion);
8639        }
8640        return null;
8641    }
8642
8643    public void shutdown() {
8644        mPackageUsage.writeNow(mPackages);
8645        mCompilerStats.writeNow();
8646    }
8647
8648    @Override
8649    public void dumpProfiles(String packageName) {
8650        PackageParser.Package pkg;
8651        synchronized (mPackages) {
8652            pkg = mPackages.get(packageName);
8653            if (pkg == null) {
8654                throw new IllegalArgumentException("Unknown package: " + packageName);
8655            }
8656        }
8657        /* Only the shell, root, or the app user should be able to dump profiles. */
8658        int callingUid = Binder.getCallingUid();
8659        if (callingUid != Process.SHELL_UID &&
8660            callingUid != Process.ROOT_UID &&
8661            callingUid != pkg.applicationInfo.uid) {
8662            throw new SecurityException("dumpProfiles");
8663        }
8664
8665        synchronized (mInstallLock) {
8666            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8667            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8668            try {
8669                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8670                String codePaths = TextUtils.join(";", allCodePaths);
8671                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8672            } catch (InstallerException e) {
8673                Slog.w(TAG, "Failed to dump profiles", e);
8674            }
8675            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8676        }
8677    }
8678
8679    @Override
8680    public void forceDexOpt(String packageName) {
8681        enforceSystemOrRoot("forceDexOpt");
8682
8683        PackageParser.Package pkg;
8684        synchronized (mPackages) {
8685            pkg = mPackages.get(packageName);
8686            if (pkg == null) {
8687                throw new IllegalArgumentException("Unknown package: " + packageName);
8688            }
8689        }
8690
8691        synchronized (mInstallLock) {
8692            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8693
8694            // Whoever is calling forceDexOpt wants a fully compiled package.
8695            // Don't use profiles since that may cause compilation to be skipped.
8696            final int res = performDexOptInternalWithDependenciesLI(pkg,
8697                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8698                    true /* force */);
8699
8700            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8701            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8702                throw new IllegalStateException("Failed to dexopt: " + res);
8703            }
8704        }
8705    }
8706
8707    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8708        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8709            Slog.w(TAG, "Unable to update from " + oldPkg.name
8710                    + " to " + newPkg.packageName
8711                    + ": old package not in system partition");
8712            return false;
8713        } else if (mPackages.get(oldPkg.name) != null) {
8714            Slog.w(TAG, "Unable to update from " + oldPkg.name
8715                    + " to " + newPkg.packageName
8716                    + ": old package still exists");
8717            return false;
8718        }
8719        return true;
8720    }
8721
8722    void removeCodePathLI(File codePath) {
8723        if (codePath.isDirectory()) {
8724            try {
8725                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8726            } catch (InstallerException e) {
8727                Slog.w(TAG, "Failed to remove code path", e);
8728            }
8729        } else {
8730            codePath.delete();
8731        }
8732    }
8733
8734    private int[] resolveUserIds(int userId) {
8735        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8736    }
8737
8738    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8739        if (pkg == null) {
8740            Slog.wtf(TAG, "Package was null!", new Throwable());
8741            return;
8742        }
8743        clearAppDataLeafLIF(pkg, userId, flags);
8744        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8745        for (int i = 0; i < childCount; i++) {
8746            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8747        }
8748    }
8749
8750    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8751        final PackageSetting ps;
8752        synchronized (mPackages) {
8753            ps = mSettings.mPackages.get(pkg.packageName);
8754        }
8755        for (int realUserId : resolveUserIds(userId)) {
8756            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8757            try {
8758                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8759                        ceDataInode);
8760            } catch (InstallerException e) {
8761                Slog.w(TAG, String.valueOf(e));
8762            }
8763        }
8764    }
8765
8766    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8767        if (pkg == null) {
8768            Slog.wtf(TAG, "Package was null!", new Throwable());
8769            return;
8770        }
8771        destroyAppDataLeafLIF(pkg, userId, flags);
8772        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8773        for (int i = 0; i < childCount; i++) {
8774            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8775        }
8776    }
8777
8778    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8779        final PackageSetting ps;
8780        synchronized (mPackages) {
8781            ps = mSettings.mPackages.get(pkg.packageName);
8782        }
8783        for (int realUserId : resolveUserIds(userId)) {
8784            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8785            try {
8786                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8787                        ceDataInode);
8788            } catch (InstallerException e) {
8789                Slog.w(TAG, String.valueOf(e));
8790            }
8791            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8792        }
8793    }
8794
8795    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8796        if (pkg == null) {
8797            Slog.wtf(TAG, "Package was null!", new Throwable());
8798            return;
8799        }
8800        destroyAppProfilesLeafLIF(pkg);
8801        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8802        for (int i = 0; i < childCount; i++) {
8803            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8804        }
8805    }
8806
8807    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8808        try {
8809            mInstaller.destroyAppProfiles(pkg.packageName);
8810        } catch (InstallerException e) {
8811            Slog.w(TAG, String.valueOf(e));
8812        }
8813    }
8814
8815    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8816        if (pkg == null) {
8817            Slog.wtf(TAG, "Package was null!", new Throwable());
8818            return;
8819        }
8820        clearAppProfilesLeafLIF(pkg);
8821        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8822        for (int i = 0; i < childCount; i++) {
8823            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8824        }
8825    }
8826
8827    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8828        try {
8829            mInstaller.clearAppProfiles(pkg.packageName);
8830        } catch (InstallerException e) {
8831            Slog.w(TAG, String.valueOf(e));
8832        }
8833    }
8834
8835    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8836            long lastUpdateTime) {
8837        // Set parent install/update time
8838        PackageSetting ps = (PackageSetting) pkg.mExtras;
8839        if (ps != null) {
8840            ps.firstInstallTime = firstInstallTime;
8841            ps.lastUpdateTime = lastUpdateTime;
8842        }
8843        // Set children install/update time
8844        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8845        for (int i = 0; i < childCount; i++) {
8846            PackageParser.Package childPkg = pkg.childPackages.get(i);
8847            ps = (PackageSetting) childPkg.mExtras;
8848            if (ps != null) {
8849                ps.firstInstallTime = firstInstallTime;
8850                ps.lastUpdateTime = lastUpdateTime;
8851            }
8852        }
8853    }
8854
8855    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8856            PackageParser.Package changingLib) {
8857        if (file.path != null) {
8858            usesLibraryFiles.add(file.path);
8859            return;
8860        }
8861        PackageParser.Package p = mPackages.get(file.apk);
8862        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8863            // If we are doing this while in the middle of updating a library apk,
8864            // then we need to make sure to use that new apk for determining the
8865            // dependencies here.  (We haven't yet finished committing the new apk
8866            // to the package manager state.)
8867            if (p == null || p.packageName.equals(changingLib.packageName)) {
8868                p = changingLib;
8869            }
8870        }
8871        if (p != null) {
8872            usesLibraryFiles.addAll(p.getAllCodePaths());
8873        }
8874    }
8875
8876    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8877            PackageParser.Package changingLib) throws PackageManagerException {
8878        if (pkg == null) {
8879            return;
8880        }
8881        ArraySet<String> usesLibraryFiles = null;
8882        if (pkg.usesLibraries != null) {
8883            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8884                    null, null, pkg.packageName, changingLib, true, null);
8885        }
8886        if (pkg.usesStaticLibraries != null) {
8887            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8888                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8889                    pkg.packageName, changingLib, true, usesLibraryFiles);
8890        }
8891        if (pkg.usesOptionalLibraries != null) {
8892            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8893                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8894        }
8895        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8896            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8897        } else {
8898            pkg.usesLibraryFiles = null;
8899        }
8900    }
8901
8902    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8903            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8904            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8905            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8906            throws PackageManagerException {
8907        final int libCount = requestedLibraries.size();
8908        for (int i = 0; i < libCount; i++) {
8909            final String libName = requestedLibraries.get(i);
8910            final int libVersion = requiredVersions != null ? requiredVersions[i]
8911                    : SharedLibraryInfo.VERSION_UNDEFINED;
8912            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8913            if (libEntry == null) {
8914                if (required) {
8915                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8916                            "Package " + packageName + " requires unavailable shared library "
8917                                    + libName + "; failing!");
8918                } else {
8919                    Slog.w(TAG, "Package " + packageName
8920                            + " desires unavailable shared library "
8921                            + libName + "; ignoring!");
8922                }
8923            } else {
8924                if (requiredVersions != null && requiredCertDigests != null) {
8925                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8926                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8927                            "Package " + packageName + " requires unavailable static shared"
8928                                    + " library " + libName + " version "
8929                                    + libEntry.info.getVersion() + "; failing!");
8930                    }
8931
8932                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8933                    if (libPkg == null) {
8934                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8935                                "Package " + packageName + " requires unavailable static shared"
8936                                        + " library; failing!");
8937                    }
8938
8939                    String expectedCertDigest = requiredCertDigests[i];
8940                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8941                                libPkg.mSignatures[0]);
8942                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8943                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8944                                "Package " + packageName + " requires differently signed" +
8945                                        " static shared library; failing!");
8946                    }
8947                }
8948
8949                if (outUsedLibraries == null) {
8950                    outUsedLibraries = new ArraySet<>();
8951                }
8952                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8953            }
8954        }
8955        return outUsedLibraries;
8956    }
8957
8958    private static boolean hasString(List<String> list, List<String> which) {
8959        if (list == null) {
8960            return false;
8961        }
8962        for (int i=list.size()-1; i>=0; i--) {
8963            for (int j=which.size()-1; j>=0; j--) {
8964                if (which.get(j).equals(list.get(i))) {
8965                    return true;
8966                }
8967            }
8968        }
8969        return false;
8970    }
8971
8972    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8973            PackageParser.Package changingPkg) {
8974        ArrayList<PackageParser.Package> res = null;
8975        for (PackageParser.Package pkg : mPackages.values()) {
8976            if (changingPkg != null
8977                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8978                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8979                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8980                            changingPkg.staticSharedLibName)) {
8981                return null;
8982            }
8983            if (res == null) {
8984                res = new ArrayList<>();
8985            }
8986            res.add(pkg);
8987            try {
8988                updateSharedLibrariesLPr(pkg, changingPkg);
8989            } catch (PackageManagerException e) {
8990                // If a system app update or an app and a required lib missing we
8991                // delete the package and for updated system apps keep the data as
8992                // it is better for the user to reinstall than to be in an limbo
8993                // state. Also libs disappearing under an app should never happen
8994                // - just in case.
8995                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8996                    final int flags = pkg.isUpdatedSystemApp()
8997                            ? PackageManager.DELETE_KEEP_DATA : 0;
8998                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8999                            flags , null, true, null);
9000                }
9001                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9002            }
9003        }
9004        return res;
9005    }
9006
9007    /**
9008     * Derive the value of the {@code cpuAbiOverride} based on the provided
9009     * value and an optional stored value from the package settings.
9010     */
9011    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9012        String cpuAbiOverride = null;
9013
9014        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9015            cpuAbiOverride = null;
9016        } else if (abiOverride != null) {
9017            cpuAbiOverride = abiOverride;
9018        } else if (settings != null) {
9019            cpuAbiOverride = settings.cpuAbiOverrideString;
9020        }
9021
9022        return cpuAbiOverride;
9023    }
9024
9025    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9026            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9027                    throws PackageManagerException {
9028        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9029        // If the package has children and this is the first dive in the function
9030        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9031        // whether all packages (parent and children) would be successfully scanned
9032        // before the actual scan since scanning mutates internal state and we want
9033        // to atomically install the package and its children.
9034        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9035            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9036                scanFlags |= SCAN_CHECK_ONLY;
9037            }
9038        } else {
9039            scanFlags &= ~SCAN_CHECK_ONLY;
9040        }
9041
9042        final PackageParser.Package scannedPkg;
9043        try {
9044            // Scan the parent
9045            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9046            // Scan the children
9047            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9048            for (int i = 0; i < childCount; i++) {
9049                PackageParser.Package childPkg = pkg.childPackages.get(i);
9050                scanPackageLI(childPkg, policyFlags,
9051                        scanFlags, currentTime, user);
9052            }
9053        } finally {
9054            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9055        }
9056
9057        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9058            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9059        }
9060
9061        return scannedPkg;
9062    }
9063
9064    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9065            int scanFlags, long currentTime, @Nullable UserHandle user)
9066                    throws PackageManagerException {
9067        boolean success = false;
9068        try {
9069            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9070                    currentTime, user);
9071            success = true;
9072            return res;
9073        } finally {
9074            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9075                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9076                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9077                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9078                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9079            }
9080        }
9081    }
9082
9083    /**
9084     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9085     */
9086    private static boolean apkHasCode(String fileName) {
9087        StrictJarFile jarFile = null;
9088        try {
9089            jarFile = new StrictJarFile(fileName,
9090                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9091            return jarFile.findEntry("classes.dex") != null;
9092        } catch (IOException ignore) {
9093        } finally {
9094            try {
9095                if (jarFile != null) {
9096                    jarFile.close();
9097                }
9098            } catch (IOException ignore) {}
9099        }
9100        return false;
9101    }
9102
9103    /**
9104     * Enforces code policy for the package. This ensures that if an APK has
9105     * declared hasCode="true" in its manifest that the APK actually contains
9106     * code.
9107     *
9108     * @throws PackageManagerException If bytecode could not be found when it should exist
9109     */
9110    private static void assertCodePolicy(PackageParser.Package pkg)
9111            throws PackageManagerException {
9112        final boolean shouldHaveCode =
9113                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9114        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9115            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9116                    "Package " + pkg.baseCodePath + " code is missing");
9117        }
9118
9119        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9120            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9121                final boolean splitShouldHaveCode =
9122                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9123                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9124                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9125                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9126                }
9127            }
9128        }
9129    }
9130
9131    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9132            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9133                    throws PackageManagerException {
9134        if (DEBUG_PACKAGE_SCANNING) {
9135            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9136                Log.d(TAG, "Scanning package " + pkg.packageName);
9137        }
9138
9139        applyPolicy(pkg, policyFlags);
9140
9141        assertPackageIsValid(pkg, policyFlags, scanFlags);
9142
9143        // Initialize package source and resource directories
9144        final File scanFile = new File(pkg.codePath);
9145        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9146        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9147
9148        SharedUserSetting suid = null;
9149        PackageSetting pkgSetting = null;
9150
9151        // Getting the package setting may have a side-effect, so if we
9152        // are only checking if scan would succeed, stash a copy of the
9153        // old setting to restore at the end.
9154        PackageSetting nonMutatedPs = null;
9155
9156        // We keep references to the derived CPU Abis from settings in oder to reuse
9157        // them in the case where we're not upgrading or booting for the first time.
9158        String primaryCpuAbiFromSettings = null;
9159        String secondaryCpuAbiFromSettings = null;
9160
9161        // writer
9162        synchronized (mPackages) {
9163            if (pkg.mSharedUserId != null) {
9164                // SIDE EFFECTS; may potentially allocate a new shared user
9165                suid = mSettings.getSharedUserLPw(
9166                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9167                if (DEBUG_PACKAGE_SCANNING) {
9168                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9169                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9170                                + "): packages=" + suid.packages);
9171                }
9172            }
9173
9174            // Check if we are renaming from an original package name.
9175            PackageSetting origPackage = null;
9176            String realName = null;
9177            if (pkg.mOriginalPackages != null) {
9178                // This package may need to be renamed to a previously
9179                // installed name.  Let's check on that...
9180                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9181                if (pkg.mOriginalPackages.contains(renamed)) {
9182                    // This package had originally been installed as the
9183                    // original name, and we have already taken care of
9184                    // transitioning to the new one.  Just update the new
9185                    // one to continue using the old name.
9186                    realName = pkg.mRealPackage;
9187                    if (!pkg.packageName.equals(renamed)) {
9188                        // Callers into this function may have already taken
9189                        // care of renaming the package; only do it here if
9190                        // it is not already done.
9191                        pkg.setPackageName(renamed);
9192                    }
9193                } else {
9194                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9195                        if ((origPackage = mSettings.getPackageLPr(
9196                                pkg.mOriginalPackages.get(i))) != null) {
9197                            // We do have the package already installed under its
9198                            // original name...  should we use it?
9199                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9200                                // New package is not compatible with original.
9201                                origPackage = null;
9202                                continue;
9203                            } else if (origPackage.sharedUser != null) {
9204                                // Make sure uid is compatible between packages.
9205                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9206                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9207                                            + " to " + pkg.packageName + ": old uid "
9208                                            + origPackage.sharedUser.name
9209                                            + " differs from " + pkg.mSharedUserId);
9210                                    origPackage = null;
9211                                    continue;
9212                                }
9213                                // TODO: Add case when shared user id is added [b/28144775]
9214                            } else {
9215                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9216                                        + pkg.packageName + " to old name " + origPackage.name);
9217                            }
9218                            break;
9219                        }
9220                    }
9221                }
9222            }
9223
9224            if (mTransferedPackages.contains(pkg.packageName)) {
9225                Slog.w(TAG, "Package " + pkg.packageName
9226                        + " was transferred to another, but its .apk remains");
9227            }
9228
9229            // See comments in nonMutatedPs declaration
9230            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9231                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9232                if (foundPs != null) {
9233                    nonMutatedPs = new PackageSetting(foundPs);
9234                }
9235            }
9236
9237            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9238                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9239                if (foundPs != null) {
9240                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9241                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9242                }
9243            }
9244
9245            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9246            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9247                PackageManagerService.reportSettingsProblem(Log.WARN,
9248                        "Package " + pkg.packageName + " shared user changed from "
9249                                + (pkgSetting.sharedUser != null
9250                                        ? pkgSetting.sharedUser.name : "<nothing>")
9251                                + " to "
9252                                + (suid != null ? suid.name : "<nothing>")
9253                                + "; replacing with new");
9254                pkgSetting = null;
9255            }
9256            final PackageSetting oldPkgSetting =
9257                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9258            final PackageSetting disabledPkgSetting =
9259                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9260
9261            String[] usesStaticLibraries = null;
9262            if (pkg.usesStaticLibraries != null) {
9263                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9264                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9265            }
9266
9267            if (pkgSetting == null) {
9268                final String parentPackageName = (pkg.parentPackage != null)
9269                        ? pkg.parentPackage.packageName : null;
9270                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9271                // REMOVE SharedUserSetting from method; update in a separate call
9272                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9273                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9274                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9275                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9276                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9277                        true /*allowInstall*/, instantApp, parentPackageName,
9278                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9279                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9280                // SIDE EFFECTS; updates system state; move elsewhere
9281                if (origPackage != null) {
9282                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9283                }
9284                mSettings.addUserToSettingLPw(pkgSetting);
9285            } else {
9286                // REMOVE SharedUserSetting from method; update in a separate call.
9287                //
9288                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9289                // secondaryCpuAbi are not known at this point so we always update them
9290                // to null here, only to reset them at a later point.
9291                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9292                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9293                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9294                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9295                        UserManagerService.getInstance(), usesStaticLibraries,
9296                        pkg.usesStaticLibrariesVersions);
9297            }
9298            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9299            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9300
9301            // SIDE EFFECTS; modifies system state; move elsewhere
9302            if (pkgSetting.origPackage != null) {
9303                // If we are first transitioning from an original package,
9304                // fix up the new package's name now.  We need to do this after
9305                // looking up the package under its new name, so getPackageLP
9306                // can take care of fiddling things correctly.
9307                pkg.setPackageName(origPackage.name);
9308
9309                // File a report about this.
9310                String msg = "New package " + pkgSetting.realName
9311                        + " renamed to replace old package " + pkgSetting.name;
9312                reportSettingsProblem(Log.WARN, msg);
9313
9314                // Make a note of it.
9315                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9316                    mTransferedPackages.add(origPackage.name);
9317                }
9318
9319                // No longer need to retain this.
9320                pkgSetting.origPackage = null;
9321            }
9322
9323            // SIDE EFFECTS; modifies system state; move elsewhere
9324            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9325                // Make a note of it.
9326                mTransferedPackages.add(pkg.packageName);
9327            }
9328
9329            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9330                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9331            }
9332
9333            if ((scanFlags & SCAN_BOOTING) == 0
9334                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9335                // Check all shared libraries and map to their actual file path.
9336                // We only do this here for apps not on a system dir, because those
9337                // are the only ones that can fail an install due to this.  We
9338                // will take care of the system apps by updating all of their
9339                // library paths after the scan is done. Also during the initial
9340                // scan don't update any libs as we do this wholesale after all
9341                // apps are scanned to avoid dependency based scanning.
9342                updateSharedLibrariesLPr(pkg, null);
9343            }
9344
9345            if (mFoundPolicyFile) {
9346                SELinuxMMAC.assignSeInfoValue(pkg);
9347            }
9348            pkg.applicationInfo.uid = pkgSetting.appId;
9349            pkg.mExtras = pkgSetting;
9350
9351
9352            // Static shared libs have same package with different versions where
9353            // we internally use a synthetic package name to allow multiple versions
9354            // of the same package, therefore we need to compare signatures against
9355            // the package setting for the latest library version.
9356            PackageSetting signatureCheckPs = pkgSetting;
9357            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9358                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9359                if (libraryEntry != null) {
9360                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9361                }
9362            }
9363
9364            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9365                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9366                    // We just determined the app is signed correctly, so bring
9367                    // over the latest parsed certs.
9368                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9369                } else {
9370                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9371                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9372                                "Package " + pkg.packageName + " upgrade keys do not match the "
9373                                + "previously installed version");
9374                    } else {
9375                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9376                        String msg = "System package " + pkg.packageName
9377                                + " signature changed; retaining data.";
9378                        reportSettingsProblem(Log.WARN, msg);
9379                    }
9380                }
9381            } else {
9382                try {
9383                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9384                    verifySignaturesLP(signatureCheckPs, pkg);
9385                    // We just determined the app is signed correctly, so bring
9386                    // over the latest parsed certs.
9387                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9388                } catch (PackageManagerException e) {
9389                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9390                        throw e;
9391                    }
9392                    // The signature has changed, but this package is in the system
9393                    // image...  let's recover!
9394                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9395                    // However...  if this package is part of a shared user, but it
9396                    // doesn't match the signature of the shared user, let's fail.
9397                    // What this means is that you can't change the signatures
9398                    // associated with an overall shared user, which doesn't seem all
9399                    // that unreasonable.
9400                    if (signatureCheckPs.sharedUser != null) {
9401                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9402                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9403                            throw new PackageManagerException(
9404                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9405                                    "Signature mismatch for shared user: "
9406                                            + pkgSetting.sharedUser);
9407                        }
9408                    }
9409                    // File a report about this.
9410                    String msg = "System package " + pkg.packageName
9411                            + " signature changed; retaining data.";
9412                    reportSettingsProblem(Log.WARN, msg);
9413                }
9414            }
9415
9416            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9417                // This package wants to adopt ownership of permissions from
9418                // another package.
9419                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9420                    final String origName = pkg.mAdoptPermissions.get(i);
9421                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9422                    if (orig != null) {
9423                        if (verifyPackageUpdateLPr(orig, pkg)) {
9424                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9425                                    + pkg.packageName);
9426                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9427                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9428                        }
9429                    }
9430                }
9431            }
9432        }
9433
9434        pkg.applicationInfo.processName = fixProcessName(
9435                pkg.applicationInfo.packageName,
9436                pkg.applicationInfo.processName);
9437
9438        if (pkg != mPlatformPackage) {
9439            // Get all of our default paths setup
9440            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9441        }
9442
9443        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9444
9445        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9446            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9447                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9448                derivePackageAbi(
9449                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9450                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9451
9452                // Some system apps still use directory structure for native libraries
9453                // in which case we might end up not detecting abi solely based on apk
9454                // structure. Try to detect abi based on directory structure.
9455                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9456                        pkg.applicationInfo.primaryCpuAbi == null) {
9457                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9458                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9459                }
9460            } else {
9461                // This is not a first boot or an upgrade, don't bother deriving the
9462                // ABI during the scan. Instead, trust the value that was stored in the
9463                // package setting.
9464                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9465                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9466
9467                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9468
9469                if (DEBUG_ABI_SELECTION) {
9470                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9471                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9472                        pkg.applicationInfo.secondaryCpuAbi);
9473                }
9474            }
9475        } else {
9476            if ((scanFlags & SCAN_MOVE) != 0) {
9477                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9478                // but we already have this packages package info in the PackageSetting. We just
9479                // use that and derive the native library path based on the new codepath.
9480                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9481                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9482            }
9483
9484            // Set native library paths again. For moves, the path will be updated based on the
9485            // ABIs we've determined above. For non-moves, the path will be updated based on the
9486            // ABIs we determined during compilation, but the path will depend on the final
9487            // package path (after the rename away from the stage path).
9488            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9489        }
9490
9491        // This is a special case for the "system" package, where the ABI is
9492        // dictated by the zygote configuration (and init.rc). We should keep track
9493        // of this ABI so that we can deal with "normal" applications that run under
9494        // the same UID correctly.
9495        if (mPlatformPackage == pkg) {
9496            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9497                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9498        }
9499
9500        // If there's a mismatch between the abi-override in the package setting
9501        // and the abiOverride specified for the install. Warn about this because we
9502        // would've already compiled the app without taking the package setting into
9503        // account.
9504        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9505            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9506                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9507                        " for package " + pkg.packageName);
9508            }
9509        }
9510
9511        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9512        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9513        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9514
9515        // Copy the derived override back to the parsed package, so that we can
9516        // update the package settings accordingly.
9517        pkg.cpuAbiOverride = cpuAbiOverride;
9518
9519        if (DEBUG_ABI_SELECTION) {
9520            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9521                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9522                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9523        }
9524
9525        // Push the derived path down into PackageSettings so we know what to
9526        // clean up at uninstall time.
9527        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9528
9529        if (DEBUG_ABI_SELECTION) {
9530            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9531                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9532                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9533        }
9534
9535        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9536        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9537            // We don't do this here during boot because we can do it all
9538            // at once after scanning all existing packages.
9539            //
9540            // We also do this *before* we perform dexopt on this package, so that
9541            // we can avoid redundant dexopts, and also to make sure we've got the
9542            // code and package path correct.
9543            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9544        }
9545
9546        if (mFactoryTest && pkg.requestedPermissions.contains(
9547                android.Manifest.permission.FACTORY_TEST)) {
9548            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9549        }
9550
9551        if (isSystemApp(pkg)) {
9552            pkgSetting.isOrphaned = true;
9553        }
9554
9555        // Take care of first install / last update times.
9556        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9557        if (currentTime != 0) {
9558            if (pkgSetting.firstInstallTime == 0) {
9559                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9560            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9561                pkgSetting.lastUpdateTime = currentTime;
9562            }
9563        } else if (pkgSetting.firstInstallTime == 0) {
9564            // We need *something*.  Take time time stamp of the file.
9565            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9566        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9567            if (scanFileTime != pkgSetting.timeStamp) {
9568                // A package on the system image has changed; consider this
9569                // to be an update.
9570                pkgSetting.lastUpdateTime = scanFileTime;
9571            }
9572        }
9573        pkgSetting.setTimeStamp(scanFileTime);
9574
9575        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9576            if (nonMutatedPs != null) {
9577                synchronized (mPackages) {
9578                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9579                }
9580            }
9581        } else {
9582            final int userId = user == null ? 0 : user.getIdentifier();
9583            // Modify state for the given package setting
9584            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9585                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9586            if (pkgSetting.getInstantApp(userId)) {
9587                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9588            }
9589        }
9590        return pkg;
9591    }
9592
9593    /**
9594     * Applies policy to the parsed package based upon the given policy flags.
9595     * Ensures the package is in a good state.
9596     * <p>
9597     * Implementation detail: This method must NOT have any side effect. It would
9598     * ideally be static, but, it requires locks to read system state.
9599     */
9600    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9601        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9602            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9603            if (pkg.applicationInfo.isDirectBootAware()) {
9604                // we're direct boot aware; set for all components
9605                for (PackageParser.Service s : pkg.services) {
9606                    s.info.encryptionAware = s.info.directBootAware = true;
9607                }
9608                for (PackageParser.Provider p : pkg.providers) {
9609                    p.info.encryptionAware = p.info.directBootAware = true;
9610                }
9611                for (PackageParser.Activity a : pkg.activities) {
9612                    a.info.encryptionAware = a.info.directBootAware = true;
9613                }
9614                for (PackageParser.Activity r : pkg.receivers) {
9615                    r.info.encryptionAware = r.info.directBootAware = true;
9616                }
9617            }
9618        } else {
9619            // Only allow system apps to be flagged as core apps.
9620            pkg.coreApp = false;
9621            // clear flags not applicable to regular apps
9622            pkg.applicationInfo.privateFlags &=
9623                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9624            pkg.applicationInfo.privateFlags &=
9625                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9626        }
9627        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9628
9629        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9630            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9631        }
9632
9633        if (!isSystemApp(pkg)) {
9634            // Only system apps can use these features.
9635            pkg.mOriginalPackages = null;
9636            pkg.mRealPackage = null;
9637            pkg.mAdoptPermissions = null;
9638        }
9639    }
9640
9641    /**
9642     * Asserts the parsed package is valid according to the given policy. If the
9643     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9644     * <p>
9645     * Implementation detail: This method must NOT have any side effects. It would
9646     * ideally be static, but, it requires locks to read system state.
9647     *
9648     * @throws PackageManagerException If the package fails any of the validation checks
9649     */
9650    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9651            throws PackageManagerException {
9652        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9653            assertCodePolicy(pkg);
9654        }
9655
9656        if (pkg.applicationInfo.getCodePath() == null ||
9657                pkg.applicationInfo.getResourcePath() == null) {
9658            // Bail out. The resource and code paths haven't been set.
9659            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9660                    "Code and resource paths haven't been set correctly");
9661        }
9662
9663        // Make sure we're not adding any bogus keyset info
9664        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9665        ksms.assertScannedPackageValid(pkg);
9666
9667        synchronized (mPackages) {
9668            // The special "android" package can only be defined once
9669            if (pkg.packageName.equals("android")) {
9670                if (mAndroidApplication != null) {
9671                    Slog.w(TAG, "*************************************************");
9672                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9673                    Slog.w(TAG, " codePath=" + pkg.codePath);
9674                    Slog.w(TAG, "*************************************************");
9675                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9676                            "Core android package being redefined.  Skipping.");
9677                }
9678            }
9679
9680            // A package name must be unique; don't allow duplicates
9681            if (mPackages.containsKey(pkg.packageName)) {
9682                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9683                        "Application package " + pkg.packageName
9684                        + " already installed.  Skipping duplicate.");
9685            }
9686
9687            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9688                // Static libs have a synthetic package name containing the version
9689                // but we still want the base name to be unique.
9690                if (mPackages.containsKey(pkg.manifestPackageName)) {
9691                    throw new PackageManagerException(
9692                            "Duplicate static shared lib provider package");
9693                }
9694
9695                // Static shared libraries should have at least O target SDK
9696                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9697                    throw new PackageManagerException(
9698                            "Packages declaring static-shared libs must target O SDK or higher");
9699                }
9700
9701                // Package declaring static a shared lib cannot be instant apps
9702                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9703                    throw new PackageManagerException(
9704                            "Packages declaring static-shared libs cannot be instant apps");
9705                }
9706
9707                // Package declaring static a shared lib cannot be renamed since the package
9708                // name is synthetic and apps can't code around package manager internals.
9709                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9710                    throw new PackageManagerException(
9711                            "Packages declaring static-shared libs cannot be renamed");
9712                }
9713
9714                // Package declaring static a shared lib cannot declare child packages
9715                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9716                    throw new PackageManagerException(
9717                            "Packages declaring static-shared libs cannot have child packages");
9718                }
9719
9720                // Package declaring static a shared lib cannot declare dynamic libs
9721                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9722                    throw new PackageManagerException(
9723                            "Packages declaring static-shared libs cannot declare dynamic libs");
9724                }
9725
9726                // Package declaring static a shared lib cannot declare shared users
9727                if (pkg.mSharedUserId != null) {
9728                    throw new PackageManagerException(
9729                            "Packages declaring static-shared libs cannot declare shared users");
9730                }
9731
9732                // Static shared libs cannot declare activities
9733                if (!pkg.activities.isEmpty()) {
9734                    throw new PackageManagerException(
9735                            "Static shared libs cannot declare activities");
9736                }
9737
9738                // Static shared libs cannot declare services
9739                if (!pkg.services.isEmpty()) {
9740                    throw new PackageManagerException(
9741                            "Static shared libs cannot declare services");
9742                }
9743
9744                // Static shared libs cannot declare providers
9745                if (!pkg.providers.isEmpty()) {
9746                    throw new PackageManagerException(
9747                            "Static shared libs cannot declare content providers");
9748                }
9749
9750                // Static shared libs cannot declare receivers
9751                if (!pkg.receivers.isEmpty()) {
9752                    throw new PackageManagerException(
9753                            "Static shared libs cannot declare broadcast receivers");
9754                }
9755
9756                // Static shared libs cannot declare permission groups
9757                if (!pkg.permissionGroups.isEmpty()) {
9758                    throw new PackageManagerException(
9759                            "Static shared libs cannot declare permission groups");
9760                }
9761
9762                // Static shared libs cannot declare permissions
9763                if (!pkg.permissions.isEmpty()) {
9764                    throw new PackageManagerException(
9765                            "Static shared libs cannot declare permissions");
9766                }
9767
9768                // Static shared libs cannot declare protected broadcasts
9769                if (pkg.protectedBroadcasts != null) {
9770                    throw new PackageManagerException(
9771                            "Static shared libs cannot declare protected broadcasts");
9772                }
9773
9774                // Static shared libs cannot be overlay targets
9775                if (pkg.mOverlayTarget != null) {
9776                    throw new PackageManagerException(
9777                            "Static shared libs cannot be overlay targets");
9778                }
9779
9780                // The version codes must be ordered as lib versions
9781                int minVersionCode = Integer.MIN_VALUE;
9782                int maxVersionCode = Integer.MAX_VALUE;
9783
9784                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9785                        pkg.staticSharedLibName);
9786                if (versionedLib != null) {
9787                    final int versionCount = versionedLib.size();
9788                    for (int i = 0; i < versionCount; i++) {
9789                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9790                        // TODO: We will change version code to long, so in the new API it is long
9791                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9792                                .getVersionCode();
9793                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9794                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9795                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9796                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9797                        } else {
9798                            minVersionCode = maxVersionCode = libVersionCode;
9799                            break;
9800                        }
9801                    }
9802                }
9803                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9804                    throw new PackageManagerException("Static shared"
9805                            + " lib version codes must be ordered as lib versions");
9806                }
9807            }
9808
9809            // Only privileged apps and updated privileged apps can add child packages.
9810            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9811                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9812                    throw new PackageManagerException("Only privileged apps can add child "
9813                            + "packages. Ignoring package " + pkg.packageName);
9814                }
9815                final int childCount = pkg.childPackages.size();
9816                for (int i = 0; i < childCount; i++) {
9817                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9818                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9819                            childPkg.packageName)) {
9820                        throw new PackageManagerException("Can't override child of "
9821                                + "another disabled app. Ignoring package " + pkg.packageName);
9822                    }
9823                }
9824            }
9825
9826            // If we're only installing presumed-existing packages, require that the
9827            // scanned APK is both already known and at the path previously established
9828            // for it.  Previously unknown packages we pick up normally, but if we have an
9829            // a priori expectation about this package's install presence, enforce it.
9830            // With a singular exception for new system packages. When an OTA contains
9831            // a new system package, we allow the codepath to change from a system location
9832            // to the user-installed location. If we don't allow this change, any newer,
9833            // user-installed version of the application will be ignored.
9834            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9835                if (mExpectingBetter.containsKey(pkg.packageName)) {
9836                    logCriticalInfo(Log.WARN,
9837                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9838                } else {
9839                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9840                    if (known != null) {
9841                        if (DEBUG_PACKAGE_SCANNING) {
9842                            Log.d(TAG, "Examining " + pkg.codePath
9843                                    + " and requiring known paths " + known.codePathString
9844                                    + " & " + known.resourcePathString);
9845                        }
9846                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9847                                || !pkg.applicationInfo.getResourcePath().equals(
9848                                        known.resourcePathString)) {
9849                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9850                                    "Application package " + pkg.packageName
9851                                    + " found at " + pkg.applicationInfo.getCodePath()
9852                                    + " but expected at " + known.codePathString
9853                                    + "; ignoring.");
9854                        }
9855                    }
9856                }
9857            }
9858
9859            // Verify that this new package doesn't have any content providers
9860            // that conflict with existing packages.  Only do this if the
9861            // package isn't already installed, since we don't want to break
9862            // things that are installed.
9863            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9864                final int N = pkg.providers.size();
9865                int i;
9866                for (i=0; i<N; i++) {
9867                    PackageParser.Provider p = pkg.providers.get(i);
9868                    if (p.info.authority != null) {
9869                        String names[] = p.info.authority.split(";");
9870                        for (int j = 0; j < names.length; j++) {
9871                            if (mProvidersByAuthority.containsKey(names[j])) {
9872                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9873                                final String otherPackageName =
9874                                        ((other != null && other.getComponentName() != null) ?
9875                                                other.getComponentName().getPackageName() : "?");
9876                                throw new PackageManagerException(
9877                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9878                                        "Can't install because provider name " + names[j]
9879                                                + " (in package " + pkg.applicationInfo.packageName
9880                                                + ") is already used by " + otherPackageName);
9881                            }
9882                        }
9883                    }
9884                }
9885            }
9886        }
9887    }
9888
9889    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9890            int type, String declaringPackageName, int declaringVersionCode) {
9891        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9892        if (versionedLib == null) {
9893            versionedLib = new SparseArray<>();
9894            mSharedLibraries.put(name, versionedLib);
9895            if (type == SharedLibraryInfo.TYPE_STATIC) {
9896                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9897            }
9898        } else if (versionedLib.indexOfKey(version) >= 0) {
9899            return false;
9900        }
9901        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9902                version, type, declaringPackageName, declaringVersionCode);
9903        versionedLib.put(version, libEntry);
9904        return true;
9905    }
9906
9907    private boolean removeSharedLibraryLPw(String name, int version) {
9908        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9909        if (versionedLib == null) {
9910            return false;
9911        }
9912        final int libIdx = versionedLib.indexOfKey(version);
9913        if (libIdx < 0) {
9914            return false;
9915        }
9916        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9917        versionedLib.remove(version);
9918        if (versionedLib.size() <= 0) {
9919            mSharedLibraries.remove(name);
9920            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9921                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9922                        .getPackageName());
9923            }
9924        }
9925        return true;
9926    }
9927
9928    /**
9929     * Adds a scanned package to the system. When this method is finished, the package will
9930     * be available for query, resolution, etc...
9931     */
9932    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9933            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9934        final String pkgName = pkg.packageName;
9935        if (mCustomResolverComponentName != null &&
9936                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9937            setUpCustomResolverActivity(pkg);
9938        }
9939
9940        if (pkg.packageName.equals("android")) {
9941            synchronized (mPackages) {
9942                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9943                    // Set up information for our fall-back user intent resolution activity.
9944                    mPlatformPackage = pkg;
9945                    pkg.mVersionCode = mSdkVersion;
9946                    mAndroidApplication = pkg.applicationInfo;
9947                    if (!mResolverReplaced) {
9948                        mResolveActivity.applicationInfo = mAndroidApplication;
9949                        mResolveActivity.name = ResolverActivity.class.getName();
9950                        mResolveActivity.packageName = mAndroidApplication.packageName;
9951                        mResolveActivity.processName = "system:ui";
9952                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9953                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9954                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9955                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9956                        mResolveActivity.exported = true;
9957                        mResolveActivity.enabled = true;
9958                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9959                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9960                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9961                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9962                                | ActivityInfo.CONFIG_ORIENTATION
9963                                | ActivityInfo.CONFIG_KEYBOARD
9964                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9965                        mResolveInfo.activityInfo = mResolveActivity;
9966                        mResolveInfo.priority = 0;
9967                        mResolveInfo.preferredOrder = 0;
9968                        mResolveInfo.match = 0;
9969                        mResolveComponentName = new ComponentName(
9970                                mAndroidApplication.packageName, mResolveActivity.name);
9971                    }
9972                }
9973            }
9974        }
9975
9976        ArrayList<PackageParser.Package> clientLibPkgs = null;
9977        // writer
9978        synchronized (mPackages) {
9979            boolean hasStaticSharedLibs = false;
9980
9981            // Any app can add new static shared libraries
9982            if (pkg.staticSharedLibName != null) {
9983                // Static shared libs don't allow renaming as they have synthetic package
9984                // names to allow install of multiple versions, so use name from manifest.
9985                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9986                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9987                        pkg.manifestPackageName, pkg.mVersionCode)) {
9988                    hasStaticSharedLibs = true;
9989                } else {
9990                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9991                                + pkg.staticSharedLibName + " already exists; skipping");
9992                }
9993                // Static shared libs cannot be updated once installed since they
9994                // use synthetic package name which includes the version code, so
9995                // not need to update other packages's shared lib dependencies.
9996            }
9997
9998            if (!hasStaticSharedLibs
9999                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10000                // Only system apps can add new dynamic shared libraries.
10001                if (pkg.libraryNames != null) {
10002                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10003                        String name = pkg.libraryNames.get(i);
10004                        boolean allowed = false;
10005                        if (pkg.isUpdatedSystemApp()) {
10006                            // New library entries can only be added through the
10007                            // system image.  This is important to get rid of a lot
10008                            // of nasty edge cases: for example if we allowed a non-
10009                            // system update of the app to add a library, then uninstalling
10010                            // the update would make the library go away, and assumptions
10011                            // we made such as through app install filtering would now
10012                            // have allowed apps on the device which aren't compatible
10013                            // with it.  Better to just have the restriction here, be
10014                            // conservative, and create many fewer cases that can negatively
10015                            // impact the user experience.
10016                            final PackageSetting sysPs = mSettings
10017                                    .getDisabledSystemPkgLPr(pkg.packageName);
10018                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10019                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10020                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10021                                        allowed = true;
10022                                        break;
10023                                    }
10024                                }
10025                            }
10026                        } else {
10027                            allowed = true;
10028                        }
10029                        if (allowed) {
10030                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10031                                    SharedLibraryInfo.VERSION_UNDEFINED,
10032                                    SharedLibraryInfo.TYPE_DYNAMIC,
10033                                    pkg.packageName, pkg.mVersionCode)) {
10034                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10035                                        + name + " already exists; skipping");
10036                            }
10037                        } else {
10038                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10039                                    + name + " that is not declared on system image; skipping");
10040                        }
10041                    }
10042
10043                    if ((scanFlags & SCAN_BOOTING) == 0) {
10044                        // If we are not booting, we need to update any applications
10045                        // that are clients of our shared library.  If we are booting,
10046                        // this will all be done once the scan is complete.
10047                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10048                    }
10049                }
10050            }
10051        }
10052
10053        if ((scanFlags & SCAN_BOOTING) != 0) {
10054            // No apps can run during boot scan, so they don't need to be frozen
10055        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10056            // Caller asked to not kill app, so it's probably not frozen
10057        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10058            // Caller asked us to ignore frozen check for some reason; they
10059            // probably didn't know the package name
10060        } else {
10061            // We're doing major surgery on this package, so it better be frozen
10062            // right now to keep it from launching
10063            checkPackageFrozen(pkgName);
10064        }
10065
10066        // Also need to kill any apps that are dependent on the library.
10067        if (clientLibPkgs != null) {
10068            for (int i=0; i<clientLibPkgs.size(); i++) {
10069                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10070                killApplication(clientPkg.applicationInfo.packageName,
10071                        clientPkg.applicationInfo.uid, "update lib");
10072            }
10073        }
10074
10075        // writer
10076        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10077
10078        synchronized (mPackages) {
10079            // We don't expect installation to fail beyond this point
10080
10081            // Add the new setting to mSettings
10082            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10083            // Add the new setting to mPackages
10084            mPackages.put(pkg.applicationInfo.packageName, pkg);
10085            // Make sure we don't accidentally delete its data.
10086            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10087            while (iter.hasNext()) {
10088                PackageCleanItem item = iter.next();
10089                if (pkgName.equals(item.packageName)) {
10090                    iter.remove();
10091                }
10092            }
10093
10094            // Add the package's KeySets to the global KeySetManagerService
10095            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10096            ksms.addScannedPackageLPw(pkg);
10097
10098            int N = pkg.providers.size();
10099            StringBuilder r = null;
10100            int i;
10101            for (i=0; i<N; i++) {
10102                PackageParser.Provider p = pkg.providers.get(i);
10103                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10104                        p.info.processName);
10105                mProviders.addProvider(p);
10106                p.syncable = p.info.isSyncable;
10107                if (p.info.authority != null) {
10108                    String names[] = p.info.authority.split(";");
10109                    p.info.authority = null;
10110                    for (int j = 0; j < names.length; j++) {
10111                        if (j == 1 && p.syncable) {
10112                            // We only want the first authority for a provider to possibly be
10113                            // syncable, so if we already added this provider using a different
10114                            // authority clear the syncable flag. We copy the provider before
10115                            // changing it because the mProviders object contains a reference
10116                            // to a provider that we don't want to change.
10117                            // Only do this for the second authority since the resulting provider
10118                            // object can be the same for all future authorities for this provider.
10119                            p = new PackageParser.Provider(p);
10120                            p.syncable = false;
10121                        }
10122                        if (!mProvidersByAuthority.containsKey(names[j])) {
10123                            mProvidersByAuthority.put(names[j], p);
10124                            if (p.info.authority == null) {
10125                                p.info.authority = names[j];
10126                            } else {
10127                                p.info.authority = p.info.authority + ";" + names[j];
10128                            }
10129                            if (DEBUG_PACKAGE_SCANNING) {
10130                                if (chatty)
10131                                    Log.d(TAG, "Registered content provider: " + names[j]
10132                                            + ", className = " + p.info.name + ", isSyncable = "
10133                                            + p.info.isSyncable);
10134                            }
10135                        } else {
10136                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10137                            Slog.w(TAG, "Skipping provider name " + names[j] +
10138                                    " (in package " + pkg.applicationInfo.packageName +
10139                                    "): name already used by "
10140                                    + ((other != null && other.getComponentName() != null)
10141                                            ? other.getComponentName().getPackageName() : "?"));
10142                        }
10143                    }
10144                }
10145                if (chatty) {
10146                    if (r == null) {
10147                        r = new StringBuilder(256);
10148                    } else {
10149                        r.append(' ');
10150                    }
10151                    r.append(p.info.name);
10152                }
10153            }
10154            if (r != null) {
10155                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10156            }
10157
10158            N = pkg.services.size();
10159            r = null;
10160            for (i=0; i<N; i++) {
10161                PackageParser.Service s = pkg.services.get(i);
10162                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10163                        s.info.processName);
10164                mServices.addService(s);
10165                if (chatty) {
10166                    if (r == null) {
10167                        r = new StringBuilder(256);
10168                    } else {
10169                        r.append(' ');
10170                    }
10171                    r.append(s.info.name);
10172                }
10173            }
10174            if (r != null) {
10175                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10176            }
10177
10178            N = pkg.receivers.size();
10179            r = null;
10180            for (i=0; i<N; i++) {
10181                PackageParser.Activity a = pkg.receivers.get(i);
10182                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10183                        a.info.processName);
10184                mReceivers.addActivity(a, "receiver");
10185                if (chatty) {
10186                    if (r == null) {
10187                        r = new StringBuilder(256);
10188                    } else {
10189                        r.append(' ');
10190                    }
10191                    r.append(a.info.name);
10192                }
10193            }
10194            if (r != null) {
10195                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10196            }
10197
10198            N = pkg.activities.size();
10199            r = null;
10200            for (i=0; i<N; i++) {
10201                PackageParser.Activity a = pkg.activities.get(i);
10202                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10203                        a.info.processName);
10204                mActivities.addActivity(a, "activity");
10205                if (chatty) {
10206                    if (r == null) {
10207                        r = new StringBuilder(256);
10208                    } else {
10209                        r.append(' ');
10210                    }
10211                    r.append(a.info.name);
10212                }
10213            }
10214            if (r != null) {
10215                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10216            }
10217
10218            N = pkg.permissionGroups.size();
10219            r = null;
10220            for (i=0; i<N; i++) {
10221                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10222                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10223                final String curPackageName = cur == null ? null : cur.info.packageName;
10224                // Dont allow ephemeral apps to define new permission groups.
10225                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10226                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10227                            + pg.info.packageName
10228                            + " ignored: instant apps cannot define new permission groups.");
10229                    continue;
10230                }
10231                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10232                if (cur == null || isPackageUpdate) {
10233                    mPermissionGroups.put(pg.info.name, pg);
10234                    if (chatty) {
10235                        if (r == null) {
10236                            r = new StringBuilder(256);
10237                        } else {
10238                            r.append(' ');
10239                        }
10240                        if (isPackageUpdate) {
10241                            r.append("UPD:");
10242                        }
10243                        r.append(pg.info.name);
10244                    }
10245                } else {
10246                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10247                            + pg.info.packageName + " ignored: original from "
10248                            + cur.info.packageName);
10249                    if (chatty) {
10250                        if (r == null) {
10251                            r = new StringBuilder(256);
10252                        } else {
10253                            r.append(' ');
10254                        }
10255                        r.append("DUP:");
10256                        r.append(pg.info.name);
10257                    }
10258                }
10259            }
10260            if (r != null) {
10261                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10262            }
10263
10264            N = pkg.permissions.size();
10265            r = null;
10266            for (i=0; i<N; i++) {
10267                PackageParser.Permission p = pkg.permissions.get(i);
10268
10269                // Dont allow ephemeral apps to define new permissions.
10270                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10271                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10272                            + p.info.packageName
10273                            + " ignored: instant apps cannot define new permissions.");
10274                    continue;
10275                }
10276
10277                // Assume by default that we did not install this permission into the system.
10278                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10279
10280                // Now that permission groups have a special meaning, we ignore permission
10281                // groups for legacy apps to prevent unexpected behavior. In particular,
10282                // permissions for one app being granted to someone just becase they happen
10283                // to be in a group defined by another app (before this had no implications).
10284                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10285                    p.group = mPermissionGroups.get(p.info.group);
10286                    // Warn for a permission in an unknown group.
10287                    if (p.info.group != null && p.group == null) {
10288                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10289                                + p.info.packageName + " in an unknown group " + p.info.group);
10290                    }
10291                }
10292
10293                ArrayMap<String, BasePermission> permissionMap =
10294                        p.tree ? mSettings.mPermissionTrees
10295                                : mSettings.mPermissions;
10296                BasePermission bp = permissionMap.get(p.info.name);
10297
10298                // Allow system apps to redefine non-system permissions
10299                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10300                    final boolean currentOwnerIsSystem = (bp.perm != null
10301                            && isSystemApp(bp.perm.owner));
10302                    if (isSystemApp(p.owner)) {
10303                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10304                            // It's a built-in permission and no owner, take ownership now
10305                            bp.packageSetting = pkgSetting;
10306                            bp.perm = p;
10307                            bp.uid = pkg.applicationInfo.uid;
10308                            bp.sourcePackage = p.info.packageName;
10309                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10310                        } else if (!currentOwnerIsSystem) {
10311                            String msg = "New decl " + p.owner + " of permission  "
10312                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10313                            reportSettingsProblem(Log.WARN, msg);
10314                            bp = null;
10315                        }
10316                    }
10317                }
10318
10319                if (bp == null) {
10320                    bp = new BasePermission(p.info.name, p.info.packageName,
10321                            BasePermission.TYPE_NORMAL);
10322                    permissionMap.put(p.info.name, bp);
10323                }
10324
10325                if (bp.perm == null) {
10326                    if (bp.sourcePackage == null
10327                            || bp.sourcePackage.equals(p.info.packageName)) {
10328                        BasePermission tree = findPermissionTreeLP(p.info.name);
10329                        if (tree == null
10330                                || tree.sourcePackage.equals(p.info.packageName)) {
10331                            bp.packageSetting = pkgSetting;
10332                            bp.perm = p;
10333                            bp.uid = pkg.applicationInfo.uid;
10334                            bp.sourcePackage = p.info.packageName;
10335                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10336                            if (chatty) {
10337                                if (r == null) {
10338                                    r = new StringBuilder(256);
10339                                } else {
10340                                    r.append(' ');
10341                                }
10342                                r.append(p.info.name);
10343                            }
10344                        } else {
10345                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10346                                    + p.info.packageName + " ignored: base tree "
10347                                    + tree.name + " is from package "
10348                                    + tree.sourcePackage);
10349                        }
10350                    } else {
10351                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10352                                + p.info.packageName + " ignored: original from "
10353                                + bp.sourcePackage);
10354                    }
10355                } else if (chatty) {
10356                    if (r == null) {
10357                        r = new StringBuilder(256);
10358                    } else {
10359                        r.append(' ');
10360                    }
10361                    r.append("DUP:");
10362                    r.append(p.info.name);
10363                }
10364                if (bp.perm == p) {
10365                    bp.protectionLevel = p.info.protectionLevel;
10366                }
10367            }
10368
10369            if (r != null) {
10370                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10371            }
10372
10373            N = pkg.instrumentation.size();
10374            r = null;
10375            for (i=0; i<N; i++) {
10376                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10377                a.info.packageName = pkg.applicationInfo.packageName;
10378                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10379                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10380                a.info.splitNames = pkg.splitNames;
10381                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10382                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10383                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10384                a.info.dataDir = pkg.applicationInfo.dataDir;
10385                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10386                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10387                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10388                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10389                mInstrumentation.put(a.getComponentName(), a);
10390                if (chatty) {
10391                    if (r == null) {
10392                        r = new StringBuilder(256);
10393                    } else {
10394                        r.append(' ');
10395                    }
10396                    r.append(a.info.name);
10397                }
10398            }
10399            if (r != null) {
10400                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10401            }
10402
10403            if (pkg.protectedBroadcasts != null) {
10404                N = pkg.protectedBroadcasts.size();
10405                for (i=0; i<N; i++) {
10406                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10407                }
10408            }
10409        }
10410
10411        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10412    }
10413
10414    /**
10415     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10416     * is derived purely on the basis of the contents of {@code scanFile} and
10417     * {@code cpuAbiOverride}.
10418     *
10419     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10420     */
10421    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10422                                 String cpuAbiOverride, boolean extractLibs,
10423                                 File appLib32InstallDir)
10424            throws PackageManagerException {
10425        // Give ourselves some initial paths; we'll come back for another
10426        // pass once we've determined ABI below.
10427        setNativeLibraryPaths(pkg, appLib32InstallDir);
10428
10429        // We would never need to extract libs for forward-locked and external packages,
10430        // since the container service will do it for us. We shouldn't attempt to
10431        // extract libs from system app when it was not updated.
10432        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10433                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10434            extractLibs = false;
10435        }
10436
10437        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10438        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10439
10440        NativeLibraryHelper.Handle handle = null;
10441        try {
10442            handle = NativeLibraryHelper.Handle.create(pkg);
10443            // TODO(multiArch): This can be null for apps that didn't go through the
10444            // usual installation process. We can calculate it again, like we
10445            // do during install time.
10446            //
10447            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10448            // unnecessary.
10449            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10450
10451            // Null out the abis so that they can be recalculated.
10452            pkg.applicationInfo.primaryCpuAbi = null;
10453            pkg.applicationInfo.secondaryCpuAbi = null;
10454            if (isMultiArch(pkg.applicationInfo)) {
10455                // Warn if we've set an abiOverride for multi-lib packages..
10456                // By definition, we need to copy both 32 and 64 bit libraries for
10457                // such packages.
10458                if (pkg.cpuAbiOverride != null
10459                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10460                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10461                }
10462
10463                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10464                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10465                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10466                    if (extractLibs) {
10467                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10468                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10469                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10470                                useIsaSpecificSubdirs);
10471                    } else {
10472                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10473                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10474                    }
10475                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10476                }
10477
10478                maybeThrowExceptionForMultiArchCopy(
10479                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10480
10481                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10482                    if (extractLibs) {
10483                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10484                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10485                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10486                                useIsaSpecificSubdirs);
10487                    } else {
10488                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10489                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10490                    }
10491                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10492                }
10493
10494                maybeThrowExceptionForMultiArchCopy(
10495                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10496
10497                if (abi64 >= 0) {
10498                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10499                }
10500
10501                if (abi32 >= 0) {
10502                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10503                    if (abi64 >= 0) {
10504                        if (pkg.use32bitAbi) {
10505                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10506                            pkg.applicationInfo.primaryCpuAbi = abi;
10507                        } else {
10508                            pkg.applicationInfo.secondaryCpuAbi = abi;
10509                        }
10510                    } else {
10511                        pkg.applicationInfo.primaryCpuAbi = abi;
10512                    }
10513                }
10514
10515            } else {
10516                String[] abiList = (cpuAbiOverride != null) ?
10517                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10518
10519                // Enable gross and lame hacks for apps that are built with old
10520                // SDK tools. We must scan their APKs for renderscript bitcode and
10521                // not launch them if it's present. Don't bother checking on devices
10522                // that don't have 64 bit support.
10523                boolean needsRenderScriptOverride = false;
10524                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10525                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10526                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10527                    needsRenderScriptOverride = true;
10528                }
10529
10530                final int copyRet;
10531                if (extractLibs) {
10532                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10533                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10534                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10535                } else {
10536                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10537                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10538                }
10539                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10540
10541                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10542                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10543                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10544                }
10545
10546                if (copyRet >= 0) {
10547                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10548                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10549                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10550                } else if (needsRenderScriptOverride) {
10551                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10552                }
10553            }
10554        } catch (IOException ioe) {
10555            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10556        } finally {
10557            IoUtils.closeQuietly(handle);
10558        }
10559
10560        // Now that we've calculated the ABIs and determined if it's an internal app,
10561        // we will go ahead and populate the nativeLibraryPath.
10562        setNativeLibraryPaths(pkg, appLib32InstallDir);
10563    }
10564
10565    /**
10566     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10567     * i.e, so that all packages can be run inside a single process if required.
10568     *
10569     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10570     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10571     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10572     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10573     * updating a package that belongs to a shared user.
10574     *
10575     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10576     * adds unnecessary complexity.
10577     */
10578    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10579            PackageParser.Package scannedPackage) {
10580        String requiredInstructionSet = null;
10581        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10582            requiredInstructionSet = VMRuntime.getInstructionSet(
10583                     scannedPackage.applicationInfo.primaryCpuAbi);
10584        }
10585
10586        PackageSetting requirer = null;
10587        for (PackageSetting ps : packagesForUser) {
10588            // If packagesForUser contains scannedPackage, we skip it. This will happen
10589            // when scannedPackage is an update of an existing package. Without this check,
10590            // we will never be able to change the ABI of any package belonging to a shared
10591            // user, even if it's compatible with other packages.
10592            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10593                if (ps.primaryCpuAbiString == null) {
10594                    continue;
10595                }
10596
10597                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10598                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10599                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10600                    // this but there's not much we can do.
10601                    String errorMessage = "Instruction set mismatch, "
10602                            + ((requirer == null) ? "[caller]" : requirer)
10603                            + " requires " + requiredInstructionSet + " whereas " + ps
10604                            + " requires " + instructionSet;
10605                    Slog.w(TAG, errorMessage);
10606                }
10607
10608                if (requiredInstructionSet == null) {
10609                    requiredInstructionSet = instructionSet;
10610                    requirer = ps;
10611                }
10612            }
10613        }
10614
10615        if (requiredInstructionSet != null) {
10616            String adjustedAbi;
10617            if (requirer != null) {
10618                // requirer != null implies that either scannedPackage was null or that scannedPackage
10619                // did not require an ABI, in which case we have to adjust scannedPackage to match
10620                // the ABI of the set (which is the same as requirer's ABI)
10621                adjustedAbi = requirer.primaryCpuAbiString;
10622                if (scannedPackage != null) {
10623                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10624                }
10625            } else {
10626                // requirer == null implies that we're updating all ABIs in the set to
10627                // match scannedPackage.
10628                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10629            }
10630
10631            for (PackageSetting ps : packagesForUser) {
10632                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10633                    if (ps.primaryCpuAbiString != null) {
10634                        continue;
10635                    }
10636
10637                    ps.primaryCpuAbiString = adjustedAbi;
10638                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10639                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10640                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10641                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10642                                + " (requirer="
10643                                + (requirer != null ? requirer.pkg : "null")
10644                                + ", scannedPackage="
10645                                + (scannedPackage != null ? scannedPackage : "null")
10646                                + ")");
10647                        try {
10648                            mInstaller.rmdex(ps.codePathString,
10649                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10650                        } catch (InstallerException ignored) {
10651                        }
10652                    }
10653                }
10654            }
10655        }
10656    }
10657
10658    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10659        synchronized (mPackages) {
10660            mResolverReplaced = true;
10661            // Set up information for custom user intent resolution activity.
10662            mResolveActivity.applicationInfo = pkg.applicationInfo;
10663            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10664            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10665            mResolveActivity.processName = pkg.applicationInfo.packageName;
10666            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10667            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10668                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10669            mResolveActivity.theme = 0;
10670            mResolveActivity.exported = true;
10671            mResolveActivity.enabled = true;
10672            mResolveInfo.activityInfo = mResolveActivity;
10673            mResolveInfo.priority = 0;
10674            mResolveInfo.preferredOrder = 0;
10675            mResolveInfo.match = 0;
10676            mResolveComponentName = mCustomResolverComponentName;
10677            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10678                    mResolveComponentName);
10679        }
10680    }
10681
10682    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10683        if (installerActivity == null) {
10684            if (DEBUG_EPHEMERAL) {
10685                Slog.d(TAG, "Clear ephemeral installer activity");
10686            }
10687            mInstantAppInstallerActivity = null;
10688            return;
10689        }
10690
10691        if (DEBUG_EPHEMERAL) {
10692            Slog.d(TAG, "Set ephemeral installer activity: "
10693                    + installerActivity.getComponentName());
10694        }
10695        // Set up information for ephemeral installer activity
10696        mInstantAppInstallerActivity = installerActivity;
10697        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10698                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10699        mInstantAppInstallerActivity.exported = true;
10700        mInstantAppInstallerActivity.enabled = true;
10701        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10702        mInstantAppInstallerInfo.priority = 0;
10703        mInstantAppInstallerInfo.preferredOrder = 1;
10704        mInstantAppInstallerInfo.isDefault = true;
10705        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10706                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10707    }
10708
10709    private static String calculateBundledApkRoot(final String codePathString) {
10710        final File codePath = new File(codePathString);
10711        final File codeRoot;
10712        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10713            codeRoot = Environment.getRootDirectory();
10714        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10715            codeRoot = Environment.getOemDirectory();
10716        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10717            codeRoot = Environment.getVendorDirectory();
10718        } else {
10719            // Unrecognized code path; take its top real segment as the apk root:
10720            // e.g. /something/app/blah.apk => /something
10721            try {
10722                File f = codePath.getCanonicalFile();
10723                File parent = f.getParentFile();    // non-null because codePath is a file
10724                File tmp;
10725                while ((tmp = parent.getParentFile()) != null) {
10726                    f = parent;
10727                    parent = tmp;
10728                }
10729                codeRoot = f;
10730                Slog.w(TAG, "Unrecognized code path "
10731                        + codePath + " - using " + codeRoot);
10732            } catch (IOException e) {
10733                // Can't canonicalize the code path -- shenanigans?
10734                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10735                return Environment.getRootDirectory().getPath();
10736            }
10737        }
10738        return codeRoot.getPath();
10739    }
10740
10741    /**
10742     * Derive and set the location of native libraries for the given package,
10743     * which varies depending on where and how the package was installed.
10744     */
10745    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10746        final ApplicationInfo info = pkg.applicationInfo;
10747        final String codePath = pkg.codePath;
10748        final File codeFile = new File(codePath);
10749        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10750        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10751
10752        info.nativeLibraryRootDir = null;
10753        info.nativeLibraryRootRequiresIsa = false;
10754        info.nativeLibraryDir = null;
10755        info.secondaryNativeLibraryDir = null;
10756
10757        if (isApkFile(codeFile)) {
10758            // Monolithic install
10759            if (bundledApp) {
10760                // If "/system/lib64/apkname" exists, assume that is the per-package
10761                // native library directory to use; otherwise use "/system/lib/apkname".
10762                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10763                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10764                        getPrimaryInstructionSet(info));
10765
10766                // This is a bundled system app so choose the path based on the ABI.
10767                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10768                // is just the default path.
10769                final String apkName = deriveCodePathName(codePath);
10770                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10771                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10772                        apkName).getAbsolutePath();
10773
10774                if (info.secondaryCpuAbi != null) {
10775                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10776                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10777                            secondaryLibDir, apkName).getAbsolutePath();
10778                }
10779            } else if (asecApp) {
10780                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10781                        .getAbsolutePath();
10782            } else {
10783                final String apkName = deriveCodePathName(codePath);
10784                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10785                        .getAbsolutePath();
10786            }
10787
10788            info.nativeLibraryRootRequiresIsa = false;
10789            info.nativeLibraryDir = info.nativeLibraryRootDir;
10790        } else {
10791            // Cluster install
10792            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10793            info.nativeLibraryRootRequiresIsa = true;
10794
10795            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10796                    getPrimaryInstructionSet(info)).getAbsolutePath();
10797
10798            if (info.secondaryCpuAbi != null) {
10799                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10800                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10801            }
10802        }
10803    }
10804
10805    /**
10806     * Calculate the abis and roots for a bundled app. These can uniquely
10807     * be determined from the contents of the system partition, i.e whether
10808     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10809     * of this information, and instead assume that the system was built
10810     * sensibly.
10811     */
10812    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10813                                           PackageSetting pkgSetting) {
10814        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10815
10816        // If "/system/lib64/apkname" exists, assume that is the per-package
10817        // native library directory to use; otherwise use "/system/lib/apkname".
10818        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10819        setBundledAppAbi(pkg, apkRoot, apkName);
10820        // pkgSetting might be null during rescan following uninstall of updates
10821        // to a bundled app, so accommodate that possibility.  The settings in
10822        // that case will be established later from the parsed package.
10823        //
10824        // If the settings aren't null, sync them up with what we've just derived.
10825        // note that apkRoot isn't stored in the package settings.
10826        if (pkgSetting != null) {
10827            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10828            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10829        }
10830    }
10831
10832    /**
10833     * Deduces the ABI of a bundled app and sets the relevant fields on the
10834     * parsed pkg object.
10835     *
10836     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10837     *        under which system libraries are installed.
10838     * @param apkName the name of the installed package.
10839     */
10840    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10841        final File codeFile = new File(pkg.codePath);
10842
10843        final boolean has64BitLibs;
10844        final boolean has32BitLibs;
10845        if (isApkFile(codeFile)) {
10846            // Monolithic install
10847            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10848            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10849        } else {
10850            // Cluster install
10851            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10852            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10853                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10854                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10855                has64BitLibs = (new File(rootDir, isa)).exists();
10856            } else {
10857                has64BitLibs = false;
10858            }
10859            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10860                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10861                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10862                has32BitLibs = (new File(rootDir, isa)).exists();
10863            } else {
10864                has32BitLibs = false;
10865            }
10866        }
10867
10868        if (has64BitLibs && !has32BitLibs) {
10869            // The package has 64 bit libs, but not 32 bit libs. Its primary
10870            // ABI should be 64 bit. We can safely assume here that the bundled
10871            // native libraries correspond to the most preferred ABI in the list.
10872
10873            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10874            pkg.applicationInfo.secondaryCpuAbi = null;
10875        } else if (has32BitLibs && !has64BitLibs) {
10876            // The package has 32 bit libs but not 64 bit libs. Its primary
10877            // ABI should be 32 bit.
10878
10879            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10880            pkg.applicationInfo.secondaryCpuAbi = null;
10881        } else if (has32BitLibs && has64BitLibs) {
10882            // The application has both 64 and 32 bit bundled libraries. We check
10883            // here that the app declares multiArch support, and warn if it doesn't.
10884            //
10885            // We will be lenient here and record both ABIs. The primary will be the
10886            // ABI that's higher on the list, i.e, a device that's configured to prefer
10887            // 64 bit apps will see a 64 bit primary ABI,
10888
10889            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10890                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10891            }
10892
10893            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10894                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10895                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10896            } else {
10897                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10898                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10899            }
10900        } else {
10901            pkg.applicationInfo.primaryCpuAbi = null;
10902            pkg.applicationInfo.secondaryCpuAbi = null;
10903        }
10904    }
10905
10906    private void killApplication(String pkgName, int appId, String reason) {
10907        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10908    }
10909
10910    private void killApplication(String pkgName, int appId, int userId, String reason) {
10911        // Request the ActivityManager to kill the process(only for existing packages)
10912        // so that we do not end up in a confused state while the user is still using the older
10913        // version of the application while the new one gets installed.
10914        final long token = Binder.clearCallingIdentity();
10915        try {
10916            IActivityManager am = ActivityManager.getService();
10917            if (am != null) {
10918                try {
10919                    am.killApplication(pkgName, appId, userId, reason);
10920                } catch (RemoteException e) {
10921                }
10922            }
10923        } finally {
10924            Binder.restoreCallingIdentity(token);
10925        }
10926    }
10927
10928    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10929        // Remove the parent package setting
10930        PackageSetting ps = (PackageSetting) pkg.mExtras;
10931        if (ps != null) {
10932            removePackageLI(ps, chatty);
10933        }
10934        // Remove the child package setting
10935        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10936        for (int i = 0; i < childCount; i++) {
10937            PackageParser.Package childPkg = pkg.childPackages.get(i);
10938            ps = (PackageSetting) childPkg.mExtras;
10939            if (ps != null) {
10940                removePackageLI(ps, chatty);
10941            }
10942        }
10943    }
10944
10945    void removePackageLI(PackageSetting ps, boolean chatty) {
10946        if (DEBUG_INSTALL) {
10947            if (chatty)
10948                Log.d(TAG, "Removing package " + ps.name);
10949        }
10950
10951        // writer
10952        synchronized (mPackages) {
10953            mPackages.remove(ps.name);
10954            final PackageParser.Package pkg = ps.pkg;
10955            if (pkg != null) {
10956                cleanPackageDataStructuresLILPw(pkg, chatty);
10957            }
10958        }
10959    }
10960
10961    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10962        if (DEBUG_INSTALL) {
10963            if (chatty)
10964                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10965        }
10966
10967        // writer
10968        synchronized (mPackages) {
10969            // Remove the parent package
10970            mPackages.remove(pkg.applicationInfo.packageName);
10971            cleanPackageDataStructuresLILPw(pkg, chatty);
10972
10973            // Remove the child packages
10974            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10975            for (int i = 0; i < childCount; i++) {
10976                PackageParser.Package childPkg = pkg.childPackages.get(i);
10977                mPackages.remove(childPkg.applicationInfo.packageName);
10978                cleanPackageDataStructuresLILPw(childPkg, chatty);
10979            }
10980        }
10981    }
10982
10983    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10984        int N = pkg.providers.size();
10985        StringBuilder r = null;
10986        int i;
10987        for (i=0; i<N; i++) {
10988            PackageParser.Provider p = pkg.providers.get(i);
10989            mProviders.removeProvider(p);
10990            if (p.info.authority == null) {
10991
10992                /* There was another ContentProvider with this authority when
10993                 * this app was installed so this authority is null,
10994                 * Ignore it as we don't have to unregister the provider.
10995                 */
10996                continue;
10997            }
10998            String names[] = p.info.authority.split(";");
10999            for (int j = 0; j < names.length; j++) {
11000                if (mProvidersByAuthority.get(names[j]) == p) {
11001                    mProvidersByAuthority.remove(names[j]);
11002                    if (DEBUG_REMOVE) {
11003                        if (chatty)
11004                            Log.d(TAG, "Unregistered content provider: " + names[j]
11005                                    + ", className = " + p.info.name + ", isSyncable = "
11006                                    + p.info.isSyncable);
11007                    }
11008                }
11009            }
11010            if (DEBUG_REMOVE && chatty) {
11011                if (r == null) {
11012                    r = new StringBuilder(256);
11013                } else {
11014                    r.append(' ');
11015                }
11016                r.append(p.info.name);
11017            }
11018        }
11019        if (r != null) {
11020            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11021        }
11022
11023        N = pkg.services.size();
11024        r = null;
11025        for (i=0; i<N; i++) {
11026            PackageParser.Service s = pkg.services.get(i);
11027            mServices.removeService(s);
11028            if (chatty) {
11029                if (r == null) {
11030                    r = new StringBuilder(256);
11031                } else {
11032                    r.append(' ');
11033                }
11034                r.append(s.info.name);
11035            }
11036        }
11037        if (r != null) {
11038            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11039        }
11040
11041        N = pkg.receivers.size();
11042        r = null;
11043        for (i=0; i<N; i++) {
11044            PackageParser.Activity a = pkg.receivers.get(i);
11045            mReceivers.removeActivity(a, "receiver");
11046            if (DEBUG_REMOVE && chatty) {
11047                if (r == null) {
11048                    r = new StringBuilder(256);
11049                } else {
11050                    r.append(' ');
11051                }
11052                r.append(a.info.name);
11053            }
11054        }
11055        if (r != null) {
11056            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11057        }
11058
11059        N = pkg.activities.size();
11060        r = null;
11061        for (i=0; i<N; i++) {
11062            PackageParser.Activity a = pkg.activities.get(i);
11063            mActivities.removeActivity(a, "activity");
11064            if (DEBUG_REMOVE && chatty) {
11065                if (r == null) {
11066                    r = new StringBuilder(256);
11067                } else {
11068                    r.append(' ');
11069                }
11070                r.append(a.info.name);
11071            }
11072        }
11073        if (r != null) {
11074            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11075        }
11076
11077        N = pkg.permissions.size();
11078        r = null;
11079        for (i=0; i<N; i++) {
11080            PackageParser.Permission p = pkg.permissions.get(i);
11081            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11082            if (bp == null) {
11083                bp = mSettings.mPermissionTrees.get(p.info.name);
11084            }
11085            if (bp != null && bp.perm == p) {
11086                bp.perm = null;
11087                if (DEBUG_REMOVE && chatty) {
11088                    if (r == null) {
11089                        r = new StringBuilder(256);
11090                    } else {
11091                        r.append(' ');
11092                    }
11093                    r.append(p.info.name);
11094                }
11095            }
11096            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11097                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11098                if (appOpPkgs != null) {
11099                    appOpPkgs.remove(pkg.packageName);
11100                }
11101            }
11102        }
11103        if (r != null) {
11104            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11105        }
11106
11107        N = pkg.requestedPermissions.size();
11108        r = null;
11109        for (i=0; i<N; i++) {
11110            String perm = pkg.requestedPermissions.get(i);
11111            BasePermission bp = mSettings.mPermissions.get(perm);
11112            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11113                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11114                if (appOpPkgs != null) {
11115                    appOpPkgs.remove(pkg.packageName);
11116                    if (appOpPkgs.isEmpty()) {
11117                        mAppOpPermissionPackages.remove(perm);
11118                    }
11119                }
11120            }
11121        }
11122        if (r != null) {
11123            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11124        }
11125
11126        N = pkg.instrumentation.size();
11127        r = null;
11128        for (i=0; i<N; i++) {
11129            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11130            mInstrumentation.remove(a.getComponentName());
11131            if (DEBUG_REMOVE && chatty) {
11132                if (r == null) {
11133                    r = new StringBuilder(256);
11134                } else {
11135                    r.append(' ');
11136                }
11137                r.append(a.info.name);
11138            }
11139        }
11140        if (r != null) {
11141            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11142        }
11143
11144        r = null;
11145        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11146            // Only system apps can hold shared libraries.
11147            if (pkg.libraryNames != null) {
11148                for (i = 0; i < pkg.libraryNames.size(); i++) {
11149                    String name = pkg.libraryNames.get(i);
11150                    if (removeSharedLibraryLPw(name, 0)) {
11151                        if (DEBUG_REMOVE && chatty) {
11152                            if (r == null) {
11153                                r = new StringBuilder(256);
11154                            } else {
11155                                r.append(' ');
11156                            }
11157                            r.append(name);
11158                        }
11159                    }
11160                }
11161            }
11162        }
11163
11164        r = null;
11165
11166        // Any package can hold static shared libraries.
11167        if (pkg.staticSharedLibName != null) {
11168            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11169                if (DEBUG_REMOVE && chatty) {
11170                    if (r == null) {
11171                        r = new StringBuilder(256);
11172                    } else {
11173                        r.append(' ');
11174                    }
11175                    r.append(pkg.staticSharedLibName);
11176                }
11177            }
11178        }
11179
11180        if (r != null) {
11181            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11182        }
11183    }
11184
11185    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11186        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11187            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11188                return true;
11189            }
11190        }
11191        return false;
11192    }
11193
11194    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11195    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11196    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11197
11198    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11199        // Update the parent permissions
11200        updatePermissionsLPw(pkg.packageName, pkg, flags);
11201        // Update the child permissions
11202        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11203        for (int i = 0; i < childCount; i++) {
11204            PackageParser.Package childPkg = pkg.childPackages.get(i);
11205            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11206        }
11207    }
11208
11209    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11210            int flags) {
11211        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11212        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11213    }
11214
11215    private void updatePermissionsLPw(String changingPkg,
11216            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11217        // Make sure there are no dangling permission trees.
11218        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11219        while (it.hasNext()) {
11220            final BasePermission bp = it.next();
11221            if (bp.packageSetting == null) {
11222                // We may not yet have parsed the package, so just see if
11223                // we still know about its settings.
11224                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11225            }
11226            if (bp.packageSetting == null) {
11227                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11228                        + " from package " + bp.sourcePackage);
11229                it.remove();
11230            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11231                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11232                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11233                            + " from package " + bp.sourcePackage);
11234                    flags |= UPDATE_PERMISSIONS_ALL;
11235                    it.remove();
11236                }
11237            }
11238        }
11239
11240        // Make sure all dynamic permissions have been assigned to a package,
11241        // and make sure there are no dangling permissions.
11242        it = mSettings.mPermissions.values().iterator();
11243        while (it.hasNext()) {
11244            final BasePermission bp = it.next();
11245            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11246                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11247                        + bp.name + " pkg=" + bp.sourcePackage
11248                        + " info=" + bp.pendingInfo);
11249                if (bp.packageSetting == null && bp.pendingInfo != null) {
11250                    final BasePermission tree = findPermissionTreeLP(bp.name);
11251                    if (tree != null && tree.perm != null) {
11252                        bp.packageSetting = tree.packageSetting;
11253                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11254                                new PermissionInfo(bp.pendingInfo));
11255                        bp.perm.info.packageName = tree.perm.info.packageName;
11256                        bp.perm.info.name = bp.name;
11257                        bp.uid = tree.uid;
11258                    }
11259                }
11260            }
11261            if (bp.packageSetting == null) {
11262                // We may not yet have parsed the package, so just see if
11263                // we still know about its settings.
11264                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11265            }
11266            if (bp.packageSetting == null) {
11267                Slog.w(TAG, "Removing dangling permission: " + bp.name
11268                        + " from package " + bp.sourcePackage);
11269                it.remove();
11270            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11271                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11272                    Slog.i(TAG, "Removing old permission: " + bp.name
11273                            + " from package " + bp.sourcePackage);
11274                    flags |= UPDATE_PERMISSIONS_ALL;
11275                    it.remove();
11276                }
11277            }
11278        }
11279
11280        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11281        // Now update the permissions for all packages, in particular
11282        // replace the granted permissions of the system packages.
11283        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11284            for (PackageParser.Package pkg : mPackages.values()) {
11285                if (pkg != pkgInfo) {
11286                    // Only replace for packages on requested volume
11287                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11288                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11289                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11290                    grantPermissionsLPw(pkg, replace, changingPkg);
11291                }
11292            }
11293        }
11294
11295        if (pkgInfo != null) {
11296            // Only replace for packages on requested volume
11297            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11298            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11299                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11300            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11301        }
11302        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11303    }
11304
11305    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11306            String packageOfInterest) {
11307        // IMPORTANT: There are two types of permissions: install and runtime.
11308        // Install time permissions are granted when the app is installed to
11309        // all device users and users added in the future. Runtime permissions
11310        // are granted at runtime explicitly to specific users. Normal and signature
11311        // protected permissions are install time permissions. Dangerous permissions
11312        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11313        // otherwise they are runtime permissions. This function does not manage
11314        // runtime permissions except for the case an app targeting Lollipop MR1
11315        // being upgraded to target a newer SDK, in which case dangerous permissions
11316        // are transformed from install time to runtime ones.
11317
11318        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11319        if (ps == null) {
11320            return;
11321        }
11322
11323        PermissionsState permissionsState = ps.getPermissionsState();
11324        PermissionsState origPermissions = permissionsState;
11325
11326        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11327
11328        boolean runtimePermissionsRevoked = false;
11329        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11330
11331        boolean changedInstallPermission = false;
11332
11333        if (replace) {
11334            ps.installPermissionsFixed = false;
11335            if (!ps.isSharedUser()) {
11336                origPermissions = new PermissionsState(permissionsState);
11337                permissionsState.reset();
11338            } else {
11339                // We need to know only about runtime permission changes since the
11340                // calling code always writes the install permissions state but
11341                // the runtime ones are written only if changed. The only cases of
11342                // changed runtime permissions here are promotion of an install to
11343                // runtime and revocation of a runtime from a shared user.
11344                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11345                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11346                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11347                    runtimePermissionsRevoked = true;
11348                }
11349            }
11350        }
11351
11352        permissionsState.setGlobalGids(mGlobalGids);
11353
11354        final int N = pkg.requestedPermissions.size();
11355        for (int i=0; i<N; i++) {
11356            final String name = pkg.requestedPermissions.get(i);
11357            final BasePermission bp = mSettings.mPermissions.get(name);
11358
11359            if (DEBUG_INSTALL) {
11360                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11361            }
11362
11363            if (bp == null || bp.packageSetting == null) {
11364                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11365                    Slog.w(TAG, "Unknown permission " + name
11366                            + " in package " + pkg.packageName);
11367                }
11368                continue;
11369            }
11370
11371
11372            // Limit ephemeral apps to ephemeral allowed permissions.
11373            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11374                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11375                        + pkg.packageName);
11376                continue;
11377            }
11378
11379            final String perm = bp.name;
11380            boolean allowedSig = false;
11381            int grant = GRANT_DENIED;
11382
11383            // Keep track of app op permissions.
11384            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11385                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11386                if (pkgs == null) {
11387                    pkgs = new ArraySet<>();
11388                    mAppOpPermissionPackages.put(bp.name, pkgs);
11389                }
11390                pkgs.add(pkg.packageName);
11391            }
11392
11393            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11394            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11395                    >= Build.VERSION_CODES.M;
11396            switch (level) {
11397                case PermissionInfo.PROTECTION_NORMAL: {
11398                    // For all apps normal permissions are install time ones.
11399                    grant = GRANT_INSTALL;
11400                } break;
11401
11402                case PermissionInfo.PROTECTION_DANGEROUS: {
11403                    // If a permission review is required for legacy apps we represent
11404                    // their permissions as always granted runtime ones since we need
11405                    // to keep the review required permission flag per user while an
11406                    // install permission's state is shared across all users.
11407                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11408                        // For legacy apps dangerous permissions are install time ones.
11409                        grant = GRANT_INSTALL;
11410                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11411                        // For legacy apps that became modern, install becomes runtime.
11412                        grant = GRANT_UPGRADE;
11413                    } else if (mPromoteSystemApps
11414                            && isSystemApp(ps)
11415                            && mExistingSystemPackages.contains(ps.name)) {
11416                        // For legacy system apps, install becomes runtime.
11417                        // We cannot check hasInstallPermission() for system apps since those
11418                        // permissions were granted implicitly and not persisted pre-M.
11419                        grant = GRANT_UPGRADE;
11420                    } else {
11421                        // For modern apps keep runtime permissions unchanged.
11422                        grant = GRANT_RUNTIME;
11423                    }
11424                } break;
11425
11426                case PermissionInfo.PROTECTION_SIGNATURE: {
11427                    // For all apps signature permissions are install time ones.
11428                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11429                    if (allowedSig) {
11430                        grant = GRANT_INSTALL;
11431                    }
11432                } break;
11433            }
11434
11435            if (DEBUG_INSTALL) {
11436                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11437            }
11438
11439            if (grant != GRANT_DENIED) {
11440                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11441                    // If this is an existing, non-system package, then
11442                    // we can't add any new permissions to it.
11443                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11444                        // Except...  if this is a permission that was added
11445                        // to the platform (note: need to only do this when
11446                        // updating the platform).
11447                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11448                            grant = GRANT_DENIED;
11449                        }
11450                    }
11451                }
11452
11453                switch (grant) {
11454                    case GRANT_INSTALL: {
11455                        // Revoke this as runtime permission to handle the case of
11456                        // a runtime permission being downgraded to an install one.
11457                        // Also in permission review mode we keep dangerous permissions
11458                        // for legacy apps
11459                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11460                            if (origPermissions.getRuntimePermissionState(
11461                                    bp.name, userId) != null) {
11462                                // Revoke the runtime permission and clear the flags.
11463                                origPermissions.revokeRuntimePermission(bp, userId);
11464                                origPermissions.updatePermissionFlags(bp, userId,
11465                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11466                                // If we revoked a permission permission, we have to write.
11467                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11468                                        changedRuntimePermissionUserIds, userId);
11469                            }
11470                        }
11471                        // Grant an install permission.
11472                        if (permissionsState.grantInstallPermission(bp) !=
11473                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11474                            changedInstallPermission = true;
11475                        }
11476                    } break;
11477
11478                    case GRANT_RUNTIME: {
11479                        // Grant previously granted runtime permissions.
11480                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11481                            PermissionState permissionState = origPermissions
11482                                    .getRuntimePermissionState(bp.name, userId);
11483                            int flags = permissionState != null
11484                                    ? permissionState.getFlags() : 0;
11485                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11486                                // Don't propagate the permission in a permission review mode if
11487                                // the former was revoked, i.e. marked to not propagate on upgrade.
11488                                // Note that in a permission review mode install permissions are
11489                                // represented as constantly granted runtime ones since we need to
11490                                // keep a per user state associated with the permission. Also the
11491                                // revoke on upgrade flag is no longer applicable and is reset.
11492                                final boolean revokeOnUpgrade = (flags & PackageManager
11493                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11494                                if (revokeOnUpgrade) {
11495                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11496                                    // Since we changed the flags, we have to write.
11497                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11498                                            changedRuntimePermissionUserIds, userId);
11499                                }
11500                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11501                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11502                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11503                                        // If we cannot put the permission as it was,
11504                                        // we have to write.
11505                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11506                                                changedRuntimePermissionUserIds, userId);
11507                                    }
11508                                }
11509
11510                                // If the app supports runtime permissions no need for a review.
11511                                if (mPermissionReviewRequired
11512                                        && appSupportsRuntimePermissions
11513                                        && (flags & PackageManager
11514                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11515                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11516                                    // Since we changed the flags, we have to write.
11517                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11518                                            changedRuntimePermissionUserIds, userId);
11519                                }
11520                            } else if (mPermissionReviewRequired
11521                                    && !appSupportsRuntimePermissions) {
11522                                // For legacy apps that need a permission review, every new
11523                                // runtime permission is granted but it is pending a review.
11524                                // We also need to review only platform defined runtime
11525                                // permissions as these are the only ones the platform knows
11526                                // how to disable the API to simulate revocation as legacy
11527                                // apps don't expect to run with revoked permissions.
11528                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11529                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11530                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11531                                        // We changed the flags, hence have to write.
11532                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11533                                                changedRuntimePermissionUserIds, userId);
11534                                    }
11535                                }
11536                                if (permissionsState.grantRuntimePermission(bp, userId)
11537                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11538                                    // We changed the permission, hence have to write.
11539                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11540                                            changedRuntimePermissionUserIds, userId);
11541                                }
11542                            }
11543                            // Propagate the permission flags.
11544                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11545                        }
11546                    } break;
11547
11548                    case GRANT_UPGRADE: {
11549                        // Grant runtime permissions for a previously held install permission.
11550                        PermissionState permissionState = origPermissions
11551                                .getInstallPermissionState(bp.name);
11552                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11553
11554                        if (origPermissions.revokeInstallPermission(bp)
11555                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11556                            // We will be transferring the permission flags, so clear them.
11557                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11558                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11559                            changedInstallPermission = true;
11560                        }
11561
11562                        // If the permission is not to be promoted to runtime we ignore it and
11563                        // also its other flags as they are not applicable to install permissions.
11564                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11565                            for (int userId : currentUserIds) {
11566                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11567                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11568                                    // Transfer the permission flags.
11569                                    permissionsState.updatePermissionFlags(bp, userId,
11570                                            flags, flags);
11571                                    // If we granted the permission, we have to write.
11572                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11573                                            changedRuntimePermissionUserIds, userId);
11574                                }
11575                            }
11576                        }
11577                    } break;
11578
11579                    default: {
11580                        if (packageOfInterest == null
11581                                || packageOfInterest.equals(pkg.packageName)) {
11582                            Slog.w(TAG, "Not granting permission " + perm
11583                                    + " to package " + pkg.packageName
11584                                    + " because it was previously installed without");
11585                        }
11586                    } break;
11587                }
11588            } else {
11589                if (permissionsState.revokeInstallPermission(bp) !=
11590                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11591                    // Also drop the permission flags.
11592                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11593                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11594                    changedInstallPermission = true;
11595                    Slog.i(TAG, "Un-granting permission " + perm
11596                            + " from package " + pkg.packageName
11597                            + " (protectionLevel=" + bp.protectionLevel
11598                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11599                            + ")");
11600                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11601                    // Don't print warning for app op permissions, since it is fine for them
11602                    // not to be granted, there is a UI for the user to decide.
11603                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11604                        Slog.w(TAG, "Not granting permission " + perm
11605                                + " to package " + pkg.packageName
11606                                + " (protectionLevel=" + bp.protectionLevel
11607                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11608                                + ")");
11609                    }
11610                }
11611            }
11612        }
11613
11614        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11615                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11616            // This is the first that we have heard about this package, so the
11617            // permissions we have now selected are fixed until explicitly
11618            // changed.
11619            ps.installPermissionsFixed = true;
11620        }
11621
11622        // Persist the runtime permissions state for users with changes. If permissions
11623        // were revoked because no app in the shared user declares them we have to
11624        // write synchronously to avoid losing runtime permissions state.
11625        for (int userId : changedRuntimePermissionUserIds) {
11626            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11627        }
11628    }
11629
11630    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11631        boolean allowed = false;
11632        final int NP = PackageParser.NEW_PERMISSIONS.length;
11633        for (int ip=0; ip<NP; ip++) {
11634            final PackageParser.NewPermissionInfo npi
11635                    = PackageParser.NEW_PERMISSIONS[ip];
11636            if (npi.name.equals(perm)
11637                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11638                allowed = true;
11639                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11640                        + pkg.packageName);
11641                break;
11642            }
11643        }
11644        return allowed;
11645    }
11646
11647    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11648            BasePermission bp, PermissionsState origPermissions) {
11649        boolean privilegedPermission = (bp.protectionLevel
11650                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11651        boolean privappPermissionsDisable =
11652                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11653        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11654        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11655        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11656                && !platformPackage && platformPermission) {
11657            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11658                    .getPrivAppPermissions(pkg.packageName);
11659            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11660            if (!whitelisted) {
11661                Slog.w(TAG, "Privileged permission " + perm + " for package "
11662                        + pkg.packageName + " - not in privapp-permissions whitelist");
11663                // Only report violations for apps on system image
11664                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11665                    if (mPrivappPermissionsViolations == null) {
11666                        mPrivappPermissionsViolations = new ArraySet<>();
11667                    }
11668                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11669                }
11670                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11671                    return false;
11672                }
11673            }
11674        }
11675        boolean allowed = (compareSignatures(
11676                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11677                        == PackageManager.SIGNATURE_MATCH)
11678                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11679                        == PackageManager.SIGNATURE_MATCH);
11680        if (!allowed && privilegedPermission) {
11681            if (isSystemApp(pkg)) {
11682                // For updated system applications, a system permission
11683                // is granted only if it had been defined by the original application.
11684                if (pkg.isUpdatedSystemApp()) {
11685                    final PackageSetting sysPs = mSettings
11686                            .getDisabledSystemPkgLPr(pkg.packageName);
11687                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11688                        // If the original was granted this permission, we take
11689                        // that grant decision as read and propagate it to the
11690                        // update.
11691                        if (sysPs.isPrivileged()) {
11692                            allowed = true;
11693                        }
11694                    } else {
11695                        // The system apk may have been updated with an older
11696                        // version of the one on the data partition, but which
11697                        // granted a new system permission that it didn't have
11698                        // before.  In this case we do want to allow the app to
11699                        // now get the new permission if the ancestral apk is
11700                        // privileged to get it.
11701                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11702                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11703                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11704                                    allowed = true;
11705                                    break;
11706                                }
11707                            }
11708                        }
11709                        // Also if a privileged parent package on the system image or any of
11710                        // its children requested a privileged permission, the updated child
11711                        // packages can also get the permission.
11712                        if (pkg.parentPackage != null) {
11713                            final PackageSetting disabledSysParentPs = mSettings
11714                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11715                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11716                                    && disabledSysParentPs.isPrivileged()) {
11717                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11718                                    allowed = true;
11719                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11720                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11721                                    for (int i = 0; i < count; i++) {
11722                                        PackageParser.Package disabledSysChildPkg =
11723                                                disabledSysParentPs.pkg.childPackages.get(i);
11724                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11725                                                perm)) {
11726                                            allowed = true;
11727                                            break;
11728                                        }
11729                                    }
11730                                }
11731                            }
11732                        }
11733                    }
11734                } else {
11735                    allowed = isPrivilegedApp(pkg);
11736                }
11737            }
11738        }
11739        if (!allowed) {
11740            if (!allowed && (bp.protectionLevel
11741                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11742                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11743                // If this was a previously normal/dangerous permission that got moved
11744                // to a system permission as part of the runtime permission redesign, then
11745                // we still want to blindly grant it to old apps.
11746                allowed = true;
11747            }
11748            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11749                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11750                // If this permission is to be granted to the system installer and
11751                // this app is an installer, then it gets the permission.
11752                allowed = true;
11753            }
11754            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11755                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11756                // If this permission is to be granted to the system verifier and
11757                // this app is a verifier, then it gets the permission.
11758                allowed = true;
11759            }
11760            if (!allowed && (bp.protectionLevel
11761                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11762                    && isSystemApp(pkg)) {
11763                // Any pre-installed system app is allowed to get this permission.
11764                allowed = true;
11765            }
11766            if (!allowed && (bp.protectionLevel
11767                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11768                // For development permissions, a development permission
11769                // is granted only if it was already granted.
11770                allowed = origPermissions.hasInstallPermission(perm);
11771            }
11772            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11773                    && pkg.packageName.equals(mSetupWizardPackage)) {
11774                // If this permission is to be granted to the system setup wizard and
11775                // this app is a setup wizard, then it gets the permission.
11776                allowed = true;
11777            }
11778        }
11779        return allowed;
11780    }
11781
11782    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11783        final int permCount = pkg.requestedPermissions.size();
11784        for (int j = 0; j < permCount; j++) {
11785            String requestedPermission = pkg.requestedPermissions.get(j);
11786            if (permission.equals(requestedPermission)) {
11787                return true;
11788            }
11789        }
11790        return false;
11791    }
11792
11793    final class ActivityIntentResolver
11794            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11795        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11796                boolean defaultOnly, int userId) {
11797            if (!sUserManager.exists(userId)) return null;
11798            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11799            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11800        }
11801
11802        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11803                int userId) {
11804            if (!sUserManager.exists(userId)) return null;
11805            mFlags = flags;
11806            return super.queryIntent(intent, resolvedType,
11807                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11808                    userId);
11809        }
11810
11811        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11812                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11813            if (!sUserManager.exists(userId)) return null;
11814            if (packageActivities == null) {
11815                return null;
11816            }
11817            mFlags = flags;
11818            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11819            final int N = packageActivities.size();
11820            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11821                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11822
11823            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11824            for (int i = 0; i < N; ++i) {
11825                intentFilters = packageActivities.get(i).intents;
11826                if (intentFilters != null && intentFilters.size() > 0) {
11827                    PackageParser.ActivityIntentInfo[] array =
11828                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11829                    intentFilters.toArray(array);
11830                    listCut.add(array);
11831                }
11832            }
11833            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11834        }
11835
11836        /**
11837         * Finds a privileged activity that matches the specified activity names.
11838         */
11839        private PackageParser.Activity findMatchingActivity(
11840                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11841            for (PackageParser.Activity sysActivity : activityList) {
11842                if (sysActivity.info.name.equals(activityInfo.name)) {
11843                    return sysActivity;
11844                }
11845                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11846                    return sysActivity;
11847                }
11848                if (sysActivity.info.targetActivity != null) {
11849                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11850                        return sysActivity;
11851                    }
11852                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11853                        return sysActivity;
11854                    }
11855                }
11856            }
11857            return null;
11858        }
11859
11860        public class IterGenerator<E> {
11861            public Iterator<E> generate(ActivityIntentInfo info) {
11862                return null;
11863            }
11864        }
11865
11866        public class ActionIterGenerator extends IterGenerator<String> {
11867            @Override
11868            public Iterator<String> generate(ActivityIntentInfo info) {
11869                return info.actionsIterator();
11870            }
11871        }
11872
11873        public class CategoriesIterGenerator extends IterGenerator<String> {
11874            @Override
11875            public Iterator<String> generate(ActivityIntentInfo info) {
11876                return info.categoriesIterator();
11877            }
11878        }
11879
11880        public class SchemesIterGenerator extends IterGenerator<String> {
11881            @Override
11882            public Iterator<String> generate(ActivityIntentInfo info) {
11883                return info.schemesIterator();
11884            }
11885        }
11886
11887        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11888            @Override
11889            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11890                return info.authoritiesIterator();
11891            }
11892        }
11893
11894        /**
11895         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11896         * MODIFIED. Do not pass in a list that should not be changed.
11897         */
11898        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11899                IterGenerator<T> generator, Iterator<T> searchIterator) {
11900            // loop through the set of actions; every one must be found in the intent filter
11901            while (searchIterator.hasNext()) {
11902                // we must have at least one filter in the list to consider a match
11903                if (intentList.size() == 0) {
11904                    break;
11905                }
11906
11907                final T searchAction = searchIterator.next();
11908
11909                // loop through the set of intent filters
11910                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11911                while (intentIter.hasNext()) {
11912                    final ActivityIntentInfo intentInfo = intentIter.next();
11913                    boolean selectionFound = false;
11914
11915                    // loop through the intent filter's selection criteria; at least one
11916                    // of them must match the searched criteria
11917                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11918                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11919                        final T intentSelection = intentSelectionIter.next();
11920                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11921                            selectionFound = true;
11922                            break;
11923                        }
11924                    }
11925
11926                    // the selection criteria wasn't found in this filter's set; this filter
11927                    // is not a potential match
11928                    if (!selectionFound) {
11929                        intentIter.remove();
11930                    }
11931                }
11932            }
11933        }
11934
11935        private boolean isProtectedAction(ActivityIntentInfo filter) {
11936            final Iterator<String> actionsIter = filter.actionsIterator();
11937            while (actionsIter != null && actionsIter.hasNext()) {
11938                final String filterAction = actionsIter.next();
11939                if (PROTECTED_ACTIONS.contains(filterAction)) {
11940                    return true;
11941                }
11942            }
11943            return false;
11944        }
11945
11946        /**
11947         * Adjusts the priority of the given intent filter according to policy.
11948         * <p>
11949         * <ul>
11950         * <li>The priority for non privileged applications is capped to '0'</li>
11951         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11952         * <li>The priority for unbundled updates to privileged applications is capped to the
11953         *      priority defined on the system partition</li>
11954         * </ul>
11955         * <p>
11956         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11957         * allowed to obtain any priority on any action.
11958         */
11959        private void adjustPriority(
11960                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11961            // nothing to do; priority is fine as-is
11962            if (intent.getPriority() <= 0) {
11963                return;
11964            }
11965
11966            final ActivityInfo activityInfo = intent.activity.info;
11967            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11968
11969            final boolean privilegedApp =
11970                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11971            if (!privilegedApp) {
11972                // non-privileged applications can never define a priority >0
11973                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11974                        + " package: " + applicationInfo.packageName
11975                        + " activity: " + intent.activity.className
11976                        + " origPrio: " + intent.getPriority());
11977                intent.setPriority(0);
11978                return;
11979            }
11980
11981            if (systemActivities == null) {
11982                // the system package is not disabled; we're parsing the system partition
11983                if (isProtectedAction(intent)) {
11984                    if (mDeferProtectedFilters) {
11985                        // We can't deal with these just yet. No component should ever obtain a
11986                        // >0 priority for a protected actions, with ONE exception -- the setup
11987                        // wizard. The setup wizard, however, cannot be known until we're able to
11988                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11989                        // until all intent filters have been processed. Chicken, meet egg.
11990                        // Let the filter temporarily have a high priority and rectify the
11991                        // priorities after all system packages have been scanned.
11992                        mProtectedFilters.add(intent);
11993                        if (DEBUG_FILTERS) {
11994                            Slog.i(TAG, "Protected action; save for later;"
11995                                    + " package: " + applicationInfo.packageName
11996                                    + " activity: " + intent.activity.className
11997                                    + " origPrio: " + intent.getPriority());
11998                        }
11999                        return;
12000                    } else {
12001                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12002                            Slog.i(TAG, "No setup wizard;"
12003                                + " All protected intents capped to priority 0");
12004                        }
12005                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12006                            if (DEBUG_FILTERS) {
12007                                Slog.i(TAG, "Found setup wizard;"
12008                                    + " allow priority " + intent.getPriority() + ";"
12009                                    + " package: " + intent.activity.info.packageName
12010                                    + " activity: " + intent.activity.className
12011                                    + " priority: " + intent.getPriority());
12012                            }
12013                            // setup wizard gets whatever it wants
12014                            return;
12015                        }
12016                        Slog.w(TAG, "Protected action; cap priority to 0;"
12017                                + " package: " + intent.activity.info.packageName
12018                                + " activity: " + intent.activity.className
12019                                + " origPrio: " + intent.getPriority());
12020                        intent.setPriority(0);
12021                        return;
12022                    }
12023                }
12024                // privileged apps on the system image get whatever priority they request
12025                return;
12026            }
12027
12028            // privileged app unbundled update ... try to find the same activity
12029            final PackageParser.Activity foundActivity =
12030                    findMatchingActivity(systemActivities, activityInfo);
12031            if (foundActivity == null) {
12032                // this is a new activity; it cannot obtain >0 priority
12033                if (DEBUG_FILTERS) {
12034                    Slog.i(TAG, "New activity; cap priority to 0;"
12035                            + " package: " + applicationInfo.packageName
12036                            + " activity: " + intent.activity.className
12037                            + " origPrio: " + intent.getPriority());
12038                }
12039                intent.setPriority(0);
12040                return;
12041            }
12042
12043            // found activity, now check for filter equivalence
12044
12045            // a shallow copy is enough; we modify the list, not its contents
12046            final List<ActivityIntentInfo> intentListCopy =
12047                    new ArrayList<>(foundActivity.intents);
12048            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12049
12050            // find matching action subsets
12051            final Iterator<String> actionsIterator = intent.actionsIterator();
12052            if (actionsIterator != null) {
12053                getIntentListSubset(
12054                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12055                if (intentListCopy.size() == 0) {
12056                    // no more intents to match; we're not equivalent
12057                    if (DEBUG_FILTERS) {
12058                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12059                                + " package: " + applicationInfo.packageName
12060                                + " activity: " + intent.activity.className
12061                                + " origPrio: " + intent.getPriority());
12062                    }
12063                    intent.setPriority(0);
12064                    return;
12065                }
12066            }
12067
12068            // find matching category subsets
12069            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12070            if (categoriesIterator != null) {
12071                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12072                        categoriesIterator);
12073                if (intentListCopy.size() == 0) {
12074                    // no more intents to match; we're not equivalent
12075                    if (DEBUG_FILTERS) {
12076                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12077                                + " package: " + applicationInfo.packageName
12078                                + " activity: " + intent.activity.className
12079                                + " origPrio: " + intent.getPriority());
12080                    }
12081                    intent.setPriority(0);
12082                    return;
12083                }
12084            }
12085
12086            // find matching schemes subsets
12087            final Iterator<String> schemesIterator = intent.schemesIterator();
12088            if (schemesIterator != null) {
12089                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12090                        schemesIterator);
12091                if (intentListCopy.size() == 0) {
12092                    // no more intents to match; we're not equivalent
12093                    if (DEBUG_FILTERS) {
12094                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12095                                + " package: " + applicationInfo.packageName
12096                                + " activity: " + intent.activity.className
12097                                + " origPrio: " + intent.getPriority());
12098                    }
12099                    intent.setPriority(0);
12100                    return;
12101                }
12102            }
12103
12104            // find matching authorities subsets
12105            final Iterator<IntentFilter.AuthorityEntry>
12106                    authoritiesIterator = intent.authoritiesIterator();
12107            if (authoritiesIterator != null) {
12108                getIntentListSubset(intentListCopy,
12109                        new AuthoritiesIterGenerator(),
12110                        authoritiesIterator);
12111                if (intentListCopy.size() == 0) {
12112                    // no more intents to match; we're not equivalent
12113                    if (DEBUG_FILTERS) {
12114                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12115                                + " package: " + applicationInfo.packageName
12116                                + " activity: " + intent.activity.className
12117                                + " origPrio: " + intent.getPriority());
12118                    }
12119                    intent.setPriority(0);
12120                    return;
12121                }
12122            }
12123
12124            // we found matching filter(s); app gets the max priority of all intents
12125            int cappedPriority = 0;
12126            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12127                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12128            }
12129            if (intent.getPriority() > cappedPriority) {
12130                if (DEBUG_FILTERS) {
12131                    Slog.i(TAG, "Found matching filter(s);"
12132                            + " cap priority to " + cappedPriority + ";"
12133                            + " package: " + applicationInfo.packageName
12134                            + " activity: " + intent.activity.className
12135                            + " origPrio: " + intent.getPriority());
12136                }
12137                intent.setPriority(cappedPriority);
12138                return;
12139            }
12140            // all this for nothing; the requested priority was <= what was on the system
12141        }
12142
12143        public final void addActivity(PackageParser.Activity a, String type) {
12144            mActivities.put(a.getComponentName(), a);
12145            if (DEBUG_SHOW_INFO)
12146                Log.v(
12147                TAG, "  " + type + " " +
12148                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12149            if (DEBUG_SHOW_INFO)
12150                Log.v(TAG, "    Class=" + a.info.name);
12151            final int NI = a.intents.size();
12152            for (int j=0; j<NI; j++) {
12153                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12154                if ("activity".equals(type)) {
12155                    final PackageSetting ps =
12156                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12157                    final List<PackageParser.Activity> systemActivities =
12158                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12159                    adjustPriority(systemActivities, intent);
12160                }
12161                if (DEBUG_SHOW_INFO) {
12162                    Log.v(TAG, "    IntentFilter:");
12163                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12164                }
12165                if (!intent.debugCheck()) {
12166                    Log.w(TAG, "==> For Activity " + a.info.name);
12167                }
12168                addFilter(intent);
12169            }
12170        }
12171
12172        public final void removeActivity(PackageParser.Activity a, String type) {
12173            mActivities.remove(a.getComponentName());
12174            if (DEBUG_SHOW_INFO) {
12175                Log.v(TAG, "  " + type + " "
12176                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12177                                : a.info.name) + ":");
12178                Log.v(TAG, "    Class=" + a.info.name);
12179            }
12180            final int NI = a.intents.size();
12181            for (int j=0; j<NI; j++) {
12182                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12183                if (DEBUG_SHOW_INFO) {
12184                    Log.v(TAG, "    IntentFilter:");
12185                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12186                }
12187                removeFilter(intent);
12188            }
12189        }
12190
12191        @Override
12192        protected boolean allowFilterResult(
12193                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12194            ActivityInfo filterAi = filter.activity.info;
12195            for (int i=dest.size()-1; i>=0; i--) {
12196                ActivityInfo destAi = dest.get(i).activityInfo;
12197                if (destAi.name == filterAi.name
12198                        && destAi.packageName == filterAi.packageName) {
12199                    return false;
12200                }
12201            }
12202            return true;
12203        }
12204
12205        @Override
12206        protected ActivityIntentInfo[] newArray(int size) {
12207            return new ActivityIntentInfo[size];
12208        }
12209
12210        @Override
12211        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12212            if (!sUserManager.exists(userId)) return true;
12213            PackageParser.Package p = filter.activity.owner;
12214            if (p != null) {
12215                PackageSetting ps = (PackageSetting)p.mExtras;
12216                if (ps != null) {
12217                    // System apps are never considered stopped for purposes of
12218                    // filtering, because there may be no way for the user to
12219                    // actually re-launch them.
12220                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12221                            && ps.getStopped(userId);
12222                }
12223            }
12224            return false;
12225        }
12226
12227        @Override
12228        protected boolean isPackageForFilter(String packageName,
12229                PackageParser.ActivityIntentInfo info) {
12230            return packageName.equals(info.activity.owner.packageName);
12231        }
12232
12233        @Override
12234        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12235                int match, int userId) {
12236            if (!sUserManager.exists(userId)) return null;
12237            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12238                return null;
12239            }
12240            final PackageParser.Activity activity = info.activity;
12241            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12242            if (ps == null) {
12243                return null;
12244            }
12245            final PackageUserState userState = ps.readUserState(userId);
12246            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12247                    userState, userId);
12248            if (ai == null) {
12249                return null;
12250            }
12251            final boolean matchVisibleToInstantApp =
12252                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12253            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12254            // throw out filters that aren't visible to ephemeral apps
12255            if (matchVisibleToInstantApp
12256                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12257                return null;
12258            }
12259            // throw out ephemeral filters if we're not explicitly requesting them
12260            if (!isInstantApp && userState.instantApp) {
12261                return null;
12262            }
12263            // throw out instant app filters if updates are available; will trigger
12264            // instant app resolution
12265            if (userState.instantApp && ps.isUpdateAvailable()) {
12266                return null;
12267            }
12268            final ResolveInfo res = new ResolveInfo();
12269            res.activityInfo = ai;
12270            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12271                res.filter = info;
12272            }
12273            if (info != null) {
12274                res.handleAllWebDataURI = info.handleAllWebDataURI();
12275            }
12276            res.priority = info.getPriority();
12277            res.preferredOrder = activity.owner.mPreferredOrder;
12278            //System.out.println("Result: " + res.activityInfo.className +
12279            //                   " = " + res.priority);
12280            res.match = match;
12281            res.isDefault = info.hasDefault;
12282            res.labelRes = info.labelRes;
12283            res.nonLocalizedLabel = info.nonLocalizedLabel;
12284            if (userNeedsBadging(userId)) {
12285                res.noResourceId = true;
12286            } else {
12287                res.icon = info.icon;
12288            }
12289            res.iconResourceId = info.icon;
12290            res.system = res.activityInfo.applicationInfo.isSystemApp();
12291            res.instantAppAvailable = userState.instantApp;
12292            return res;
12293        }
12294
12295        @Override
12296        protected void sortResults(List<ResolveInfo> results) {
12297            Collections.sort(results, mResolvePrioritySorter);
12298        }
12299
12300        @Override
12301        protected void dumpFilter(PrintWriter out, String prefix,
12302                PackageParser.ActivityIntentInfo filter) {
12303            out.print(prefix); out.print(
12304                    Integer.toHexString(System.identityHashCode(filter.activity)));
12305                    out.print(' ');
12306                    filter.activity.printComponentShortName(out);
12307                    out.print(" filter ");
12308                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12309        }
12310
12311        @Override
12312        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12313            return filter.activity;
12314        }
12315
12316        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12317            PackageParser.Activity activity = (PackageParser.Activity)label;
12318            out.print(prefix); out.print(
12319                    Integer.toHexString(System.identityHashCode(activity)));
12320                    out.print(' ');
12321                    activity.printComponentShortName(out);
12322            if (count > 1) {
12323                out.print(" ("); out.print(count); out.print(" filters)");
12324            }
12325            out.println();
12326        }
12327
12328        // Keys are String (activity class name), values are Activity.
12329        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12330                = new ArrayMap<ComponentName, PackageParser.Activity>();
12331        private int mFlags;
12332    }
12333
12334    private final class ServiceIntentResolver
12335            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12336        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12337                boolean defaultOnly, int userId) {
12338            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12339            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12340        }
12341
12342        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12343                int userId) {
12344            if (!sUserManager.exists(userId)) return null;
12345            mFlags = flags;
12346            return super.queryIntent(intent, resolvedType,
12347                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12348                    userId);
12349        }
12350
12351        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12352                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12353            if (!sUserManager.exists(userId)) return null;
12354            if (packageServices == null) {
12355                return null;
12356            }
12357            mFlags = flags;
12358            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12359            final int N = packageServices.size();
12360            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12361                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12362
12363            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12364            for (int i = 0; i < N; ++i) {
12365                intentFilters = packageServices.get(i).intents;
12366                if (intentFilters != null && intentFilters.size() > 0) {
12367                    PackageParser.ServiceIntentInfo[] array =
12368                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12369                    intentFilters.toArray(array);
12370                    listCut.add(array);
12371                }
12372            }
12373            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12374        }
12375
12376        public final void addService(PackageParser.Service s) {
12377            mServices.put(s.getComponentName(), s);
12378            if (DEBUG_SHOW_INFO) {
12379                Log.v(TAG, "  "
12380                        + (s.info.nonLocalizedLabel != null
12381                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12382                Log.v(TAG, "    Class=" + s.info.name);
12383            }
12384            final int NI = s.intents.size();
12385            int j;
12386            for (j=0; j<NI; j++) {
12387                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12388                if (DEBUG_SHOW_INFO) {
12389                    Log.v(TAG, "    IntentFilter:");
12390                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12391                }
12392                if (!intent.debugCheck()) {
12393                    Log.w(TAG, "==> For Service " + s.info.name);
12394                }
12395                addFilter(intent);
12396            }
12397        }
12398
12399        public final void removeService(PackageParser.Service s) {
12400            mServices.remove(s.getComponentName());
12401            if (DEBUG_SHOW_INFO) {
12402                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12403                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12404                Log.v(TAG, "    Class=" + s.info.name);
12405            }
12406            final int NI = s.intents.size();
12407            int j;
12408            for (j=0; j<NI; j++) {
12409                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12410                if (DEBUG_SHOW_INFO) {
12411                    Log.v(TAG, "    IntentFilter:");
12412                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12413                }
12414                removeFilter(intent);
12415            }
12416        }
12417
12418        @Override
12419        protected boolean allowFilterResult(
12420                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12421            ServiceInfo filterSi = filter.service.info;
12422            for (int i=dest.size()-1; i>=0; i--) {
12423                ServiceInfo destAi = dest.get(i).serviceInfo;
12424                if (destAi.name == filterSi.name
12425                        && destAi.packageName == filterSi.packageName) {
12426                    return false;
12427                }
12428            }
12429            return true;
12430        }
12431
12432        @Override
12433        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12434            return new PackageParser.ServiceIntentInfo[size];
12435        }
12436
12437        @Override
12438        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12439            if (!sUserManager.exists(userId)) return true;
12440            PackageParser.Package p = filter.service.owner;
12441            if (p != null) {
12442                PackageSetting ps = (PackageSetting)p.mExtras;
12443                if (ps != null) {
12444                    // System apps are never considered stopped for purposes of
12445                    // filtering, because there may be no way for the user to
12446                    // actually re-launch them.
12447                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12448                            && ps.getStopped(userId);
12449                }
12450            }
12451            return false;
12452        }
12453
12454        @Override
12455        protected boolean isPackageForFilter(String packageName,
12456                PackageParser.ServiceIntentInfo info) {
12457            return packageName.equals(info.service.owner.packageName);
12458        }
12459
12460        @Override
12461        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12462                int match, int userId) {
12463            if (!sUserManager.exists(userId)) return null;
12464            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12465            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12466                return null;
12467            }
12468            final PackageParser.Service service = info.service;
12469            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12470            if (ps == null) {
12471                return null;
12472            }
12473            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12474                    ps.readUserState(userId), userId);
12475            if (si == null) {
12476                return null;
12477            }
12478            final ResolveInfo res = new ResolveInfo();
12479            res.serviceInfo = si;
12480            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12481                res.filter = filter;
12482            }
12483            res.priority = info.getPriority();
12484            res.preferredOrder = service.owner.mPreferredOrder;
12485            res.match = match;
12486            res.isDefault = info.hasDefault;
12487            res.labelRes = info.labelRes;
12488            res.nonLocalizedLabel = info.nonLocalizedLabel;
12489            res.icon = info.icon;
12490            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12491            return res;
12492        }
12493
12494        @Override
12495        protected void sortResults(List<ResolveInfo> results) {
12496            Collections.sort(results, mResolvePrioritySorter);
12497        }
12498
12499        @Override
12500        protected void dumpFilter(PrintWriter out, String prefix,
12501                PackageParser.ServiceIntentInfo filter) {
12502            out.print(prefix); out.print(
12503                    Integer.toHexString(System.identityHashCode(filter.service)));
12504                    out.print(' ');
12505                    filter.service.printComponentShortName(out);
12506                    out.print(" filter ");
12507                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12508        }
12509
12510        @Override
12511        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12512            return filter.service;
12513        }
12514
12515        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12516            PackageParser.Service service = (PackageParser.Service)label;
12517            out.print(prefix); out.print(
12518                    Integer.toHexString(System.identityHashCode(service)));
12519                    out.print(' ');
12520                    service.printComponentShortName(out);
12521            if (count > 1) {
12522                out.print(" ("); out.print(count); out.print(" filters)");
12523            }
12524            out.println();
12525        }
12526
12527//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12528//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12529//            final List<ResolveInfo> retList = Lists.newArrayList();
12530//            while (i.hasNext()) {
12531//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12532//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12533//                    retList.add(resolveInfo);
12534//                }
12535//            }
12536//            return retList;
12537//        }
12538
12539        // Keys are String (activity class name), values are Activity.
12540        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12541                = new ArrayMap<ComponentName, PackageParser.Service>();
12542        private int mFlags;
12543    }
12544
12545    private final class ProviderIntentResolver
12546            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12547        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12548                boolean defaultOnly, int userId) {
12549            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12550            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12551        }
12552
12553        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12554                int userId) {
12555            if (!sUserManager.exists(userId))
12556                return null;
12557            mFlags = flags;
12558            return super.queryIntent(intent, resolvedType,
12559                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12560                    userId);
12561        }
12562
12563        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12564                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12565            if (!sUserManager.exists(userId))
12566                return null;
12567            if (packageProviders == null) {
12568                return null;
12569            }
12570            mFlags = flags;
12571            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12572            final int N = packageProviders.size();
12573            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12574                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12575
12576            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12577            for (int i = 0; i < N; ++i) {
12578                intentFilters = packageProviders.get(i).intents;
12579                if (intentFilters != null && intentFilters.size() > 0) {
12580                    PackageParser.ProviderIntentInfo[] array =
12581                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12582                    intentFilters.toArray(array);
12583                    listCut.add(array);
12584                }
12585            }
12586            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12587        }
12588
12589        public final void addProvider(PackageParser.Provider p) {
12590            if (mProviders.containsKey(p.getComponentName())) {
12591                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12592                return;
12593            }
12594
12595            mProviders.put(p.getComponentName(), p);
12596            if (DEBUG_SHOW_INFO) {
12597                Log.v(TAG, "  "
12598                        + (p.info.nonLocalizedLabel != null
12599                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12600                Log.v(TAG, "    Class=" + p.info.name);
12601            }
12602            final int NI = p.intents.size();
12603            int j;
12604            for (j = 0; j < NI; j++) {
12605                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12606                if (DEBUG_SHOW_INFO) {
12607                    Log.v(TAG, "    IntentFilter:");
12608                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12609                }
12610                if (!intent.debugCheck()) {
12611                    Log.w(TAG, "==> For Provider " + p.info.name);
12612                }
12613                addFilter(intent);
12614            }
12615        }
12616
12617        public final void removeProvider(PackageParser.Provider p) {
12618            mProviders.remove(p.getComponentName());
12619            if (DEBUG_SHOW_INFO) {
12620                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12621                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12622                Log.v(TAG, "    Class=" + p.info.name);
12623            }
12624            final int NI = p.intents.size();
12625            int j;
12626            for (j = 0; j < NI; j++) {
12627                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12628                if (DEBUG_SHOW_INFO) {
12629                    Log.v(TAG, "    IntentFilter:");
12630                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12631                }
12632                removeFilter(intent);
12633            }
12634        }
12635
12636        @Override
12637        protected boolean allowFilterResult(
12638                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12639            ProviderInfo filterPi = filter.provider.info;
12640            for (int i = dest.size() - 1; i >= 0; i--) {
12641                ProviderInfo destPi = dest.get(i).providerInfo;
12642                if (destPi.name == filterPi.name
12643                        && destPi.packageName == filterPi.packageName) {
12644                    return false;
12645                }
12646            }
12647            return true;
12648        }
12649
12650        @Override
12651        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12652            return new PackageParser.ProviderIntentInfo[size];
12653        }
12654
12655        @Override
12656        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12657            if (!sUserManager.exists(userId))
12658                return true;
12659            PackageParser.Package p = filter.provider.owner;
12660            if (p != null) {
12661                PackageSetting ps = (PackageSetting) p.mExtras;
12662                if (ps != null) {
12663                    // System apps are never considered stopped for purposes of
12664                    // filtering, because there may be no way for the user to
12665                    // actually re-launch them.
12666                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12667                            && ps.getStopped(userId);
12668                }
12669            }
12670            return false;
12671        }
12672
12673        @Override
12674        protected boolean isPackageForFilter(String packageName,
12675                PackageParser.ProviderIntentInfo info) {
12676            return packageName.equals(info.provider.owner.packageName);
12677        }
12678
12679        @Override
12680        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12681                int match, int userId) {
12682            if (!sUserManager.exists(userId))
12683                return null;
12684            final PackageParser.ProviderIntentInfo info = filter;
12685            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12686                return null;
12687            }
12688            final PackageParser.Provider provider = info.provider;
12689            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12690            if (ps == null) {
12691                return null;
12692            }
12693            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12694                    ps.readUserState(userId), userId);
12695            if (pi == null) {
12696                return null;
12697            }
12698            final ResolveInfo res = new ResolveInfo();
12699            res.providerInfo = pi;
12700            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12701                res.filter = filter;
12702            }
12703            res.priority = info.getPriority();
12704            res.preferredOrder = provider.owner.mPreferredOrder;
12705            res.match = match;
12706            res.isDefault = info.hasDefault;
12707            res.labelRes = info.labelRes;
12708            res.nonLocalizedLabel = info.nonLocalizedLabel;
12709            res.icon = info.icon;
12710            res.system = res.providerInfo.applicationInfo.isSystemApp();
12711            return res;
12712        }
12713
12714        @Override
12715        protected void sortResults(List<ResolveInfo> results) {
12716            Collections.sort(results, mResolvePrioritySorter);
12717        }
12718
12719        @Override
12720        protected void dumpFilter(PrintWriter out, String prefix,
12721                PackageParser.ProviderIntentInfo filter) {
12722            out.print(prefix);
12723            out.print(
12724                    Integer.toHexString(System.identityHashCode(filter.provider)));
12725            out.print(' ');
12726            filter.provider.printComponentShortName(out);
12727            out.print(" filter ");
12728            out.println(Integer.toHexString(System.identityHashCode(filter)));
12729        }
12730
12731        @Override
12732        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12733            return filter.provider;
12734        }
12735
12736        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12737            PackageParser.Provider provider = (PackageParser.Provider)label;
12738            out.print(prefix); out.print(
12739                    Integer.toHexString(System.identityHashCode(provider)));
12740                    out.print(' ');
12741                    provider.printComponentShortName(out);
12742            if (count > 1) {
12743                out.print(" ("); out.print(count); out.print(" filters)");
12744            }
12745            out.println();
12746        }
12747
12748        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12749                = new ArrayMap<ComponentName, PackageParser.Provider>();
12750        private int mFlags;
12751    }
12752
12753    static final class EphemeralIntentResolver
12754            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12755        /**
12756         * The result that has the highest defined order. Ordering applies on a
12757         * per-package basis. Mapping is from package name to Pair of order and
12758         * EphemeralResolveInfo.
12759         * <p>
12760         * NOTE: This is implemented as a field variable for convenience and efficiency.
12761         * By having a field variable, we're able to track filter ordering as soon as
12762         * a non-zero order is defined. Otherwise, multiple loops across the result set
12763         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12764         * this needs to be contained entirely within {@link #filterResults}.
12765         */
12766        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12767
12768        @Override
12769        protected AuxiliaryResolveInfo[] newArray(int size) {
12770            return new AuxiliaryResolveInfo[size];
12771        }
12772
12773        @Override
12774        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12775            return true;
12776        }
12777
12778        @Override
12779        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12780                int userId) {
12781            if (!sUserManager.exists(userId)) {
12782                return null;
12783            }
12784            final String packageName = responseObj.resolveInfo.getPackageName();
12785            final Integer order = responseObj.getOrder();
12786            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12787                    mOrderResult.get(packageName);
12788            // ordering is enabled and this item's order isn't high enough
12789            if (lastOrderResult != null && lastOrderResult.first >= order) {
12790                return null;
12791            }
12792            final InstantAppResolveInfo res = responseObj.resolveInfo;
12793            if (order > 0) {
12794                // non-zero order, enable ordering
12795                mOrderResult.put(packageName, new Pair<>(order, res));
12796            }
12797            return responseObj;
12798        }
12799
12800        @Override
12801        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12802            // only do work if ordering is enabled [most of the time it won't be]
12803            if (mOrderResult.size() == 0) {
12804                return;
12805            }
12806            int resultSize = results.size();
12807            for (int i = 0; i < resultSize; i++) {
12808                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12809                final String packageName = info.getPackageName();
12810                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12811                if (savedInfo == null) {
12812                    // package doesn't having ordering
12813                    continue;
12814                }
12815                if (savedInfo.second == info) {
12816                    // circled back to the highest ordered item; remove from order list
12817                    mOrderResult.remove(savedInfo);
12818                    if (mOrderResult.size() == 0) {
12819                        // no more ordered items
12820                        break;
12821                    }
12822                    continue;
12823                }
12824                // item has a worse order, remove it from the result list
12825                results.remove(i);
12826                resultSize--;
12827                i--;
12828            }
12829        }
12830    }
12831
12832    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12833            new Comparator<ResolveInfo>() {
12834        public int compare(ResolveInfo r1, ResolveInfo r2) {
12835            int v1 = r1.priority;
12836            int v2 = r2.priority;
12837            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12838            if (v1 != v2) {
12839                return (v1 > v2) ? -1 : 1;
12840            }
12841            v1 = r1.preferredOrder;
12842            v2 = r2.preferredOrder;
12843            if (v1 != v2) {
12844                return (v1 > v2) ? -1 : 1;
12845            }
12846            if (r1.isDefault != r2.isDefault) {
12847                return r1.isDefault ? -1 : 1;
12848            }
12849            v1 = r1.match;
12850            v2 = r2.match;
12851            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12852            if (v1 != v2) {
12853                return (v1 > v2) ? -1 : 1;
12854            }
12855            if (r1.system != r2.system) {
12856                return r1.system ? -1 : 1;
12857            }
12858            if (r1.activityInfo != null) {
12859                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12860            }
12861            if (r1.serviceInfo != null) {
12862                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12863            }
12864            if (r1.providerInfo != null) {
12865                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12866            }
12867            return 0;
12868        }
12869    };
12870
12871    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12872            new Comparator<ProviderInfo>() {
12873        public int compare(ProviderInfo p1, ProviderInfo p2) {
12874            final int v1 = p1.initOrder;
12875            final int v2 = p2.initOrder;
12876            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12877        }
12878    };
12879
12880    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12881            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12882            final int[] userIds) {
12883        mHandler.post(new Runnable() {
12884            @Override
12885            public void run() {
12886                try {
12887                    final IActivityManager am = ActivityManager.getService();
12888                    if (am == null) return;
12889                    final int[] resolvedUserIds;
12890                    if (userIds == null) {
12891                        resolvedUserIds = am.getRunningUserIds();
12892                    } else {
12893                        resolvedUserIds = userIds;
12894                    }
12895                    for (int id : resolvedUserIds) {
12896                        final Intent intent = new Intent(action,
12897                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12898                        if (extras != null) {
12899                            intent.putExtras(extras);
12900                        }
12901                        if (targetPkg != null) {
12902                            intent.setPackage(targetPkg);
12903                        }
12904                        // Modify the UID when posting to other users
12905                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12906                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12907                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12908                            intent.putExtra(Intent.EXTRA_UID, uid);
12909                        }
12910                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12911                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12912                        if (DEBUG_BROADCASTS) {
12913                            RuntimeException here = new RuntimeException("here");
12914                            here.fillInStackTrace();
12915                            Slog.d(TAG, "Sending to user " + id + ": "
12916                                    + intent.toShortString(false, true, false, false)
12917                                    + " " + intent.getExtras(), here);
12918                        }
12919                        am.broadcastIntent(null, intent, null, finishedReceiver,
12920                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12921                                null, finishedReceiver != null, false, id);
12922                    }
12923                } catch (RemoteException ex) {
12924                }
12925            }
12926        });
12927    }
12928
12929    /**
12930     * Check if the external storage media is available. This is true if there
12931     * is a mounted external storage medium or if the external storage is
12932     * emulated.
12933     */
12934    private boolean isExternalMediaAvailable() {
12935        return mMediaMounted || Environment.isExternalStorageEmulated();
12936    }
12937
12938    @Override
12939    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12940        // writer
12941        synchronized (mPackages) {
12942            if (!isExternalMediaAvailable()) {
12943                // If the external storage is no longer mounted at this point,
12944                // the caller may not have been able to delete all of this
12945                // packages files and can not delete any more.  Bail.
12946                return null;
12947            }
12948            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12949            if (lastPackage != null) {
12950                pkgs.remove(lastPackage);
12951            }
12952            if (pkgs.size() > 0) {
12953                return pkgs.get(0);
12954            }
12955        }
12956        return null;
12957    }
12958
12959    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12960        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12961                userId, andCode ? 1 : 0, packageName);
12962        if (mSystemReady) {
12963            msg.sendToTarget();
12964        } else {
12965            if (mPostSystemReadyMessages == null) {
12966                mPostSystemReadyMessages = new ArrayList<>();
12967            }
12968            mPostSystemReadyMessages.add(msg);
12969        }
12970    }
12971
12972    void startCleaningPackages() {
12973        // reader
12974        if (!isExternalMediaAvailable()) {
12975            return;
12976        }
12977        synchronized (mPackages) {
12978            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12979                return;
12980            }
12981        }
12982        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12983        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12984        IActivityManager am = ActivityManager.getService();
12985        if (am != null) {
12986            try {
12987                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12988                        UserHandle.USER_SYSTEM);
12989            } catch (RemoteException e) {
12990            }
12991        }
12992    }
12993
12994    @Override
12995    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12996            int installFlags, String installerPackageName, int userId) {
12997        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12998
12999        final int callingUid = Binder.getCallingUid();
13000        enforceCrossUserPermission(callingUid, userId,
13001                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13002
13003        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13004            try {
13005                if (observer != null) {
13006                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13007                }
13008            } catch (RemoteException re) {
13009            }
13010            return;
13011        }
13012
13013        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13014            installFlags |= PackageManager.INSTALL_FROM_ADB;
13015
13016        } else {
13017            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13018            // about installerPackageName.
13019
13020            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13021            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13022        }
13023
13024        UserHandle user;
13025        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13026            user = UserHandle.ALL;
13027        } else {
13028            user = new UserHandle(userId);
13029        }
13030
13031        // Only system components can circumvent runtime permissions when installing.
13032        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13033                && mContext.checkCallingOrSelfPermission(Manifest.permission
13034                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13035            throw new SecurityException("You need the "
13036                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13037                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13038        }
13039
13040        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13041                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13042            throw new IllegalArgumentException(
13043                    "New installs into ASEC containers no longer supported");
13044        }
13045
13046        final File originFile = new File(originPath);
13047        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13048
13049        final Message msg = mHandler.obtainMessage(INIT_COPY);
13050        final VerificationInfo verificationInfo = new VerificationInfo(
13051                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13052        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13053                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13054                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13055                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13056        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13057        msg.obj = params;
13058
13059        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13060                System.identityHashCode(msg.obj));
13061        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13062                System.identityHashCode(msg.obj));
13063
13064        mHandler.sendMessage(msg);
13065    }
13066
13067
13068    /**
13069     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13070     * it is acting on behalf on an enterprise or the user).
13071     *
13072     * Note that the ordering of the conditionals in this method is important. The checks we perform
13073     * are as follows, in this order:
13074     *
13075     * 1) If the install is being performed by a system app, we can trust the app to have set the
13076     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13077     *    what it is.
13078     * 2) If the install is being performed by a device or profile owner app, the install reason
13079     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13080     *    set the install reason correctly. If the app targets an older SDK version where install
13081     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13082     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13083     * 3) In all other cases, the install is being performed by a regular app that is neither part
13084     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13085     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13086     *    set to enterprise policy and if so, change it to unknown instead.
13087     */
13088    private int fixUpInstallReason(String installerPackageName, int installerUid,
13089            int installReason) {
13090        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13091                == PERMISSION_GRANTED) {
13092            // If the install is being performed by a system app, we trust that app to have set the
13093            // install reason correctly.
13094            return installReason;
13095        }
13096
13097        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13098            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13099        if (dpm != null) {
13100            ComponentName owner = null;
13101            try {
13102                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13103                if (owner == null) {
13104                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13105                }
13106            } catch (RemoteException e) {
13107            }
13108            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13109                // If the install is being performed by a device or profile owner, the install
13110                // reason should be enterprise policy.
13111                return PackageManager.INSTALL_REASON_POLICY;
13112            }
13113        }
13114
13115        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13116            // If the install is being performed by a regular app (i.e. neither system app nor
13117            // device or profile owner), we have no reason to believe that the app is acting on
13118            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13119            // change it to unknown instead.
13120            return PackageManager.INSTALL_REASON_UNKNOWN;
13121        }
13122
13123        // If the install is being performed by a regular app and the install reason was set to any
13124        // value but enterprise policy, leave the install reason unchanged.
13125        return installReason;
13126    }
13127
13128    void installStage(String packageName, File stagedDir, String stagedCid,
13129            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13130            String installerPackageName, int installerUid, UserHandle user,
13131            Certificate[][] certificates) {
13132        if (DEBUG_EPHEMERAL) {
13133            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13134                Slog.d(TAG, "Ephemeral install of " + packageName);
13135            }
13136        }
13137        final VerificationInfo verificationInfo = new VerificationInfo(
13138                sessionParams.originatingUri, sessionParams.referrerUri,
13139                sessionParams.originatingUid, installerUid);
13140
13141        final OriginInfo origin;
13142        if (stagedDir != null) {
13143            origin = OriginInfo.fromStagedFile(stagedDir);
13144        } else {
13145            origin = OriginInfo.fromStagedContainer(stagedCid);
13146        }
13147
13148        final Message msg = mHandler.obtainMessage(INIT_COPY);
13149        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13150                sessionParams.installReason);
13151        final InstallParams params = new InstallParams(origin, null, observer,
13152                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13153                verificationInfo, user, sessionParams.abiOverride,
13154                sessionParams.grantedRuntimePermissions, certificates, installReason);
13155        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13156        msg.obj = params;
13157
13158        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13159                System.identityHashCode(msg.obj));
13160        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13161                System.identityHashCode(msg.obj));
13162
13163        mHandler.sendMessage(msg);
13164    }
13165
13166    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13167            int userId) {
13168        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13169        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13170    }
13171
13172    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13173            int appId, int... userIds) {
13174        if (ArrayUtils.isEmpty(userIds)) {
13175            return;
13176        }
13177        Bundle extras = new Bundle(1);
13178        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13179        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13180
13181        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13182                packageName, extras, 0, null, null, userIds);
13183        if (isSystem) {
13184            mHandler.post(() -> {
13185                        for (int userId : userIds) {
13186                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13187                        }
13188                    }
13189            );
13190        }
13191    }
13192
13193    /**
13194     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13195     * automatically without needing an explicit launch.
13196     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13197     */
13198    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13199        // If user is not running, the app didn't miss any broadcast
13200        if (!mUserManagerInternal.isUserRunning(userId)) {
13201            return;
13202        }
13203        final IActivityManager am = ActivityManager.getService();
13204        try {
13205            // Deliver LOCKED_BOOT_COMPLETED first
13206            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13207                    .setPackage(packageName);
13208            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13209            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13210                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13211
13212            // Deliver BOOT_COMPLETED only if user is unlocked
13213            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13214                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13215                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13216                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13217            }
13218        } catch (RemoteException e) {
13219            throw e.rethrowFromSystemServer();
13220        }
13221    }
13222
13223    @Override
13224    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13225            int userId) {
13226        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13227        PackageSetting pkgSetting;
13228        final int uid = Binder.getCallingUid();
13229        enforceCrossUserPermission(uid, userId,
13230                true /* requireFullPermission */, true /* checkShell */,
13231                "setApplicationHiddenSetting for user " + userId);
13232
13233        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13234            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13235            return false;
13236        }
13237
13238        long callingId = Binder.clearCallingIdentity();
13239        try {
13240            boolean sendAdded = false;
13241            boolean sendRemoved = false;
13242            // writer
13243            synchronized (mPackages) {
13244                pkgSetting = mSettings.mPackages.get(packageName);
13245                if (pkgSetting == null) {
13246                    return false;
13247                }
13248                // Do not allow "android" is being disabled
13249                if ("android".equals(packageName)) {
13250                    Slog.w(TAG, "Cannot hide package: android");
13251                    return false;
13252                }
13253                // Cannot hide static shared libs as they are considered
13254                // a part of the using app (emulating static linking). Also
13255                // static libs are installed always on internal storage.
13256                PackageParser.Package pkg = mPackages.get(packageName);
13257                if (pkg != null && pkg.staticSharedLibName != null) {
13258                    Slog.w(TAG, "Cannot hide package: " + packageName
13259                            + " providing static shared library: "
13260                            + pkg.staticSharedLibName);
13261                    return false;
13262                }
13263                // Only allow protected packages to hide themselves.
13264                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13265                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13266                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13267                    return false;
13268                }
13269
13270                if (pkgSetting.getHidden(userId) != hidden) {
13271                    pkgSetting.setHidden(hidden, userId);
13272                    mSettings.writePackageRestrictionsLPr(userId);
13273                    if (hidden) {
13274                        sendRemoved = true;
13275                    } else {
13276                        sendAdded = true;
13277                    }
13278                }
13279            }
13280            if (sendAdded) {
13281                sendPackageAddedForUser(packageName, pkgSetting, userId);
13282                return true;
13283            }
13284            if (sendRemoved) {
13285                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13286                        "hiding pkg");
13287                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13288                return true;
13289            }
13290        } finally {
13291            Binder.restoreCallingIdentity(callingId);
13292        }
13293        return false;
13294    }
13295
13296    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13297            int userId) {
13298        final PackageRemovedInfo info = new PackageRemovedInfo();
13299        info.removedPackage = packageName;
13300        info.removedUsers = new int[] {userId};
13301        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13302        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13303    }
13304
13305    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13306        if (pkgList.length > 0) {
13307            Bundle extras = new Bundle(1);
13308            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13309
13310            sendPackageBroadcast(
13311                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13312                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13313                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13314                    new int[] {userId});
13315        }
13316    }
13317
13318    /**
13319     * Returns true if application is not found or there was an error. Otherwise it returns
13320     * the hidden state of the package for the given user.
13321     */
13322    @Override
13323    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13324        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13326                true /* requireFullPermission */, false /* checkShell */,
13327                "getApplicationHidden for user " + userId);
13328        PackageSetting pkgSetting;
13329        long callingId = Binder.clearCallingIdentity();
13330        try {
13331            // writer
13332            synchronized (mPackages) {
13333                pkgSetting = mSettings.mPackages.get(packageName);
13334                if (pkgSetting == null) {
13335                    return true;
13336                }
13337                return pkgSetting.getHidden(userId);
13338            }
13339        } finally {
13340            Binder.restoreCallingIdentity(callingId);
13341        }
13342    }
13343
13344    /**
13345     * @hide
13346     */
13347    @Override
13348    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13349            int installReason) {
13350        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13351                null);
13352        PackageSetting pkgSetting;
13353        final int uid = Binder.getCallingUid();
13354        enforceCrossUserPermission(uid, userId,
13355                true /* requireFullPermission */, true /* checkShell */,
13356                "installExistingPackage for user " + userId);
13357        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13358            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13359        }
13360
13361        long callingId = Binder.clearCallingIdentity();
13362        try {
13363            boolean installed = false;
13364            final boolean instantApp =
13365                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13366            final boolean fullApp =
13367                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13368
13369            // writer
13370            synchronized (mPackages) {
13371                pkgSetting = mSettings.mPackages.get(packageName);
13372                if (pkgSetting == null) {
13373                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13374                }
13375                if (!pkgSetting.getInstalled(userId)) {
13376                    pkgSetting.setInstalled(true, userId);
13377                    pkgSetting.setHidden(false, userId);
13378                    pkgSetting.setInstallReason(installReason, userId);
13379                    mSettings.writePackageRestrictionsLPr(userId);
13380                    mSettings.writeKernelMappingLPr(pkgSetting);
13381                    installed = true;
13382                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13383                    // upgrade app from instant to full; we don't allow app downgrade
13384                    installed = true;
13385                }
13386                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13387            }
13388
13389            if (installed) {
13390                if (pkgSetting.pkg != null) {
13391                    synchronized (mInstallLock) {
13392                        // We don't need to freeze for a brand new install
13393                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13394                    }
13395                }
13396                sendPackageAddedForUser(packageName, pkgSetting, userId);
13397                synchronized (mPackages) {
13398                    updateSequenceNumberLP(packageName, new int[]{ userId });
13399                }
13400            }
13401        } finally {
13402            Binder.restoreCallingIdentity(callingId);
13403        }
13404
13405        return PackageManager.INSTALL_SUCCEEDED;
13406    }
13407
13408    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13409            boolean instantApp, boolean fullApp) {
13410        // no state specified; do nothing
13411        if (!instantApp && !fullApp) {
13412            return;
13413        }
13414        if (userId != UserHandle.USER_ALL) {
13415            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13416                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13417            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13418                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13419            }
13420        } else {
13421            for (int currentUserId : sUserManager.getUserIds()) {
13422                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13423                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13424                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13425                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13426                }
13427            }
13428        }
13429    }
13430
13431    boolean isUserRestricted(int userId, String restrictionKey) {
13432        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13433        if (restrictions.getBoolean(restrictionKey, false)) {
13434            Log.w(TAG, "User is restricted: " + restrictionKey);
13435            return true;
13436        }
13437        return false;
13438    }
13439
13440    @Override
13441    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13442            int userId) {
13443        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13445                true /* requireFullPermission */, true /* checkShell */,
13446                "setPackagesSuspended for user " + userId);
13447
13448        if (ArrayUtils.isEmpty(packageNames)) {
13449            return packageNames;
13450        }
13451
13452        // List of package names for whom the suspended state has changed.
13453        List<String> changedPackages = new ArrayList<>(packageNames.length);
13454        // List of package names for whom the suspended state is not set as requested in this
13455        // method.
13456        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13457        long callingId = Binder.clearCallingIdentity();
13458        try {
13459            for (int i = 0; i < packageNames.length; i++) {
13460                String packageName = packageNames[i];
13461                boolean changed = false;
13462                final int appId;
13463                synchronized (mPackages) {
13464                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13465                    if (pkgSetting == null) {
13466                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13467                                + "\". Skipping suspending/un-suspending.");
13468                        unactionedPackages.add(packageName);
13469                        continue;
13470                    }
13471                    appId = pkgSetting.appId;
13472                    if (pkgSetting.getSuspended(userId) != suspended) {
13473                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13474                            unactionedPackages.add(packageName);
13475                            continue;
13476                        }
13477                        pkgSetting.setSuspended(suspended, userId);
13478                        mSettings.writePackageRestrictionsLPr(userId);
13479                        changed = true;
13480                        changedPackages.add(packageName);
13481                    }
13482                }
13483
13484                if (changed && suspended) {
13485                    killApplication(packageName, UserHandle.getUid(userId, appId),
13486                            "suspending package");
13487                }
13488            }
13489        } finally {
13490            Binder.restoreCallingIdentity(callingId);
13491        }
13492
13493        if (!changedPackages.isEmpty()) {
13494            sendPackagesSuspendedForUser(changedPackages.toArray(
13495                    new String[changedPackages.size()]), userId, suspended);
13496        }
13497
13498        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13499    }
13500
13501    @Override
13502    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13503        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13504                true /* requireFullPermission */, false /* checkShell */,
13505                "isPackageSuspendedForUser for user " + userId);
13506        synchronized (mPackages) {
13507            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13508            if (pkgSetting == null) {
13509                throw new IllegalArgumentException("Unknown target package: " + packageName);
13510            }
13511            return pkgSetting.getSuspended(userId);
13512        }
13513    }
13514
13515    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13516        if (isPackageDeviceAdmin(packageName, userId)) {
13517            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13518                    + "\": has an active device admin");
13519            return false;
13520        }
13521
13522        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13523        if (packageName.equals(activeLauncherPackageName)) {
13524            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13525                    + "\": contains the active launcher");
13526            return false;
13527        }
13528
13529        if (packageName.equals(mRequiredInstallerPackage)) {
13530            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13531                    + "\": required for package installation");
13532            return false;
13533        }
13534
13535        if (packageName.equals(mRequiredUninstallerPackage)) {
13536            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13537                    + "\": required for package uninstallation");
13538            return false;
13539        }
13540
13541        if (packageName.equals(mRequiredVerifierPackage)) {
13542            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13543                    + "\": required for package verification");
13544            return false;
13545        }
13546
13547        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13548            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13549                    + "\": is the default dialer");
13550            return false;
13551        }
13552
13553        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13554            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13555                    + "\": protected package");
13556            return false;
13557        }
13558
13559        // Cannot suspend static shared libs as they are considered
13560        // a part of the using app (emulating static linking). Also
13561        // static libs are installed always on internal storage.
13562        PackageParser.Package pkg = mPackages.get(packageName);
13563        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13564            Slog.w(TAG, "Cannot suspend package: " + packageName
13565                    + " providing static shared library: "
13566                    + pkg.staticSharedLibName);
13567            return false;
13568        }
13569
13570        return true;
13571    }
13572
13573    private String getActiveLauncherPackageName(int userId) {
13574        Intent intent = new Intent(Intent.ACTION_MAIN);
13575        intent.addCategory(Intent.CATEGORY_HOME);
13576        ResolveInfo resolveInfo = resolveIntent(
13577                intent,
13578                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13579                PackageManager.MATCH_DEFAULT_ONLY,
13580                userId);
13581
13582        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13583    }
13584
13585    private String getDefaultDialerPackageName(int userId) {
13586        synchronized (mPackages) {
13587            return mSettings.getDefaultDialerPackageNameLPw(userId);
13588        }
13589    }
13590
13591    @Override
13592    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13593        mContext.enforceCallingOrSelfPermission(
13594                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13595                "Only package verification agents can verify applications");
13596
13597        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13598        final PackageVerificationResponse response = new PackageVerificationResponse(
13599                verificationCode, Binder.getCallingUid());
13600        msg.arg1 = id;
13601        msg.obj = response;
13602        mHandler.sendMessage(msg);
13603    }
13604
13605    @Override
13606    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13607            long millisecondsToDelay) {
13608        mContext.enforceCallingOrSelfPermission(
13609                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13610                "Only package verification agents can extend verification timeouts");
13611
13612        final PackageVerificationState state = mPendingVerification.get(id);
13613        final PackageVerificationResponse response = new PackageVerificationResponse(
13614                verificationCodeAtTimeout, Binder.getCallingUid());
13615
13616        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13617            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13618        }
13619        if (millisecondsToDelay < 0) {
13620            millisecondsToDelay = 0;
13621        }
13622        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13623                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13624            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13625        }
13626
13627        if ((state != null) && !state.timeoutExtended()) {
13628            state.extendTimeout();
13629
13630            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13631            msg.arg1 = id;
13632            msg.obj = response;
13633            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13634        }
13635    }
13636
13637    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13638            int verificationCode, UserHandle user) {
13639        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13640        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13641        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13642        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13643        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13644
13645        mContext.sendBroadcastAsUser(intent, user,
13646                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13647    }
13648
13649    private ComponentName matchComponentForVerifier(String packageName,
13650            List<ResolveInfo> receivers) {
13651        ActivityInfo targetReceiver = null;
13652
13653        final int NR = receivers.size();
13654        for (int i = 0; i < NR; i++) {
13655            final ResolveInfo info = receivers.get(i);
13656            if (info.activityInfo == null) {
13657                continue;
13658            }
13659
13660            if (packageName.equals(info.activityInfo.packageName)) {
13661                targetReceiver = info.activityInfo;
13662                break;
13663            }
13664        }
13665
13666        if (targetReceiver == null) {
13667            return null;
13668        }
13669
13670        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13671    }
13672
13673    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13674            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13675        if (pkgInfo.verifiers.length == 0) {
13676            return null;
13677        }
13678
13679        final int N = pkgInfo.verifiers.length;
13680        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13681        for (int i = 0; i < N; i++) {
13682            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13683
13684            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13685                    receivers);
13686            if (comp == null) {
13687                continue;
13688            }
13689
13690            final int verifierUid = getUidForVerifier(verifierInfo);
13691            if (verifierUid == -1) {
13692                continue;
13693            }
13694
13695            if (DEBUG_VERIFY) {
13696                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13697                        + " with the correct signature");
13698            }
13699            sufficientVerifiers.add(comp);
13700            verificationState.addSufficientVerifier(verifierUid);
13701        }
13702
13703        return sufficientVerifiers;
13704    }
13705
13706    private int getUidForVerifier(VerifierInfo verifierInfo) {
13707        synchronized (mPackages) {
13708            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13709            if (pkg == null) {
13710                return -1;
13711            } else if (pkg.mSignatures.length != 1) {
13712                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13713                        + " has more than one signature; ignoring");
13714                return -1;
13715            }
13716
13717            /*
13718             * If the public key of the package's signature does not match
13719             * our expected public key, then this is a different package and
13720             * we should skip.
13721             */
13722
13723            final byte[] expectedPublicKey;
13724            try {
13725                final Signature verifierSig = pkg.mSignatures[0];
13726                final PublicKey publicKey = verifierSig.getPublicKey();
13727                expectedPublicKey = publicKey.getEncoded();
13728            } catch (CertificateException e) {
13729                return -1;
13730            }
13731
13732            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13733
13734            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13735                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13736                        + " does not have the expected public key; ignoring");
13737                return -1;
13738            }
13739
13740            return pkg.applicationInfo.uid;
13741        }
13742    }
13743
13744    @Override
13745    public void finishPackageInstall(int token, boolean didLaunch) {
13746        enforceSystemOrRoot("Only the system is allowed to finish installs");
13747
13748        if (DEBUG_INSTALL) {
13749            Slog.v(TAG, "BM finishing package install for " + token);
13750        }
13751        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13752
13753        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13754        mHandler.sendMessage(msg);
13755    }
13756
13757    /**
13758     * Get the verification agent timeout.
13759     *
13760     * @return verification timeout in milliseconds
13761     */
13762    private long getVerificationTimeout() {
13763        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13764                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13765                DEFAULT_VERIFICATION_TIMEOUT);
13766    }
13767
13768    /**
13769     * Get the default verification agent response code.
13770     *
13771     * @return default verification response code
13772     */
13773    private int getDefaultVerificationResponse() {
13774        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13775                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13776                DEFAULT_VERIFICATION_RESPONSE);
13777    }
13778
13779    /**
13780     * Check whether or not package verification has been enabled.
13781     *
13782     * @return true if verification should be performed
13783     */
13784    private boolean isVerificationEnabled(int userId, int installFlags) {
13785        if (!DEFAULT_VERIFY_ENABLE) {
13786            return false;
13787        }
13788
13789        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13790
13791        // Check if installing from ADB
13792        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13793            // Do not run verification in a test harness environment
13794            if (ActivityManager.isRunningInTestHarness()) {
13795                return false;
13796            }
13797            if (ensureVerifyAppsEnabled) {
13798                return true;
13799            }
13800            // Check if the developer does not want package verification for ADB installs
13801            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13802                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13803                return false;
13804            }
13805        }
13806
13807        if (ensureVerifyAppsEnabled) {
13808            return true;
13809        }
13810
13811        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13812                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13813    }
13814
13815    @Override
13816    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13817            throws RemoteException {
13818        mContext.enforceCallingOrSelfPermission(
13819                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13820                "Only intentfilter verification agents can verify applications");
13821
13822        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13823        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13824                Binder.getCallingUid(), verificationCode, failedDomains);
13825        msg.arg1 = id;
13826        msg.obj = response;
13827        mHandler.sendMessage(msg);
13828    }
13829
13830    @Override
13831    public int getIntentVerificationStatus(String packageName, int userId) {
13832        synchronized (mPackages) {
13833            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13834        }
13835    }
13836
13837    @Override
13838    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13839        mContext.enforceCallingOrSelfPermission(
13840                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13841
13842        boolean result = false;
13843        synchronized (mPackages) {
13844            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13845        }
13846        if (result) {
13847            scheduleWritePackageRestrictionsLocked(userId);
13848        }
13849        return result;
13850    }
13851
13852    @Override
13853    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13854            String packageName) {
13855        synchronized (mPackages) {
13856            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13857        }
13858    }
13859
13860    @Override
13861    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13862        if (TextUtils.isEmpty(packageName)) {
13863            return ParceledListSlice.emptyList();
13864        }
13865        synchronized (mPackages) {
13866            PackageParser.Package pkg = mPackages.get(packageName);
13867            if (pkg == null || pkg.activities == null) {
13868                return ParceledListSlice.emptyList();
13869            }
13870            final int count = pkg.activities.size();
13871            ArrayList<IntentFilter> result = new ArrayList<>();
13872            for (int n=0; n<count; n++) {
13873                PackageParser.Activity activity = pkg.activities.get(n);
13874                if (activity.intents != null && activity.intents.size() > 0) {
13875                    result.addAll(activity.intents);
13876                }
13877            }
13878            return new ParceledListSlice<>(result);
13879        }
13880    }
13881
13882    @Override
13883    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13884        mContext.enforceCallingOrSelfPermission(
13885                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13886
13887        synchronized (mPackages) {
13888            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13889            if (packageName != null) {
13890                result |= updateIntentVerificationStatus(packageName,
13891                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13892                        userId);
13893                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13894                        packageName, userId);
13895            }
13896            return result;
13897        }
13898    }
13899
13900    @Override
13901    public String getDefaultBrowserPackageName(int userId) {
13902        synchronized (mPackages) {
13903            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13904        }
13905    }
13906
13907    /**
13908     * Get the "allow unknown sources" setting.
13909     *
13910     * @return the current "allow unknown sources" setting
13911     */
13912    private int getUnknownSourcesSettings() {
13913        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13914                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13915                -1);
13916    }
13917
13918    @Override
13919    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13920        final int uid = Binder.getCallingUid();
13921        // writer
13922        synchronized (mPackages) {
13923            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13924            if (targetPackageSetting == null) {
13925                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13926            }
13927
13928            PackageSetting installerPackageSetting;
13929            if (installerPackageName != null) {
13930                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13931                if (installerPackageSetting == null) {
13932                    throw new IllegalArgumentException("Unknown installer package: "
13933                            + installerPackageName);
13934                }
13935            } else {
13936                installerPackageSetting = null;
13937            }
13938
13939            Signature[] callerSignature;
13940            Object obj = mSettings.getUserIdLPr(uid);
13941            if (obj != null) {
13942                if (obj instanceof SharedUserSetting) {
13943                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13944                } else if (obj instanceof PackageSetting) {
13945                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13946                } else {
13947                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13948                }
13949            } else {
13950                throw new SecurityException("Unknown calling UID: " + uid);
13951            }
13952
13953            // Verify: can't set installerPackageName to a package that is
13954            // not signed with the same cert as the caller.
13955            if (installerPackageSetting != null) {
13956                if (compareSignatures(callerSignature,
13957                        installerPackageSetting.signatures.mSignatures)
13958                        != PackageManager.SIGNATURE_MATCH) {
13959                    throw new SecurityException(
13960                            "Caller does not have same cert as new installer package "
13961                            + installerPackageName);
13962                }
13963            }
13964
13965            // Verify: if target already has an installer package, it must
13966            // be signed with the same cert as the caller.
13967            if (targetPackageSetting.installerPackageName != null) {
13968                PackageSetting setting = mSettings.mPackages.get(
13969                        targetPackageSetting.installerPackageName);
13970                // If the currently set package isn't valid, then it's always
13971                // okay to change it.
13972                if (setting != null) {
13973                    if (compareSignatures(callerSignature,
13974                            setting.signatures.mSignatures)
13975                            != PackageManager.SIGNATURE_MATCH) {
13976                        throw new SecurityException(
13977                                "Caller does not have same cert as old installer package "
13978                                + targetPackageSetting.installerPackageName);
13979                    }
13980                }
13981            }
13982
13983            // Okay!
13984            targetPackageSetting.installerPackageName = installerPackageName;
13985            if (installerPackageName != null) {
13986                mSettings.mInstallerPackages.add(installerPackageName);
13987            }
13988            scheduleWriteSettingsLocked();
13989        }
13990    }
13991
13992    @Override
13993    public void setApplicationCategoryHint(String packageName, int categoryHint,
13994            String callerPackageName) {
13995        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13996                callerPackageName);
13997        synchronized (mPackages) {
13998            PackageSetting ps = mSettings.mPackages.get(packageName);
13999            if (ps == null) {
14000                throw new IllegalArgumentException("Unknown target package " + packageName);
14001            }
14002
14003            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14004                throw new IllegalArgumentException("Calling package " + callerPackageName
14005                        + " is not installer for " + packageName);
14006            }
14007
14008            if (ps.categoryHint != categoryHint) {
14009                ps.categoryHint = categoryHint;
14010                scheduleWriteSettingsLocked();
14011            }
14012        }
14013    }
14014
14015    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14016        // Queue up an async operation since the package installation may take a little while.
14017        mHandler.post(new Runnable() {
14018            public void run() {
14019                mHandler.removeCallbacks(this);
14020                 // Result object to be returned
14021                PackageInstalledInfo res = new PackageInstalledInfo();
14022                res.setReturnCode(currentStatus);
14023                res.uid = -1;
14024                res.pkg = null;
14025                res.removedInfo = null;
14026                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14027                    args.doPreInstall(res.returnCode);
14028                    synchronized (mInstallLock) {
14029                        installPackageTracedLI(args, res);
14030                    }
14031                    args.doPostInstall(res.returnCode, res.uid);
14032                }
14033
14034                // A restore should be performed at this point if (a) the install
14035                // succeeded, (b) the operation is not an update, and (c) the new
14036                // package has not opted out of backup participation.
14037                final boolean update = res.removedInfo != null
14038                        && res.removedInfo.removedPackage != null;
14039                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14040                boolean doRestore = !update
14041                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14042
14043                // Set up the post-install work request bookkeeping.  This will be used
14044                // and cleaned up by the post-install event handling regardless of whether
14045                // there's a restore pass performed.  Token values are >= 1.
14046                int token;
14047                if (mNextInstallToken < 0) mNextInstallToken = 1;
14048                token = mNextInstallToken++;
14049
14050                PostInstallData data = new PostInstallData(args, res);
14051                mRunningInstalls.put(token, data);
14052                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14053
14054                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14055                    // Pass responsibility to the Backup Manager.  It will perform a
14056                    // restore if appropriate, then pass responsibility back to the
14057                    // Package Manager to run the post-install observer callbacks
14058                    // and broadcasts.
14059                    IBackupManager bm = IBackupManager.Stub.asInterface(
14060                            ServiceManager.getService(Context.BACKUP_SERVICE));
14061                    if (bm != null) {
14062                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14063                                + " to BM for possible restore");
14064                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14065                        try {
14066                            // TODO: http://b/22388012
14067                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14068                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14069                            } else {
14070                                doRestore = false;
14071                            }
14072                        } catch (RemoteException e) {
14073                            // can't happen; the backup manager is local
14074                        } catch (Exception e) {
14075                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14076                            doRestore = false;
14077                        }
14078                    } else {
14079                        Slog.e(TAG, "Backup Manager not found!");
14080                        doRestore = false;
14081                    }
14082                }
14083
14084                if (!doRestore) {
14085                    // No restore possible, or the Backup Manager was mysteriously not
14086                    // available -- just fire the post-install work request directly.
14087                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14088
14089                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14090
14091                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14092                    mHandler.sendMessage(msg);
14093                }
14094            }
14095        });
14096    }
14097
14098    /**
14099     * Callback from PackageSettings whenever an app is first transitioned out of the
14100     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14101     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14102     * here whether the app is the target of an ongoing install, and only send the
14103     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14104     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14105     * handling.
14106     */
14107    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14108        // Serialize this with the rest of the install-process message chain.  In the
14109        // restore-at-install case, this Runnable will necessarily run before the
14110        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14111        // are coherent.  In the non-restore case, the app has already completed install
14112        // and been launched through some other means, so it is not in a problematic
14113        // state for observers to see the FIRST_LAUNCH signal.
14114        mHandler.post(new Runnable() {
14115            @Override
14116            public void run() {
14117                for (int i = 0; i < mRunningInstalls.size(); i++) {
14118                    final PostInstallData data = mRunningInstalls.valueAt(i);
14119                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14120                        continue;
14121                    }
14122                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14123                        // right package; but is it for the right user?
14124                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14125                            if (userId == data.res.newUsers[uIndex]) {
14126                                if (DEBUG_BACKUP) {
14127                                    Slog.i(TAG, "Package " + pkgName
14128                                            + " being restored so deferring FIRST_LAUNCH");
14129                                }
14130                                return;
14131                            }
14132                        }
14133                    }
14134                }
14135                // didn't find it, so not being restored
14136                if (DEBUG_BACKUP) {
14137                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14138                }
14139                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14140            }
14141        });
14142    }
14143
14144    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14145        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14146                installerPkg, null, userIds);
14147    }
14148
14149    private abstract class HandlerParams {
14150        private static final int MAX_RETRIES = 4;
14151
14152        /**
14153         * Number of times startCopy() has been attempted and had a non-fatal
14154         * error.
14155         */
14156        private int mRetries = 0;
14157
14158        /** User handle for the user requesting the information or installation. */
14159        private final UserHandle mUser;
14160        String traceMethod;
14161        int traceCookie;
14162
14163        HandlerParams(UserHandle user) {
14164            mUser = user;
14165        }
14166
14167        UserHandle getUser() {
14168            return mUser;
14169        }
14170
14171        HandlerParams setTraceMethod(String traceMethod) {
14172            this.traceMethod = traceMethod;
14173            return this;
14174        }
14175
14176        HandlerParams setTraceCookie(int traceCookie) {
14177            this.traceCookie = traceCookie;
14178            return this;
14179        }
14180
14181        final boolean startCopy() {
14182            boolean res;
14183            try {
14184                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14185
14186                if (++mRetries > MAX_RETRIES) {
14187                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14188                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14189                    handleServiceError();
14190                    return false;
14191                } else {
14192                    handleStartCopy();
14193                    res = true;
14194                }
14195            } catch (RemoteException e) {
14196                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14197                mHandler.sendEmptyMessage(MCS_RECONNECT);
14198                res = false;
14199            }
14200            handleReturnCode();
14201            return res;
14202        }
14203
14204        final void serviceError() {
14205            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14206            handleServiceError();
14207            handleReturnCode();
14208        }
14209
14210        abstract void handleStartCopy() throws RemoteException;
14211        abstract void handleServiceError();
14212        abstract void handleReturnCode();
14213    }
14214
14215    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14216        for (File path : paths) {
14217            try {
14218                mcs.clearDirectory(path.getAbsolutePath());
14219            } catch (RemoteException e) {
14220            }
14221        }
14222    }
14223
14224    static class OriginInfo {
14225        /**
14226         * Location where install is coming from, before it has been
14227         * copied/renamed into place. This could be a single monolithic APK
14228         * file, or a cluster directory. This location may be untrusted.
14229         */
14230        final File file;
14231        final String cid;
14232
14233        /**
14234         * Flag indicating that {@link #file} or {@link #cid} has already been
14235         * staged, meaning downstream users don't need to defensively copy the
14236         * contents.
14237         */
14238        final boolean staged;
14239
14240        /**
14241         * Flag indicating that {@link #file} or {@link #cid} is an already
14242         * installed app that is being moved.
14243         */
14244        final boolean existing;
14245
14246        final String resolvedPath;
14247        final File resolvedFile;
14248
14249        static OriginInfo fromNothing() {
14250            return new OriginInfo(null, null, false, false);
14251        }
14252
14253        static OriginInfo fromUntrustedFile(File file) {
14254            return new OriginInfo(file, null, false, false);
14255        }
14256
14257        static OriginInfo fromExistingFile(File file) {
14258            return new OriginInfo(file, null, false, true);
14259        }
14260
14261        static OriginInfo fromStagedFile(File file) {
14262            return new OriginInfo(file, null, true, false);
14263        }
14264
14265        static OriginInfo fromStagedContainer(String cid) {
14266            return new OriginInfo(null, cid, true, false);
14267        }
14268
14269        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14270            this.file = file;
14271            this.cid = cid;
14272            this.staged = staged;
14273            this.existing = existing;
14274
14275            if (cid != null) {
14276                resolvedPath = PackageHelper.getSdDir(cid);
14277                resolvedFile = new File(resolvedPath);
14278            } else if (file != null) {
14279                resolvedPath = file.getAbsolutePath();
14280                resolvedFile = file;
14281            } else {
14282                resolvedPath = null;
14283                resolvedFile = null;
14284            }
14285        }
14286    }
14287
14288    static class MoveInfo {
14289        final int moveId;
14290        final String fromUuid;
14291        final String toUuid;
14292        final String packageName;
14293        final String dataAppName;
14294        final int appId;
14295        final String seinfo;
14296        final int targetSdkVersion;
14297
14298        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14299                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14300            this.moveId = moveId;
14301            this.fromUuid = fromUuid;
14302            this.toUuid = toUuid;
14303            this.packageName = packageName;
14304            this.dataAppName = dataAppName;
14305            this.appId = appId;
14306            this.seinfo = seinfo;
14307            this.targetSdkVersion = targetSdkVersion;
14308        }
14309    }
14310
14311    static class VerificationInfo {
14312        /** A constant used to indicate that a uid value is not present. */
14313        public static final int NO_UID = -1;
14314
14315        /** URI referencing where the package was downloaded from. */
14316        final Uri originatingUri;
14317
14318        /** HTTP referrer URI associated with the originatingURI. */
14319        final Uri referrer;
14320
14321        /** UID of the application that the install request originated from. */
14322        final int originatingUid;
14323
14324        /** UID of application requesting the install */
14325        final int installerUid;
14326
14327        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14328            this.originatingUri = originatingUri;
14329            this.referrer = referrer;
14330            this.originatingUid = originatingUid;
14331            this.installerUid = installerUid;
14332        }
14333    }
14334
14335    class InstallParams extends HandlerParams {
14336        final OriginInfo origin;
14337        final MoveInfo move;
14338        final IPackageInstallObserver2 observer;
14339        int installFlags;
14340        final String installerPackageName;
14341        final String volumeUuid;
14342        private InstallArgs mArgs;
14343        private int mRet;
14344        final String packageAbiOverride;
14345        final String[] grantedRuntimePermissions;
14346        final VerificationInfo verificationInfo;
14347        final Certificate[][] certificates;
14348        final int installReason;
14349
14350        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14351                int installFlags, String installerPackageName, String volumeUuid,
14352                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14353                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14354            super(user);
14355            this.origin = origin;
14356            this.move = move;
14357            this.observer = observer;
14358            this.installFlags = installFlags;
14359            this.installerPackageName = installerPackageName;
14360            this.volumeUuid = volumeUuid;
14361            this.verificationInfo = verificationInfo;
14362            this.packageAbiOverride = packageAbiOverride;
14363            this.grantedRuntimePermissions = grantedPermissions;
14364            this.certificates = certificates;
14365            this.installReason = installReason;
14366        }
14367
14368        @Override
14369        public String toString() {
14370            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14371                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14372        }
14373
14374        private int installLocationPolicy(PackageInfoLite pkgLite) {
14375            String packageName = pkgLite.packageName;
14376            int installLocation = pkgLite.installLocation;
14377            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14378            // reader
14379            synchronized (mPackages) {
14380                // Currently installed package which the new package is attempting to replace or
14381                // null if no such package is installed.
14382                PackageParser.Package installedPkg = mPackages.get(packageName);
14383                // Package which currently owns the data which the new package will own if installed.
14384                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14385                // will be null whereas dataOwnerPkg will contain information about the package
14386                // which was uninstalled while keeping its data.
14387                PackageParser.Package dataOwnerPkg = installedPkg;
14388                if (dataOwnerPkg  == null) {
14389                    PackageSetting ps = mSettings.mPackages.get(packageName);
14390                    if (ps != null) {
14391                        dataOwnerPkg = ps.pkg;
14392                    }
14393                }
14394
14395                if (dataOwnerPkg != null) {
14396                    // If installed, the package will get access to data left on the device by its
14397                    // predecessor. As a security measure, this is permited only if this is not a
14398                    // version downgrade or if the predecessor package is marked as debuggable and
14399                    // a downgrade is explicitly requested.
14400                    //
14401                    // On debuggable platform builds, downgrades are permitted even for
14402                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14403                    // not offer security guarantees and thus it's OK to disable some security
14404                    // mechanisms to make debugging/testing easier on those builds. However, even on
14405                    // debuggable builds downgrades of packages are permitted only if requested via
14406                    // installFlags. This is because we aim to keep the behavior of debuggable
14407                    // platform builds as close as possible to the behavior of non-debuggable
14408                    // platform builds.
14409                    final boolean downgradeRequested =
14410                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14411                    final boolean packageDebuggable =
14412                                (dataOwnerPkg.applicationInfo.flags
14413                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14414                    final boolean downgradePermitted =
14415                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14416                    if (!downgradePermitted) {
14417                        try {
14418                            checkDowngrade(dataOwnerPkg, pkgLite);
14419                        } catch (PackageManagerException e) {
14420                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14421                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14422                        }
14423                    }
14424                }
14425
14426                if (installedPkg != null) {
14427                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14428                        // Check for updated system application.
14429                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14430                            if (onSd) {
14431                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14432                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14433                            }
14434                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14435                        } else {
14436                            if (onSd) {
14437                                // Install flag overrides everything.
14438                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14439                            }
14440                            // If current upgrade specifies particular preference
14441                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14442                                // Application explicitly specified internal.
14443                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14444                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14445                                // App explictly prefers external. Let policy decide
14446                            } else {
14447                                // Prefer previous location
14448                                if (isExternal(installedPkg)) {
14449                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14450                                }
14451                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14452                            }
14453                        }
14454                    } else {
14455                        // Invalid install. Return error code
14456                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14457                    }
14458                }
14459            }
14460            // All the special cases have been taken care of.
14461            // Return result based on recommended install location.
14462            if (onSd) {
14463                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14464            }
14465            return pkgLite.recommendedInstallLocation;
14466        }
14467
14468        /*
14469         * Invoke remote method to get package information and install
14470         * location values. Override install location based on default
14471         * policy if needed and then create install arguments based
14472         * on the install location.
14473         */
14474        public void handleStartCopy() throws RemoteException {
14475            int ret = PackageManager.INSTALL_SUCCEEDED;
14476
14477            // If we're already staged, we've firmly committed to an install location
14478            if (origin.staged) {
14479                if (origin.file != null) {
14480                    installFlags |= PackageManager.INSTALL_INTERNAL;
14481                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14482                } else if (origin.cid != null) {
14483                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14484                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14485                } else {
14486                    throw new IllegalStateException("Invalid stage location");
14487                }
14488            }
14489
14490            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14491            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14492            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14493            PackageInfoLite pkgLite = null;
14494
14495            if (onInt && onSd) {
14496                // Check if both bits are set.
14497                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14498                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14499            } else if (onSd && ephemeral) {
14500                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14501                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14502            } else {
14503                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14504                        packageAbiOverride);
14505
14506                if (DEBUG_EPHEMERAL && ephemeral) {
14507                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14508                }
14509
14510                /*
14511                 * If we have too little free space, try to free cache
14512                 * before giving up.
14513                 */
14514                if (!origin.staged && pkgLite.recommendedInstallLocation
14515                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14516                    // TODO: focus freeing disk space on the target device
14517                    final StorageManager storage = StorageManager.from(mContext);
14518                    final long lowThreshold = storage.getStorageLowBytes(
14519                            Environment.getDataDirectory());
14520
14521                    final long sizeBytes = mContainerService.calculateInstalledSize(
14522                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14523
14524                    try {
14525                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14526                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14527                                installFlags, packageAbiOverride);
14528                    } catch (InstallerException e) {
14529                        Slog.w(TAG, "Failed to free cache", e);
14530                    }
14531
14532                    /*
14533                     * The cache free must have deleted the file we
14534                     * downloaded to install.
14535                     *
14536                     * TODO: fix the "freeCache" call to not delete
14537                     *       the file we care about.
14538                     */
14539                    if (pkgLite.recommendedInstallLocation
14540                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14541                        pkgLite.recommendedInstallLocation
14542                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14543                    }
14544                }
14545            }
14546
14547            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14548                int loc = pkgLite.recommendedInstallLocation;
14549                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14550                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14551                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14552                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14553                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14554                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14555                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14556                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14557                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14558                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14559                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14560                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14561                } else {
14562                    // Override with defaults if needed.
14563                    loc = installLocationPolicy(pkgLite);
14564                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14565                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14566                    } else if (!onSd && !onInt) {
14567                        // Override install location with flags
14568                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14569                            // Set the flag to install on external media.
14570                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14571                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14572                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14573                            if (DEBUG_EPHEMERAL) {
14574                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14575                            }
14576                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14577                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14578                                    |PackageManager.INSTALL_INTERNAL);
14579                        } else {
14580                            // Make sure the flag for installing on external
14581                            // media is unset
14582                            installFlags |= PackageManager.INSTALL_INTERNAL;
14583                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14584                        }
14585                    }
14586                }
14587            }
14588
14589            final InstallArgs args = createInstallArgs(this);
14590            mArgs = args;
14591
14592            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14593                // TODO: http://b/22976637
14594                // Apps installed for "all" users use the device owner to verify the app
14595                UserHandle verifierUser = getUser();
14596                if (verifierUser == UserHandle.ALL) {
14597                    verifierUser = UserHandle.SYSTEM;
14598                }
14599
14600                /*
14601                 * Determine if we have any installed package verifiers. If we
14602                 * do, then we'll defer to them to verify the packages.
14603                 */
14604                final int requiredUid = mRequiredVerifierPackage == null ? -1
14605                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14606                                verifierUser.getIdentifier());
14607                if (!origin.existing && requiredUid != -1
14608                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14609                    final Intent verification = new Intent(
14610                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14611                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14612                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14613                            PACKAGE_MIME_TYPE);
14614                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14615
14616                    // Query all live verifiers based on current user state
14617                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14618                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14619
14620                    if (DEBUG_VERIFY) {
14621                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14622                                + verification.toString() + " with " + pkgLite.verifiers.length
14623                                + " optional verifiers");
14624                    }
14625
14626                    final int verificationId = mPendingVerificationToken++;
14627
14628                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14629
14630                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14631                            installerPackageName);
14632
14633                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14634                            installFlags);
14635
14636                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14637                            pkgLite.packageName);
14638
14639                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14640                            pkgLite.versionCode);
14641
14642                    if (verificationInfo != null) {
14643                        if (verificationInfo.originatingUri != null) {
14644                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14645                                    verificationInfo.originatingUri);
14646                        }
14647                        if (verificationInfo.referrer != null) {
14648                            verification.putExtra(Intent.EXTRA_REFERRER,
14649                                    verificationInfo.referrer);
14650                        }
14651                        if (verificationInfo.originatingUid >= 0) {
14652                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14653                                    verificationInfo.originatingUid);
14654                        }
14655                        if (verificationInfo.installerUid >= 0) {
14656                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14657                                    verificationInfo.installerUid);
14658                        }
14659                    }
14660
14661                    final PackageVerificationState verificationState = new PackageVerificationState(
14662                            requiredUid, args);
14663
14664                    mPendingVerification.append(verificationId, verificationState);
14665
14666                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14667                            receivers, verificationState);
14668
14669                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14670                    final long idleDuration = getVerificationTimeout();
14671
14672                    /*
14673                     * If any sufficient verifiers were listed in the package
14674                     * manifest, attempt to ask them.
14675                     */
14676                    if (sufficientVerifiers != null) {
14677                        final int N = sufficientVerifiers.size();
14678                        if (N == 0) {
14679                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14680                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14681                        } else {
14682                            for (int i = 0; i < N; i++) {
14683                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14684                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14685                                        verifierComponent.getPackageName(), idleDuration,
14686                                        verifierUser.getIdentifier(), false, "package verifier");
14687
14688                                final Intent sufficientIntent = new Intent(verification);
14689                                sufficientIntent.setComponent(verifierComponent);
14690                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14691                            }
14692                        }
14693                    }
14694
14695                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14696                            mRequiredVerifierPackage, receivers);
14697                    if (ret == PackageManager.INSTALL_SUCCEEDED
14698                            && mRequiredVerifierPackage != null) {
14699                        Trace.asyncTraceBegin(
14700                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14701                        /*
14702                         * Send the intent to the required verification agent,
14703                         * but only start the verification timeout after the
14704                         * target BroadcastReceivers have run.
14705                         */
14706                        verification.setComponent(requiredVerifierComponent);
14707                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14708                                mRequiredVerifierPackage, idleDuration,
14709                                verifierUser.getIdentifier(), false, "package verifier");
14710                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14711                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14712                                new BroadcastReceiver() {
14713                                    @Override
14714                                    public void onReceive(Context context, Intent intent) {
14715                                        final Message msg = mHandler
14716                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14717                                        msg.arg1 = verificationId;
14718                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14719                                    }
14720                                }, null, 0, null, null);
14721
14722                        /*
14723                         * We don't want the copy to proceed until verification
14724                         * succeeds, so null out this field.
14725                         */
14726                        mArgs = null;
14727                    }
14728                } else {
14729                    /*
14730                     * No package verification is enabled, so immediately start
14731                     * the remote call to initiate copy using temporary file.
14732                     */
14733                    ret = args.copyApk(mContainerService, true);
14734                }
14735            }
14736
14737            mRet = ret;
14738        }
14739
14740        @Override
14741        void handleReturnCode() {
14742            // If mArgs is null, then MCS couldn't be reached. When it
14743            // reconnects, it will try again to install. At that point, this
14744            // will succeed.
14745            if (mArgs != null) {
14746                processPendingInstall(mArgs, mRet);
14747            }
14748        }
14749
14750        @Override
14751        void handleServiceError() {
14752            mArgs = createInstallArgs(this);
14753            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14754        }
14755
14756        public boolean isForwardLocked() {
14757            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14758        }
14759    }
14760
14761    /**
14762     * Used during creation of InstallArgs
14763     *
14764     * @param installFlags package installation flags
14765     * @return true if should be installed on external storage
14766     */
14767    private static boolean installOnExternalAsec(int installFlags) {
14768        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14769            return false;
14770        }
14771        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14772            return true;
14773        }
14774        return false;
14775    }
14776
14777    /**
14778     * Used during creation of InstallArgs
14779     *
14780     * @param installFlags package installation flags
14781     * @return true if should be installed as forward locked
14782     */
14783    private static boolean installForwardLocked(int installFlags) {
14784        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14785    }
14786
14787    private InstallArgs createInstallArgs(InstallParams params) {
14788        if (params.move != null) {
14789            return new MoveInstallArgs(params);
14790        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14791            return new AsecInstallArgs(params);
14792        } else {
14793            return new FileInstallArgs(params);
14794        }
14795    }
14796
14797    /**
14798     * Create args that describe an existing installed package. Typically used
14799     * when cleaning up old installs, or used as a move source.
14800     */
14801    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14802            String resourcePath, String[] instructionSets) {
14803        final boolean isInAsec;
14804        if (installOnExternalAsec(installFlags)) {
14805            /* Apps on SD card are always in ASEC containers. */
14806            isInAsec = true;
14807        } else if (installForwardLocked(installFlags)
14808                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14809            /*
14810             * Forward-locked apps are only in ASEC containers if they're the
14811             * new style
14812             */
14813            isInAsec = true;
14814        } else {
14815            isInAsec = false;
14816        }
14817
14818        if (isInAsec) {
14819            return new AsecInstallArgs(codePath, instructionSets,
14820                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14821        } else {
14822            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14823        }
14824    }
14825
14826    static abstract class InstallArgs {
14827        /** @see InstallParams#origin */
14828        final OriginInfo origin;
14829        /** @see InstallParams#move */
14830        final MoveInfo move;
14831
14832        final IPackageInstallObserver2 observer;
14833        // Always refers to PackageManager flags only
14834        final int installFlags;
14835        final String installerPackageName;
14836        final String volumeUuid;
14837        final UserHandle user;
14838        final String abiOverride;
14839        final String[] installGrantPermissions;
14840        /** If non-null, drop an async trace when the install completes */
14841        final String traceMethod;
14842        final int traceCookie;
14843        final Certificate[][] certificates;
14844        final int installReason;
14845
14846        // The list of instruction sets supported by this app. This is currently
14847        // only used during the rmdex() phase to clean up resources. We can get rid of this
14848        // if we move dex files under the common app path.
14849        /* nullable */ String[] instructionSets;
14850
14851        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14852                int installFlags, String installerPackageName, String volumeUuid,
14853                UserHandle user, String[] instructionSets,
14854                String abiOverride, String[] installGrantPermissions,
14855                String traceMethod, int traceCookie, Certificate[][] certificates,
14856                int installReason) {
14857            this.origin = origin;
14858            this.move = move;
14859            this.installFlags = installFlags;
14860            this.observer = observer;
14861            this.installerPackageName = installerPackageName;
14862            this.volumeUuid = volumeUuid;
14863            this.user = user;
14864            this.instructionSets = instructionSets;
14865            this.abiOverride = abiOverride;
14866            this.installGrantPermissions = installGrantPermissions;
14867            this.traceMethod = traceMethod;
14868            this.traceCookie = traceCookie;
14869            this.certificates = certificates;
14870            this.installReason = installReason;
14871        }
14872
14873        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14874        abstract int doPreInstall(int status);
14875
14876        /**
14877         * Rename package into final resting place. All paths on the given
14878         * scanned package should be updated to reflect the rename.
14879         */
14880        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14881        abstract int doPostInstall(int status, int uid);
14882
14883        /** @see PackageSettingBase#codePathString */
14884        abstract String getCodePath();
14885        /** @see PackageSettingBase#resourcePathString */
14886        abstract String getResourcePath();
14887
14888        // Need installer lock especially for dex file removal.
14889        abstract void cleanUpResourcesLI();
14890        abstract boolean doPostDeleteLI(boolean delete);
14891
14892        /**
14893         * Called before the source arguments are copied. This is used mostly
14894         * for MoveParams when it needs to read the source file to put it in the
14895         * destination.
14896         */
14897        int doPreCopy() {
14898            return PackageManager.INSTALL_SUCCEEDED;
14899        }
14900
14901        /**
14902         * Called after the source arguments are copied. This is used mostly for
14903         * MoveParams when it needs to read the source file to put it in the
14904         * destination.
14905         */
14906        int doPostCopy(int uid) {
14907            return PackageManager.INSTALL_SUCCEEDED;
14908        }
14909
14910        protected boolean isFwdLocked() {
14911            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14912        }
14913
14914        protected boolean isExternalAsec() {
14915            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14916        }
14917
14918        protected boolean isEphemeral() {
14919            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14920        }
14921
14922        UserHandle getUser() {
14923            return user;
14924        }
14925    }
14926
14927    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14928        if (!allCodePaths.isEmpty()) {
14929            if (instructionSets == null) {
14930                throw new IllegalStateException("instructionSet == null");
14931            }
14932            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14933            for (String codePath : allCodePaths) {
14934                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14935                    try {
14936                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14937                    } catch (InstallerException ignored) {
14938                    }
14939                }
14940            }
14941        }
14942    }
14943
14944    /**
14945     * Logic to handle installation of non-ASEC applications, including copying
14946     * and renaming logic.
14947     */
14948    class FileInstallArgs extends InstallArgs {
14949        private File codeFile;
14950        private File resourceFile;
14951
14952        // Example topology:
14953        // /data/app/com.example/base.apk
14954        // /data/app/com.example/split_foo.apk
14955        // /data/app/com.example/lib/arm/libfoo.so
14956        // /data/app/com.example/lib/arm64/libfoo.so
14957        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14958
14959        /** New install */
14960        FileInstallArgs(InstallParams params) {
14961            super(params.origin, params.move, params.observer, params.installFlags,
14962                    params.installerPackageName, params.volumeUuid,
14963                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14964                    params.grantedRuntimePermissions,
14965                    params.traceMethod, params.traceCookie, params.certificates,
14966                    params.installReason);
14967            if (isFwdLocked()) {
14968                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14969            }
14970        }
14971
14972        /** Existing install */
14973        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14974            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14975                    null, null, null, 0, null /*certificates*/,
14976                    PackageManager.INSTALL_REASON_UNKNOWN);
14977            this.codeFile = (codePath != null) ? new File(codePath) : null;
14978            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14979        }
14980
14981        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14982            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14983            try {
14984                return doCopyApk(imcs, temp);
14985            } finally {
14986                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14987            }
14988        }
14989
14990        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14991            if (origin.staged) {
14992                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14993                codeFile = origin.file;
14994                resourceFile = origin.file;
14995                return PackageManager.INSTALL_SUCCEEDED;
14996            }
14997
14998            try {
14999                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15000                final File tempDir =
15001                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15002                codeFile = tempDir;
15003                resourceFile = tempDir;
15004            } catch (IOException e) {
15005                Slog.w(TAG, "Failed to create copy file: " + e);
15006                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15007            }
15008
15009            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15010                @Override
15011                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15012                    if (!FileUtils.isValidExtFilename(name)) {
15013                        throw new IllegalArgumentException("Invalid filename: " + name);
15014                    }
15015                    try {
15016                        final File file = new File(codeFile, name);
15017                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15018                                O_RDWR | O_CREAT, 0644);
15019                        Os.chmod(file.getAbsolutePath(), 0644);
15020                        return new ParcelFileDescriptor(fd);
15021                    } catch (ErrnoException e) {
15022                        throw new RemoteException("Failed to open: " + e.getMessage());
15023                    }
15024                }
15025            };
15026
15027            int ret = PackageManager.INSTALL_SUCCEEDED;
15028            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15029            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15030                Slog.e(TAG, "Failed to copy package");
15031                return ret;
15032            }
15033
15034            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15035            NativeLibraryHelper.Handle handle = null;
15036            try {
15037                handle = NativeLibraryHelper.Handle.create(codeFile);
15038                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15039                        abiOverride);
15040            } catch (IOException e) {
15041                Slog.e(TAG, "Copying native libraries failed", e);
15042                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15043            } finally {
15044                IoUtils.closeQuietly(handle);
15045            }
15046
15047            return ret;
15048        }
15049
15050        int doPreInstall(int status) {
15051            if (status != PackageManager.INSTALL_SUCCEEDED) {
15052                cleanUp();
15053            }
15054            return status;
15055        }
15056
15057        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15058            if (status != PackageManager.INSTALL_SUCCEEDED) {
15059                cleanUp();
15060                return false;
15061            }
15062
15063            final File targetDir = codeFile.getParentFile();
15064            final File beforeCodeFile = codeFile;
15065            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15066
15067            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15068            try {
15069                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15070            } catch (ErrnoException e) {
15071                Slog.w(TAG, "Failed to rename", e);
15072                return false;
15073            }
15074
15075            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15076                Slog.w(TAG, "Failed to restorecon");
15077                return false;
15078            }
15079
15080            // Reflect the rename internally
15081            codeFile = afterCodeFile;
15082            resourceFile = afterCodeFile;
15083
15084            // Reflect the rename in scanned details
15085            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15086            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15087                    afterCodeFile, pkg.baseCodePath));
15088            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15089                    afterCodeFile, pkg.splitCodePaths));
15090
15091            // Reflect the rename in app info
15092            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15093            pkg.setApplicationInfoCodePath(pkg.codePath);
15094            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15095            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15096            pkg.setApplicationInfoResourcePath(pkg.codePath);
15097            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15098            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15099
15100            return true;
15101        }
15102
15103        int doPostInstall(int status, int uid) {
15104            if (status != PackageManager.INSTALL_SUCCEEDED) {
15105                cleanUp();
15106            }
15107            return status;
15108        }
15109
15110        @Override
15111        String getCodePath() {
15112            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15113        }
15114
15115        @Override
15116        String getResourcePath() {
15117            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15118        }
15119
15120        private boolean cleanUp() {
15121            if (codeFile == null || !codeFile.exists()) {
15122                return false;
15123            }
15124
15125            removeCodePathLI(codeFile);
15126
15127            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15128                resourceFile.delete();
15129            }
15130
15131            return true;
15132        }
15133
15134        void cleanUpResourcesLI() {
15135            // Try enumerating all code paths before deleting
15136            List<String> allCodePaths = Collections.EMPTY_LIST;
15137            if (codeFile != null && codeFile.exists()) {
15138                try {
15139                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15140                    allCodePaths = pkg.getAllCodePaths();
15141                } catch (PackageParserException e) {
15142                    // Ignored; we tried our best
15143                }
15144            }
15145
15146            cleanUp();
15147            removeDexFiles(allCodePaths, instructionSets);
15148        }
15149
15150        boolean doPostDeleteLI(boolean delete) {
15151            // XXX err, shouldn't we respect the delete flag?
15152            cleanUpResourcesLI();
15153            return true;
15154        }
15155    }
15156
15157    private boolean isAsecExternal(String cid) {
15158        final String asecPath = PackageHelper.getSdFilesystem(cid);
15159        return !asecPath.startsWith(mAsecInternalPath);
15160    }
15161
15162    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15163            PackageManagerException {
15164        if (copyRet < 0) {
15165            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15166                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15167                throw new PackageManagerException(copyRet, message);
15168            }
15169        }
15170    }
15171
15172    /**
15173     * Extract the StorageManagerService "container ID" from the full code path of an
15174     * .apk.
15175     */
15176    static String cidFromCodePath(String fullCodePath) {
15177        int eidx = fullCodePath.lastIndexOf("/");
15178        String subStr1 = fullCodePath.substring(0, eidx);
15179        int sidx = subStr1.lastIndexOf("/");
15180        return subStr1.substring(sidx+1, eidx);
15181    }
15182
15183    /**
15184     * Logic to handle installation of ASEC applications, including copying and
15185     * renaming logic.
15186     */
15187    class AsecInstallArgs extends InstallArgs {
15188        static final String RES_FILE_NAME = "pkg.apk";
15189        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15190
15191        String cid;
15192        String packagePath;
15193        String resourcePath;
15194
15195        /** New install */
15196        AsecInstallArgs(InstallParams params) {
15197            super(params.origin, params.move, params.observer, params.installFlags,
15198                    params.installerPackageName, params.volumeUuid,
15199                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15200                    params.grantedRuntimePermissions,
15201                    params.traceMethod, params.traceCookie, params.certificates,
15202                    params.installReason);
15203        }
15204
15205        /** Existing install */
15206        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15207                        boolean isExternal, boolean isForwardLocked) {
15208            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15209                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15210                    instructionSets, null, null, null, 0, null /*certificates*/,
15211                    PackageManager.INSTALL_REASON_UNKNOWN);
15212            // Hackily pretend we're still looking at a full code path
15213            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15214                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15215            }
15216
15217            // Extract cid from fullCodePath
15218            int eidx = fullCodePath.lastIndexOf("/");
15219            String subStr1 = fullCodePath.substring(0, eidx);
15220            int sidx = subStr1.lastIndexOf("/");
15221            cid = subStr1.substring(sidx+1, eidx);
15222            setMountPath(subStr1);
15223        }
15224
15225        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15226            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15227                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15228                    instructionSets, null, null, null, 0, null /*certificates*/,
15229                    PackageManager.INSTALL_REASON_UNKNOWN);
15230            this.cid = cid;
15231            setMountPath(PackageHelper.getSdDir(cid));
15232        }
15233
15234        void createCopyFile() {
15235            cid = mInstallerService.allocateExternalStageCidLegacy();
15236        }
15237
15238        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15239            if (origin.staged && origin.cid != null) {
15240                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15241                cid = origin.cid;
15242                setMountPath(PackageHelper.getSdDir(cid));
15243                return PackageManager.INSTALL_SUCCEEDED;
15244            }
15245
15246            if (temp) {
15247                createCopyFile();
15248            } else {
15249                /*
15250                 * Pre-emptively destroy the container since it's destroyed if
15251                 * copying fails due to it existing anyway.
15252                 */
15253                PackageHelper.destroySdDir(cid);
15254            }
15255
15256            final String newMountPath = imcs.copyPackageToContainer(
15257                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15258                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15259
15260            if (newMountPath != null) {
15261                setMountPath(newMountPath);
15262                return PackageManager.INSTALL_SUCCEEDED;
15263            } else {
15264                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15265            }
15266        }
15267
15268        @Override
15269        String getCodePath() {
15270            return packagePath;
15271        }
15272
15273        @Override
15274        String getResourcePath() {
15275            return resourcePath;
15276        }
15277
15278        int doPreInstall(int status) {
15279            if (status != PackageManager.INSTALL_SUCCEEDED) {
15280                // Destroy container
15281                PackageHelper.destroySdDir(cid);
15282            } else {
15283                boolean mounted = PackageHelper.isContainerMounted(cid);
15284                if (!mounted) {
15285                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15286                            Process.SYSTEM_UID);
15287                    if (newMountPath != null) {
15288                        setMountPath(newMountPath);
15289                    } else {
15290                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15291                    }
15292                }
15293            }
15294            return status;
15295        }
15296
15297        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15298            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15299            String newMountPath = null;
15300            if (PackageHelper.isContainerMounted(cid)) {
15301                // Unmount the container
15302                if (!PackageHelper.unMountSdDir(cid)) {
15303                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15304                    return false;
15305                }
15306            }
15307            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15308                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15309                        " which might be stale. Will try to clean up.");
15310                // Clean up the stale container and proceed to recreate.
15311                if (!PackageHelper.destroySdDir(newCacheId)) {
15312                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15313                    return false;
15314                }
15315                // Successfully cleaned up stale container. Try to rename again.
15316                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15317                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15318                            + " inspite of cleaning it up.");
15319                    return false;
15320                }
15321            }
15322            if (!PackageHelper.isContainerMounted(newCacheId)) {
15323                Slog.w(TAG, "Mounting container " + newCacheId);
15324                newMountPath = PackageHelper.mountSdDir(newCacheId,
15325                        getEncryptKey(), Process.SYSTEM_UID);
15326            } else {
15327                newMountPath = PackageHelper.getSdDir(newCacheId);
15328            }
15329            if (newMountPath == null) {
15330                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15331                return false;
15332            }
15333            Log.i(TAG, "Succesfully renamed " + cid +
15334                    " to " + newCacheId +
15335                    " at new path: " + newMountPath);
15336            cid = newCacheId;
15337
15338            final File beforeCodeFile = new File(packagePath);
15339            setMountPath(newMountPath);
15340            final File afterCodeFile = new File(packagePath);
15341
15342            // Reflect the rename in scanned details
15343            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15344            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15345                    afterCodeFile, pkg.baseCodePath));
15346            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15347                    afterCodeFile, pkg.splitCodePaths));
15348
15349            // Reflect the rename in app info
15350            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15351            pkg.setApplicationInfoCodePath(pkg.codePath);
15352            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15353            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15354            pkg.setApplicationInfoResourcePath(pkg.codePath);
15355            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15356            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15357
15358            return true;
15359        }
15360
15361        private void setMountPath(String mountPath) {
15362            final File mountFile = new File(mountPath);
15363
15364            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15365            if (monolithicFile.exists()) {
15366                packagePath = monolithicFile.getAbsolutePath();
15367                if (isFwdLocked()) {
15368                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15369                } else {
15370                    resourcePath = packagePath;
15371                }
15372            } else {
15373                packagePath = mountFile.getAbsolutePath();
15374                resourcePath = packagePath;
15375            }
15376        }
15377
15378        int doPostInstall(int status, int uid) {
15379            if (status != PackageManager.INSTALL_SUCCEEDED) {
15380                cleanUp();
15381            } else {
15382                final int groupOwner;
15383                final String protectedFile;
15384                if (isFwdLocked()) {
15385                    groupOwner = UserHandle.getSharedAppGid(uid);
15386                    protectedFile = RES_FILE_NAME;
15387                } else {
15388                    groupOwner = -1;
15389                    protectedFile = null;
15390                }
15391
15392                if (uid < Process.FIRST_APPLICATION_UID
15393                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15394                    Slog.e(TAG, "Failed to finalize " + cid);
15395                    PackageHelper.destroySdDir(cid);
15396                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15397                }
15398
15399                boolean mounted = PackageHelper.isContainerMounted(cid);
15400                if (!mounted) {
15401                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15402                }
15403            }
15404            return status;
15405        }
15406
15407        private void cleanUp() {
15408            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15409
15410            // Destroy secure container
15411            PackageHelper.destroySdDir(cid);
15412        }
15413
15414        private List<String> getAllCodePaths() {
15415            final File codeFile = new File(getCodePath());
15416            if (codeFile != null && codeFile.exists()) {
15417                try {
15418                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15419                    return pkg.getAllCodePaths();
15420                } catch (PackageParserException e) {
15421                    // Ignored; we tried our best
15422                }
15423            }
15424            return Collections.EMPTY_LIST;
15425        }
15426
15427        void cleanUpResourcesLI() {
15428            // Enumerate all code paths before deleting
15429            cleanUpResourcesLI(getAllCodePaths());
15430        }
15431
15432        private void cleanUpResourcesLI(List<String> allCodePaths) {
15433            cleanUp();
15434            removeDexFiles(allCodePaths, instructionSets);
15435        }
15436
15437        String getPackageName() {
15438            return getAsecPackageName(cid);
15439        }
15440
15441        boolean doPostDeleteLI(boolean delete) {
15442            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15443            final List<String> allCodePaths = getAllCodePaths();
15444            boolean mounted = PackageHelper.isContainerMounted(cid);
15445            if (mounted) {
15446                // Unmount first
15447                if (PackageHelper.unMountSdDir(cid)) {
15448                    mounted = false;
15449                }
15450            }
15451            if (!mounted && delete) {
15452                cleanUpResourcesLI(allCodePaths);
15453            }
15454            return !mounted;
15455        }
15456
15457        @Override
15458        int doPreCopy() {
15459            if (isFwdLocked()) {
15460                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15461                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15462                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15463                }
15464            }
15465
15466            return PackageManager.INSTALL_SUCCEEDED;
15467        }
15468
15469        @Override
15470        int doPostCopy(int uid) {
15471            if (isFwdLocked()) {
15472                if (uid < Process.FIRST_APPLICATION_UID
15473                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15474                                RES_FILE_NAME)) {
15475                    Slog.e(TAG, "Failed to finalize " + cid);
15476                    PackageHelper.destroySdDir(cid);
15477                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15478                }
15479            }
15480
15481            return PackageManager.INSTALL_SUCCEEDED;
15482        }
15483    }
15484
15485    /**
15486     * Logic to handle movement of existing installed applications.
15487     */
15488    class MoveInstallArgs extends InstallArgs {
15489        private File codeFile;
15490        private File resourceFile;
15491
15492        /** New install */
15493        MoveInstallArgs(InstallParams params) {
15494            super(params.origin, params.move, params.observer, params.installFlags,
15495                    params.installerPackageName, params.volumeUuid,
15496                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15497                    params.grantedRuntimePermissions,
15498                    params.traceMethod, params.traceCookie, params.certificates,
15499                    params.installReason);
15500        }
15501
15502        int copyApk(IMediaContainerService imcs, boolean temp) {
15503            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15504                    + move.fromUuid + " to " + move.toUuid);
15505            synchronized (mInstaller) {
15506                try {
15507                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15508                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15509                } catch (InstallerException e) {
15510                    Slog.w(TAG, "Failed to move app", e);
15511                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15512                }
15513            }
15514
15515            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15516            resourceFile = codeFile;
15517            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15518
15519            return PackageManager.INSTALL_SUCCEEDED;
15520        }
15521
15522        int doPreInstall(int status) {
15523            if (status != PackageManager.INSTALL_SUCCEEDED) {
15524                cleanUp(move.toUuid);
15525            }
15526            return status;
15527        }
15528
15529        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15530            if (status != PackageManager.INSTALL_SUCCEEDED) {
15531                cleanUp(move.toUuid);
15532                return false;
15533            }
15534
15535            // Reflect the move in app info
15536            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15537            pkg.setApplicationInfoCodePath(pkg.codePath);
15538            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15539            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15540            pkg.setApplicationInfoResourcePath(pkg.codePath);
15541            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15542            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15543
15544            return true;
15545        }
15546
15547        int doPostInstall(int status, int uid) {
15548            if (status == PackageManager.INSTALL_SUCCEEDED) {
15549                cleanUp(move.fromUuid);
15550            } else {
15551                cleanUp(move.toUuid);
15552            }
15553            return status;
15554        }
15555
15556        @Override
15557        String getCodePath() {
15558            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15559        }
15560
15561        @Override
15562        String getResourcePath() {
15563            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15564        }
15565
15566        private boolean cleanUp(String volumeUuid) {
15567            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15568                    move.dataAppName);
15569            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15570            final int[] userIds = sUserManager.getUserIds();
15571            synchronized (mInstallLock) {
15572                // Clean up both app data and code
15573                // All package moves are frozen until finished
15574                for (int userId : userIds) {
15575                    try {
15576                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15577                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15578                    } catch (InstallerException e) {
15579                        Slog.w(TAG, String.valueOf(e));
15580                    }
15581                }
15582                removeCodePathLI(codeFile);
15583            }
15584            return true;
15585        }
15586
15587        void cleanUpResourcesLI() {
15588            throw new UnsupportedOperationException();
15589        }
15590
15591        boolean doPostDeleteLI(boolean delete) {
15592            throw new UnsupportedOperationException();
15593        }
15594    }
15595
15596    static String getAsecPackageName(String packageCid) {
15597        int idx = packageCid.lastIndexOf("-");
15598        if (idx == -1) {
15599            return packageCid;
15600        }
15601        return packageCid.substring(0, idx);
15602    }
15603
15604    // Utility method used to create code paths based on package name and available index.
15605    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15606        String idxStr = "";
15607        int idx = 1;
15608        // Fall back to default value of idx=1 if prefix is not
15609        // part of oldCodePath
15610        if (oldCodePath != null) {
15611            String subStr = oldCodePath;
15612            // Drop the suffix right away
15613            if (suffix != null && subStr.endsWith(suffix)) {
15614                subStr = subStr.substring(0, subStr.length() - suffix.length());
15615            }
15616            // If oldCodePath already contains prefix find out the
15617            // ending index to either increment or decrement.
15618            int sidx = subStr.lastIndexOf(prefix);
15619            if (sidx != -1) {
15620                subStr = subStr.substring(sidx + prefix.length());
15621                if (subStr != null) {
15622                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15623                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15624                    }
15625                    try {
15626                        idx = Integer.parseInt(subStr);
15627                        if (idx <= 1) {
15628                            idx++;
15629                        } else {
15630                            idx--;
15631                        }
15632                    } catch(NumberFormatException e) {
15633                    }
15634                }
15635            }
15636        }
15637        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15638        return prefix + idxStr;
15639    }
15640
15641    private File getNextCodePath(File targetDir, String packageName) {
15642        File result;
15643        SecureRandom random = new SecureRandom();
15644        byte[] bytes = new byte[16];
15645        do {
15646            random.nextBytes(bytes);
15647            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15648            result = new File(targetDir, packageName + "-" + suffix);
15649        } while (result.exists());
15650        return result;
15651    }
15652
15653    // Utility method that returns the relative package path with respect
15654    // to the installation directory. Like say for /data/data/com.test-1.apk
15655    // string com.test-1 is returned.
15656    static String deriveCodePathName(String codePath) {
15657        if (codePath == null) {
15658            return null;
15659        }
15660        final File codeFile = new File(codePath);
15661        final String name = codeFile.getName();
15662        if (codeFile.isDirectory()) {
15663            return name;
15664        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15665            final int lastDot = name.lastIndexOf('.');
15666            return name.substring(0, lastDot);
15667        } else {
15668            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15669            return null;
15670        }
15671    }
15672
15673    static class PackageInstalledInfo {
15674        String name;
15675        int uid;
15676        // The set of users that originally had this package installed.
15677        int[] origUsers;
15678        // The set of users that now have this package installed.
15679        int[] newUsers;
15680        PackageParser.Package pkg;
15681        int returnCode;
15682        String returnMsg;
15683        PackageRemovedInfo removedInfo;
15684        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15685
15686        public void setError(int code, String msg) {
15687            setReturnCode(code);
15688            setReturnMessage(msg);
15689            Slog.w(TAG, msg);
15690        }
15691
15692        public void setError(String msg, PackageParserException e) {
15693            setReturnCode(e.error);
15694            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15695            Slog.w(TAG, msg, e);
15696        }
15697
15698        public void setError(String msg, PackageManagerException e) {
15699            returnCode = e.error;
15700            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15701            Slog.w(TAG, msg, e);
15702        }
15703
15704        public void setReturnCode(int returnCode) {
15705            this.returnCode = returnCode;
15706            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15707            for (int i = 0; i < childCount; i++) {
15708                addedChildPackages.valueAt(i).returnCode = returnCode;
15709            }
15710        }
15711
15712        private void setReturnMessage(String returnMsg) {
15713            this.returnMsg = returnMsg;
15714            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15715            for (int i = 0; i < childCount; i++) {
15716                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15717            }
15718        }
15719
15720        // In some error cases we want to convey more info back to the observer
15721        String origPackage;
15722        String origPermission;
15723    }
15724
15725    /*
15726     * Install a non-existing package.
15727     */
15728    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15729            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15730            PackageInstalledInfo res, int installReason) {
15731        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15732
15733        // Remember this for later, in case we need to rollback this install
15734        String pkgName = pkg.packageName;
15735
15736        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15737
15738        synchronized(mPackages) {
15739            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15740            if (renamedPackage != null) {
15741                // A package with the same name is already installed, though
15742                // it has been renamed to an older name.  The package we
15743                // are trying to install should be installed as an update to
15744                // the existing one, but that has not been requested, so bail.
15745                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15746                        + " without first uninstalling package running as "
15747                        + renamedPackage);
15748                return;
15749            }
15750            if (mPackages.containsKey(pkgName)) {
15751                // Don't allow installation over an existing package with the same name.
15752                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15753                        + " without first uninstalling.");
15754                return;
15755            }
15756        }
15757
15758        try {
15759            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15760                    System.currentTimeMillis(), user);
15761
15762            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15763
15764            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15765                prepareAppDataAfterInstallLIF(newPackage);
15766
15767            } else {
15768                // Remove package from internal structures, but keep around any
15769                // data that might have already existed
15770                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15771                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15772            }
15773        } catch (PackageManagerException e) {
15774            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15775        }
15776
15777        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15778    }
15779
15780    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15781        // Can't rotate keys during boot or if sharedUser.
15782        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15783                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15784            return false;
15785        }
15786        // app is using upgradeKeySets; make sure all are valid
15787        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15788        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15789        for (int i = 0; i < upgradeKeySets.length; i++) {
15790            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15791                Slog.wtf(TAG, "Package "
15792                         + (oldPs.name != null ? oldPs.name : "<null>")
15793                         + " contains upgrade-key-set reference to unknown key-set: "
15794                         + upgradeKeySets[i]
15795                         + " reverting to signatures check.");
15796                return false;
15797            }
15798        }
15799        return true;
15800    }
15801
15802    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15803        // Upgrade keysets are being used.  Determine if new package has a superset of the
15804        // required keys.
15805        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15806        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15807        for (int i = 0; i < upgradeKeySets.length; i++) {
15808            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15809            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15810                return true;
15811            }
15812        }
15813        return false;
15814    }
15815
15816    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15817        try (DigestInputStream digestStream =
15818                new DigestInputStream(new FileInputStream(file), digest)) {
15819            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15820        }
15821    }
15822
15823    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15824            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15825            int installReason) {
15826        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15827
15828        final PackageParser.Package oldPackage;
15829        final String pkgName = pkg.packageName;
15830        final int[] allUsers;
15831        final int[] installedUsers;
15832
15833        synchronized(mPackages) {
15834            oldPackage = mPackages.get(pkgName);
15835            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15836
15837            // don't allow upgrade to target a release SDK from a pre-release SDK
15838            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15839                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15840            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15841                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15842            if (oldTargetsPreRelease
15843                    && !newTargetsPreRelease
15844                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15845                Slog.w(TAG, "Can't install package targeting released sdk");
15846                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15847                return;
15848            }
15849
15850            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15851
15852            // verify signatures are valid
15853            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15854                if (!checkUpgradeKeySetLP(ps, pkg)) {
15855                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15856                            "New package not signed by keys specified by upgrade-keysets: "
15857                                    + pkgName);
15858                    return;
15859                }
15860            } else {
15861                // default to original signature matching
15862                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15863                        != PackageManager.SIGNATURE_MATCH) {
15864                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15865                            "New package has a different signature: " + pkgName);
15866                    return;
15867                }
15868            }
15869
15870            // don't allow a system upgrade unless the upgrade hash matches
15871            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15872                byte[] digestBytes = null;
15873                try {
15874                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15875                    updateDigest(digest, new File(pkg.baseCodePath));
15876                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15877                        for (String path : pkg.splitCodePaths) {
15878                            updateDigest(digest, new File(path));
15879                        }
15880                    }
15881                    digestBytes = digest.digest();
15882                } catch (NoSuchAlgorithmException | IOException e) {
15883                    res.setError(INSTALL_FAILED_INVALID_APK,
15884                            "Could not compute hash: " + pkgName);
15885                    return;
15886                }
15887                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15888                    res.setError(INSTALL_FAILED_INVALID_APK,
15889                            "New package fails restrict-update check: " + pkgName);
15890                    return;
15891                }
15892                // retain upgrade restriction
15893                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15894            }
15895
15896            // Check for shared user id changes
15897            String invalidPackageName =
15898                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15899            if (invalidPackageName != null) {
15900                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15901                        "Package " + invalidPackageName + " tried to change user "
15902                                + oldPackage.mSharedUserId);
15903                return;
15904            }
15905
15906            // In case of rollback, remember per-user/profile install state
15907            allUsers = sUserManager.getUserIds();
15908            installedUsers = ps.queryInstalledUsers(allUsers, true);
15909
15910            // don't allow an upgrade from full to ephemeral
15911            if (isInstantApp) {
15912                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15913                    for (int currentUser : allUsers) {
15914                        if (!ps.getInstantApp(currentUser)) {
15915                            // can't downgrade from full to instant
15916                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15917                                    + " for user: " + currentUser);
15918                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15919                            return;
15920                        }
15921                    }
15922                } else if (!ps.getInstantApp(user.getIdentifier())) {
15923                    // can't downgrade from full to instant
15924                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15925                            + " for user: " + user.getIdentifier());
15926                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15927                    return;
15928                }
15929            }
15930        }
15931
15932        // Update what is removed
15933        res.removedInfo = new PackageRemovedInfo();
15934        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15935        res.removedInfo.removedPackage = oldPackage.packageName;
15936        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15937        res.removedInfo.isUpdate = true;
15938        res.removedInfo.origUsers = installedUsers;
15939        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15940        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15941        for (int i = 0; i < installedUsers.length; i++) {
15942            final int userId = installedUsers[i];
15943            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15944        }
15945
15946        final int childCount = (oldPackage.childPackages != null)
15947                ? oldPackage.childPackages.size() : 0;
15948        for (int i = 0; i < childCount; i++) {
15949            boolean childPackageUpdated = false;
15950            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15951            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15952            if (res.addedChildPackages != null) {
15953                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15954                if (childRes != null) {
15955                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15956                    childRes.removedInfo.removedPackage = childPkg.packageName;
15957                    childRes.removedInfo.isUpdate = true;
15958                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15959                    childPackageUpdated = true;
15960                }
15961            }
15962            if (!childPackageUpdated) {
15963                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15964                childRemovedRes.removedPackage = childPkg.packageName;
15965                childRemovedRes.isUpdate = false;
15966                childRemovedRes.dataRemoved = true;
15967                synchronized (mPackages) {
15968                    if (childPs != null) {
15969                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15970                    }
15971                }
15972                if (res.removedInfo.removedChildPackages == null) {
15973                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15974                }
15975                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15976            }
15977        }
15978
15979        boolean sysPkg = (isSystemApp(oldPackage));
15980        if (sysPkg) {
15981            // Set the system/privileged flags as needed
15982            final boolean privileged =
15983                    (oldPackage.applicationInfo.privateFlags
15984                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15985            final int systemPolicyFlags = policyFlags
15986                    | PackageParser.PARSE_IS_SYSTEM
15987                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15988
15989            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15990                    user, allUsers, installerPackageName, res, installReason);
15991        } else {
15992            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15993                    user, allUsers, installerPackageName, res, installReason);
15994        }
15995    }
15996
15997    public List<String> getPreviousCodePaths(String packageName) {
15998        final PackageSetting ps = mSettings.mPackages.get(packageName);
15999        final List<String> result = new ArrayList<String>();
16000        if (ps != null && ps.oldCodePaths != null) {
16001            result.addAll(ps.oldCodePaths);
16002        }
16003        return result;
16004    }
16005
16006    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16007            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16008            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16009            int installReason) {
16010        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16011                + deletedPackage);
16012
16013        String pkgName = deletedPackage.packageName;
16014        boolean deletedPkg = true;
16015        boolean addedPkg = false;
16016        boolean updatedSettings = false;
16017        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16018        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16019                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16020
16021        final long origUpdateTime = (pkg.mExtras != null)
16022                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16023
16024        // First delete the existing package while retaining the data directory
16025        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16026                res.removedInfo, true, pkg)) {
16027            // If the existing package wasn't successfully deleted
16028            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16029            deletedPkg = false;
16030        } else {
16031            // Successfully deleted the old package; proceed with replace.
16032
16033            // If deleted package lived in a container, give users a chance to
16034            // relinquish resources before killing.
16035            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16036                if (DEBUG_INSTALL) {
16037                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16038                }
16039                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16040                final ArrayList<String> pkgList = new ArrayList<String>(1);
16041                pkgList.add(deletedPackage.applicationInfo.packageName);
16042                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16043            }
16044
16045            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16046                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16047            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16048
16049            try {
16050                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16051                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16052                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16053                        installReason);
16054
16055                // Update the in-memory copy of the previous code paths.
16056                PackageSetting ps = mSettings.mPackages.get(pkgName);
16057                if (!killApp) {
16058                    if (ps.oldCodePaths == null) {
16059                        ps.oldCodePaths = new ArraySet<>();
16060                    }
16061                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16062                    if (deletedPackage.splitCodePaths != null) {
16063                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16064                    }
16065                } else {
16066                    ps.oldCodePaths = null;
16067                }
16068                if (ps.childPackageNames != null) {
16069                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16070                        final String childPkgName = ps.childPackageNames.get(i);
16071                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16072                        childPs.oldCodePaths = ps.oldCodePaths;
16073                    }
16074                }
16075                // set instant app status, but, only if it's explicitly specified
16076                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16077                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16078                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16079                prepareAppDataAfterInstallLIF(newPackage);
16080                addedPkg = true;
16081                mDexManager.notifyPackageUpdated(newPackage.packageName,
16082                        newPackage.baseCodePath, newPackage.splitCodePaths);
16083            } catch (PackageManagerException e) {
16084                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16085            }
16086        }
16087
16088        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16089            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16090
16091            // Revert all internal state mutations and added folders for the failed install
16092            if (addedPkg) {
16093                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16094                        res.removedInfo, true, null);
16095            }
16096
16097            // Restore the old package
16098            if (deletedPkg) {
16099                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16100                File restoreFile = new File(deletedPackage.codePath);
16101                // Parse old package
16102                boolean oldExternal = isExternal(deletedPackage);
16103                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16104                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16105                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16106                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16107                try {
16108                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16109                            null);
16110                } catch (PackageManagerException e) {
16111                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16112                            + e.getMessage());
16113                    return;
16114                }
16115
16116                synchronized (mPackages) {
16117                    // Ensure the installer package name up to date
16118                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16119
16120                    // Update permissions for restored package
16121                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16122
16123                    mSettings.writeLPr();
16124                }
16125
16126                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16127            }
16128        } else {
16129            synchronized (mPackages) {
16130                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16131                if (ps != null) {
16132                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16133                    if (res.removedInfo.removedChildPackages != null) {
16134                        final int childCount = res.removedInfo.removedChildPackages.size();
16135                        // Iterate in reverse as we may modify the collection
16136                        for (int i = childCount - 1; i >= 0; i--) {
16137                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16138                            if (res.addedChildPackages.containsKey(childPackageName)) {
16139                                res.removedInfo.removedChildPackages.removeAt(i);
16140                            } else {
16141                                PackageRemovedInfo childInfo = res.removedInfo
16142                                        .removedChildPackages.valueAt(i);
16143                                childInfo.removedForAllUsers = mPackages.get(
16144                                        childInfo.removedPackage) == null;
16145                            }
16146                        }
16147                    }
16148                }
16149            }
16150        }
16151    }
16152
16153    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16154            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16155            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16156            int installReason) {
16157        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16158                + ", old=" + deletedPackage);
16159
16160        final boolean disabledSystem;
16161
16162        // Remove existing system package
16163        removePackageLI(deletedPackage, true);
16164
16165        synchronized (mPackages) {
16166            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16167        }
16168        if (!disabledSystem) {
16169            // We didn't need to disable the .apk as a current system package,
16170            // which means we are replacing another update that is already
16171            // installed.  We need to make sure to delete the older one's .apk.
16172            res.removedInfo.args = createInstallArgsForExisting(0,
16173                    deletedPackage.applicationInfo.getCodePath(),
16174                    deletedPackage.applicationInfo.getResourcePath(),
16175                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16176        } else {
16177            res.removedInfo.args = null;
16178        }
16179
16180        // Successfully disabled the old package. Now proceed with re-installation
16181        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16182                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16183        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16184
16185        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16186        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16187                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16188
16189        PackageParser.Package newPackage = null;
16190        try {
16191            // Add the package to the internal data structures
16192            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16193
16194            // Set the update and install times
16195            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16196            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16197                    System.currentTimeMillis());
16198
16199            // Update the package dynamic state if succeeded
16200            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16201                // Now that the install succeeded make sure we remove data
16202                // directories for any child package the update removed.
16203                final int deletedChildCount = (deletedPackage.childPackages != null)
16204                        ? deletedPackage.childPackages.size() : 0;
16205                final int newChildCount = (newPackage.childPackages != null)
16206                        ? newPackage.childPackages.size() : 0;
16207                for (int i = 0; i < deletedChildCount; i++) {
16208                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16209                    boolean childPackageDeleted = true;
16210                    for (int j = 0; j < newChildCount; j++) {
16211                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16212                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16213                            childPackageDeleted = false;
16214                            break;
16215                        }
16216                    }
16217                    if (childPackageDeleted) {
16218                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16219                                deletedChildPkg.packageName);
16220                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16221                            PackageRemovedInfo removedChildRes = res.removedInfo
16222                                    .removedChildPackages.get(deletedChildPkg.packageName);
16223                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16224                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16225                        }
16226                    }
16227                }
16228
16229                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16230                        installReason);
16231                prepareAppDataAfterInstallLIF(newPackage);
16232
16233                mDexManager.notifyPackageUpdated(newPackage.packageName,
16234                            newPackage.baseCodePath, newPackage.splitCodePaths);
16235            }
16236        } catch (PackageManagerException e) {
16237            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16238            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16239        }
16240
16241        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16242            // Re installation failed. Restore old information
16243            // Remove new pkg information
16244            if (newPackage != null) {
16245                removeInstalledPackageLI(newPackage, true);
16246            }
16247            // Add back the old system package
16248            try {
16249                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16250            } catch (PackageManagerException e) {
16251                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16252            }
16253
16254            synchronized (mPackages) {
16255                if (disabledSystem) {
16256                    enableSystemPackageLPw(deletedPackage);
16257                }
16258
16259                // Ensure the installer package name up to date
16260                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16261
16262                // Update permissions for restored package
16263                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16264
16265                mSettings.writeLPr();
16266            }
16267
16268            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16269                    + " after failed upgrade");
16270        }
16271    }
16272
16273    /**
16274     * Checks whether the parent or any of the child packages have a change shared
16275     * user. For a package to be a valid update the shred users of the parent and
16276     * the children should match. We may later support changing child shared users.
16277     * @param oldPkg The updated package.
16278     * @param newPkg The update package.
16279     * @return The shared user that change between the versions.
16280     */
16281    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16282            PackageParser.Package newPkg) {
16283        // Check parent shared user
16284        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16285            return newPkg.packageName;
16286        }
16287        // Check child shared users
16288        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16289        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16290        for (int i = 0; i < newChildCount; i++) {
16291            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16292            // If this child was present, did it have the same shared user?
16293            for (int j = 0; j < oldChildCount; j++) {
16294                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16295                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16296                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16297                    return newChildPkg.packageName;
16298                }
16299            }
16300        }
16301        return null;
16302    }
16303
16304    private void removeNativeBinariesLI(PackageSetting ps) {
16305        // Remove the lib path for the parent package
16306        if (ps != null) {
16307            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16308            // Remove the lib path for the child packages
16309            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16310            for (int i = 0; i < childCount; i++) {
16311                PackageSetting childPs = null;
16312                synchronized (mPackages) {
16313                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16314                }
16315                if (childPs != null) {
16316                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16317                            .legacyNativeLibraryPathString);
16318                }
16319            }
16320        }
16321    }
16322
16323    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16324        // Enable the parent package
16325        mSettings.enableSystemPackageLPw(pkg.packageName);
16326        // Enable the child packages
16327        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16328        for (int i = 0; i < childCount; i++) {
16329            PackageParser.Package childPkg = pkg.childPackages.get(i);
16330            mSettings.enableSystemPackageLPw(childPkg.packageName);
16331        }
16332    }
16333
16334    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16335            PackageParser.Package newPkg) {
16336        // Disable the parent package (parent always replaced)
16337        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16338        // Disable the child packages
16339        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16340        for (int i = 0; i < childCount; i++) {
16341            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16342            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16343            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16344        }
16345        return disabled;
16346    }
16347
16348    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16349            String installerPackageName) {
16350        // Enable the parent package
16351        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16352        // Enable the child packages
16353        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16354        for (int i = 0; i < childCount; i++) {
16355            PackageParser.Package childPkg = pkg.childPackages.get(i);
16356            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16357        }
16358    }
16359
16360    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16361        // Collect all used permissions in the UID
16362        ArraySet<String> usedPermissions = new ArraySet<>();
16363        final int packageCount = su.packages.size();
16364        for (int i = 0; i < packageCount; i++) {
16365            PackageSetting ps = su.packages.valueAt(i);
16366            if (ps.pkg == null) {
16367                continue;
16368            }
16369            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16370            for (int j = 0; j < requestedPermCount; j++) {
16371                String permission = ps.pkg.requestedPermissions.get(j);
16372                BasePermission bp = mSettings.mPermissions.get(permission);
16373                if (bp != null) {
16374                    usedPermissions.add(permission);
16375                }
16376            }
16377        }
16378
16379        PermissionsState permissionsState = su.getPermissionsState();
16380        // Prune install permissions
16381        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16382        final int installPermCount = installPermStates.size();
16383        for (int i = installPermCount - 1; i >= 0;  i--) {
16384            PermissionState permissionState = installPermStates.get(i);
16385            if (!usedPermissions.contains(permissionState.getName())) {
16386                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16387                if (bp != null) {
16388                    permissionsState.revokeInstallPermission(bp);
16389                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16390                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16391                }
16392            }
16393        }
16394
16395        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16396
16397        // Prune runtime permissions
16398        for (int userId : allUserIds) {
16399            List<PermissionState> runtimePermStates = permissionsState
16400                    .getRuntimePermissionStates(userId);
16401            final int runtimePermCount = runtimePermStates.size();
16402            for (int i = runtimePermCount - 1; i >= 0; i--) {
16403                PermissionState permissionState = runtimePermStates.get(i);
16404                if (!usedPermissions.contains(permissionState.getName())) {
16405                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16406                    if (bp != null) {
16407                        permissionsState.revokeRuntimePermission(bp, userId);
16408                        permissionsState.updatePermissionFlags(bp, userId,
16409                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16410                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16411                                runtimePermissionChangedUserIds, userId);
16412                    }
16413                }
16414            }
16415        }
16416
16417        return runtimePermissionChangedUserIds;
16418    }
16419
16420    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16421            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16422        // Update the parent package setting
16423        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16424                res, user, installReason);
16425        // Update the child packages setting
16426        final int childCount = (newPackage.childPackages != null)
16427                ? newPackage.childPackages.size() : 0;
16428        for (int i = 0; i < childCount; i++) {
16429            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16430            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16431            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16432                    childRes.origUsers, childRes, user, installReason);
16433        }
16434    }
16435
16436    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16437            String installerPackageName, int[] allUsers, int[] installedForUsers,
16438            PackageInstalledInfo res, UserHandle user, int installReason) {
16439        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16440
16441        String pkgName = newPackage.packageName;
16442        synchronized (mPackages) {
16443            //write settings. the installStatus will be incomplete at this stage.
16444            //note that the new package setting would have already been
16445            //added to mPackages. It hasn't been persisted yet.
16446            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16447            // TODO: Remove this write? It's also written at the end of this method
16448            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16449            mSettings.writeLPr();
16450            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16451        }
16452
16453        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16454        synchronized (mPackages) {
16455            updatePermissionsLPw(newPackage.packageName, newPackage,
16456                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16457                            ? UPDATE_PERMISSIONS_ALL : 0));
16458            // For system-bundled packages, we assume that installing an upgraded version
16459            // of the package implies that the user actually wants to run that new code,
16460            // so we enable the package.
16461            PackageSetting ps = mSettings.mPackages.get(pkgName);
16462            final int userId = user.getIdentifier();
16463            if (ps != null) {
16464                if (isSystemApp(newPackage)) {
16465                    if (DEBUG_INSTALL) {
16466                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16467                    }
16468                    // Enable system package for requested users
16469                    if (res.origUsers != null) {
16470                        for (int origUserId : res.origUsers) {
16471                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16472                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16473                                        origUserId, installerPackageName);
16474                            }
16475                        }
16476                    }
16477                    // Also convey the prior install/uninstall state
16478                    if (allUsers != null && installedForUsers != null) {
16479                        for (int currentUserId : allUsers) {
16480                            final boolean installed = ArrayUtils.contains(
16481                                    installedForUsers, currentUserId);
16482                            if (DEBUG_INSTALL) {
16483                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16484                            }
16485                            ps.setInstalled(installed, currentUserId);
16486                        }
16487                        // these install state changes will be persisted in the
16488                        // upcoming call to mSettings.writeLPr().
16489                    }
16490                }
16491                // It's implied that when a user requests installation, they want the app to be
16492                // installed and enabled.
16493                if (userId != UserHandle.USER_ALL) {
16494                    ps.setInstalled(true, userId);
16495                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16496                }
16497
16498                // When replacing an existing package, preserve the original install reason for all
16499                // users that had the package installed before.
16500                final Set<Integer> previousUserIds = new ArraySet<>();
16501                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16502                    final int installReasonCount = res.removedInfo.installReasons.size();
16503                    for (int i = 0; i < installReasonCount; i++) {
16504                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16505                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16506                        ps.setInstallReason(previousInstallReason, previousUserId);
16507                        previousUserIds.add(previousUserId);
16508                    }
16509                }
16510
16511                // Set install reason for users that are having the package newly installed.
16512                if (userId == UserHandle.USER_ALL) {
16513                    for (int currentUserId : sUserManager.getUserIds()) {
16514                        if (!previousUserIds.contains(currentUserId)) {
16515                            ps.setInstallReason(installReason, currentUserId);
16516                        }
16517                    }
16518                } else if (!previousUserIds.contains(userId)) {
16519                    ps.setInstallReason(installReason, userId);
16520                }
16521                mSettings.writeKernelMappingLPr(ps);
16522            }
16523            res.name = pkgName;
16524            res.uid = newPackage.applicationInfo.uid;
16525            res.pkg = newPackage;
16526            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16527            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16528            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16529            //to update install status
16530            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16531            mSettings.writeLPr();
16532            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16533        }
16534
16535        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16536    }
16537
16538    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16539        try {
16540            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16541            installPackageLI(args, res);
16542        } finally {
16543            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16544        }
16545    }
16546
16547    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16548        final int installFlags = args.installFlags;
16549        final String installerPackageName = args.installerPackageName;
16550        final String volumeUuid = args.volumeUuid;
16551        final File tmpPackageFile = new File(args.getCodePath());
16552        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16553        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16554                || (args.volumeUuid != null));
16555        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16556        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16557        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16558        boolean replace = false;
16559        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16560        if (args.move != null) {
16561            // moving a complete application; perform an initial scan on the new install location
16562            scanFlags |= SCAN_INITIAL;
16563        }
16564        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16565            scanFlags |= SCAN_DONT_KILL_APP;
16566        }
16567        if (instantApp) {
16568            scanFlags |= SCAN_AS_INSTANT_APP;
16569        }
16570        if (fullApp) {
16571            scanFlags |= SCAN_AS_FULL_APP;
16572        }
16573
16574        // Result object to be returned
16575        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16576
16577        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16578
16579        // Sanity check
16580        if (instantApp && (forwardLocked || onExternal)) {
16581            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16582                    + " external=" + onExternal);
16583            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16584            return;
16585        }
16586
16587        // Retrieve PackageSettings and parse package
16588        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16589                | PackageParser.PARSE_ENFORCE_CODE
16590                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16591                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16592                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16593                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16594        PackageParser pp = new PackageParser();
16595        pp.setSeparateProcesses(mSeparateProcesses);
16596        pp.setDisplayMetrics(mMetrics);
16597        pp.setCallback(mPackageParserCallback);
16598
16599        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16600        final PackageParser.Package pkg;
16601        try {
16602            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16603        } catch (PackageParserException e) {
16604            res.setError("Failed parse during installPackageLI", e);
16605            return;
16606        } finally {
16607            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16608        }
16609
16610        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16611        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16612            Slog.w(TAG, "Instant app package " + pkg.packageName
16613                    + " does not target O, this will be a fatal error.");
16614            // STOPSHIP: Make this a fatal error
16615            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16616        }
16617        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16618            Slog.w(TAG, "Instant app package " + pkg.packageName
16619                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16620            // STOPSHIP: Make this a fatal error
16621            pkg.applicationInfo.targetSandboxVersion = 2;
16622        }
16623
16624        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16625            // Static shared libraries have synthetic package names
16626            renameStaticSharedLibraryPackage(pkg);
16627
16628            // No static shared libs on external storage
16629            if (onExternal) {
16630                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16631                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16632                        "Packages declaring static-shared libs cannot be updated");
16633                return;
16634            }
16635        }
16636
16637        // If we are installing a clustered package add results for the children
16638        if (pkg.childPackages != null) {
16639            synchronized (mPackages) {
16640                final int childCount = pkg.childPackages.size();
16641                for (int i = 0; i < childCount; i++) {
16642                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16643                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16644                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16645                    childRes.pkg = childPkg;
16646                    childRes.name = childPkg.packageName;
16647                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16648                    if (childPs != null) {
16649                        childRes.origUsers = childPs.queryInstalledUsers(
16650                                sUserManager.getUserIds(), true);
16651                    }
16652                    if ((mPackages.containsKey(childPkg.packageName))) {
16653                        childRes.removedInfo = new PackageRemovedInfo();
16654                        childRes.removedInfo.removedPackage = childPkg.packageName;
16655                    }
16656                    if (res.addedChildPackages == null) {
16657                        res.addedChildPackages = new ArrayMap<>();
16658                    }
16659                    res.addedChildPackages.put(childPkg.packageName, childRes);
16660                }
16661            }
16662        }
16663
16664        // If package doesn't declare API override, mark that we have an install
16665        // time CPU ABI override.
16666        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16667            pkg.cpuAbiOverride = args.abiOverride;
16668        }
16669
16670        String pkgName = res.name = pkg.packageName;
16671        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16672            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16673                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16674                return;
16675            }
16676        }
16677
16678        try {
16679            // either use what we've been given or parse directly from the APK
16680            if (args.certificates != null) {
16681                try {
16682                    PackageParser.populateCertificates(pkg, args.certificates);
16683                } catch (PackageParserException e) {
16684                    // there was something wrong with the certificates we were given;
16685                    // try to pull them from the APK
16686                    PackageParser.collectCertificates(pkg, parseFlags);
16687                }
16688            } else {
16689                PackageParser.collectCertificates(pkg, parseFlags);
16690            }
16691        } catch (PackageParserException e) {
16692            res.setError("Failed collect during installPackageLI", e);
16693            return;
16694        }
16695
16696        // Get rid of all references to package scan path via parser.
16697        pp = null;
16698        String oldCodePath = null;
16699        boolean systemApp = false;
16700        synchronized (mPackages) {
16701            // Check if installing already existing package
16702            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16703                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16704                if (pkg.mOriginalPackages != null
16705                        && pkg.mOriginalPackages.contains(oldName)
16706                        && mPackages.containsKey(oldName)) {
16707                    // This package is derived from an original package,
16708                    // and this device has been updating from that original
16709                    // name.  We must continue using the original name, so
16710                    // rename the new package here.
16711                    pkg.setPackageName(oldName);
16712                    pkgName = pkg.packageName;
16713                    replace = true;
16714                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16715                            + oldName + " pkgName=" + pkgName);
16716                } else if (mPackages.containsKey(pkgName)) {
16717                    // This package, under its official name, already exists
16718                    // on the device; we should replace it.
16719                    replace = true;
16720                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16721                }
16722
16723                // Child packages are installed through the parent package
16724                if (pkg.parentPackage != null) {
16725                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16726                            "Package " + pkg.packageName + " is child of package "
16727                                    + pkg.parentPackage.parentPackage + ". Child packages "
16728                                    + "can be updated only through the parent package.");
16729                    return;
16730                }
16731
16732                if (replace) {
16733                    // Prevent apps opting out from runtime permissions
16734                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16735                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16736                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16737                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16738                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16739                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16740                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16741                                        + " doesn't support runtime permissions but the old"
16742                                        + " target SDK " + oldTargetSdk + " does.");
16743                        return;
16744                    }
16745                    // Prevent apps from downgrading their targetSandbox.
16746                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16747                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16748                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16749                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16750                                "Package " + pkg.packageName + " new target sandbox "
16751                                + newTargetSandbox + " is incompatible with the previous value of"
16752                                + oldTargetSandbox + ".");
16753                        return;
16754                    }
16755
16756                    // Prevent installing of child packages
16757                    if (oldPackage.parentPackage != null) {
16758                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16759                                "Package " + pkg.packageName + " is child of package "
16760                                        + oldPackage.parentPackage + ". Child packages "
16761                                        + "can be updated only through the parent package.");
16762                        return;
16763                    }
16764                }
16765            }
16766
16767            PackageSetting ps = mSettings.mPackages.get(pkgName);
16768            if (ps != null) {
16769                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16770
16771                // Static shared libs have same package with different versions where
16772                // we internally use a synthetic package name to allow multiple versions
16773                // of the same package, therefore we need to compare signatures against
16774                // the package setting for the latest library version.
16775                PackageSetting signatureCheckPs = ps;
16776                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16777                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16778                    if (libraryEntry != null) {
16779                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16780                    }
16781                }
16782
16783                // Quick sanity check that we're signed correctly if updating;
16784                // we'll check this again later when scanning, but we want to
16785                // bail early here before tripping over redefined permissions.
16786                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16787                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16788                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16789                                + pkg.packageName + " upgrade keys do not match the "
16790                                + "previously installed version");
16791                        return;
16792                    }
16793                } else {
16794                    try {
16795                        verifySignaturesLP(signatureCheckPs, pkg);
16796                    } catch (PackageManagerException e) {
16797                        res.setError(e.error, e.getMessage());
16798                        return;
16799                    }
16800                }
16801
16802                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16803                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16804                    systemApp = (ps.pkg.applicationInfo.flags &
16805                            ApplicationInfo.FLAG_SYSTEM) != 0;
16806                }
16807                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16808            }
16809
16810            int N = pkg.permissions.size();
16811            for (int i = N-1; i >= 0; i--) {
16812                PackageParser.Permission perm = pkg.permissions.get(i);
16813                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16814
16815                // Don't allow anyone but the platform to define ephemeral permissions.
16816                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16817                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16818                    Slog.w(TAG, "Package " + pkg.packageName
16819                            + " attempting to delcare ephemeral permission "
16820                            + perm.info.name + "; Removing ephemeral.");
16821                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16822                }
16823                // Check whether the newly-scanned package wants to define an already-defined perm
16824                if (bp != null) {
16825                    // If the defining package is signed with our cert, it's okay.  This
16826                    // also includes the "updating the same package" case, of course.
16827                    // "updating same package" could also involve key-rotation.
16828                    final boolean sigsOk;
16829                    if (bp.sourcePackage.equals(pkg.packageName)
16830                            && (bp.packageSetting instanceof PackageSetting)
16831                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16832                                    scanFlags))) {
16833                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16834                    } else {
16835                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16836                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16837                    }
16838                    if (!sigsOk) {
16839                        // If the owning package is the system itself, we log but allow
16840                        // install to proceed; we fail the install on all other permission
16841                        // redefinitions.
16842                        if (!bp.sourcePackage.equals("android")) {
16843                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16844                                    + pkg.packageName + " attempting to redeclare permission "
16845                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16846                            res.origPermission = perm.info.name;
16847                            res.origPackage = bp.sourcePackage;
16848                            return;
16849                        } else {
16850                            Slog.w(TAG, "Package " + pkg.packageName
16851                                    + " attempting to redeclare system permission "
16852                                    + perm.info.name + "; ignoring new declaration");
16853                            pkg.permissions.remove(i);
16854                        }
16855                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16856                        // Prevent apps to change protection level to dangerous from any other
16857                        // type as this would allow a privilege escalation where an app adds a
16858                        // normal/signature permission in other app's group and later redefines
16859                        // it as dangerous leading to the group auto-grant.
16860                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16861                                == PermissionInfo.PROTECTION_DANGEROUS) {
16862                            if (bp != null && !bp.isRuntime()) {
16863                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16864                                        + "non-runtime permission " + perm.info.name
16865                                        + " to runtime; keeping old protection level");
16866                                perm.info.protectionLevel = bp.protectionLevel;
16867                            }
16868                        }
16869                    }
16870                }
16871            }
16872        }
16873
16874        if (systemApp) {
16875            if (onExternal) {
16876                // Abort update; system app can't be replaced with app on sdcard
16877                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16878                        "Cannot install updates to system apps on sdcard");
16879                return;
16880            } else if (instantApp) {
16881                // Abort update; system app can't be replaced with an instant app
16882                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16883                        "Cannot update a system app with an instant app");
16884                return;
16885            }
16886        }
16887
16888        if (args.move != null) {
16889            // We did an in-place move, so dex is ready to roll
16890            scanFlags |= SCAN_NO_DEX;
16891            scanFlags |= SCAN_MOVE;
16892
16893            synchronized (mPackages) {
16894                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16895                if (ps == null) {
16896                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16897                            "Missing settings for moved package " + pkgName);
16898                }
16899
16900                // We moved the entire application as-is, so bring over the
16901                // previously derived ABI information.
16902                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16903                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16904            }
16905
16906        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16907            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16908            scanFlags |= SCAN_NO_DEX;
16909
16910            try {
16911                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16912                    args.abiOverride : pkg.cpuAbiOverride);
16913                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16914                        true /*extractLibs*/, mAppLib32InstallDir);
16915            } catch (PackageManagerException pme) {
16916                Slog.e(TAG, "Error deriving application ABI", pme);
16917                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16918                return;
16919            }
16920
16921            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16922            // Do not run PackageDexOptimizer through the local performDexOpt
16923            // method because `pkg` may not be in `mPackages` yet.
16924            //
16925            // Also, don't fail application installs if the dexopt step fails.
16926            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16927                    null /* instructionSets */, false /* checkProfiles */,
16928                    getCompilerFilterForReason(REASON_INSTALL),
16929                    getOrCreateCompilerPackageStats(pkg),
16930                    mDexManager.isUsedByOtherApps(pkg.packageName));
16931            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16932
16933            // Notify BackgroundDexOptService that the package has been changed.
16934            // If this is an update of a package which used to fail to compile,
16935            // BDOS will remove it from its blacklist.
16936            // TODO: Layering violation
16937            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16938        }
16939
16940        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16941            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16942            return;
16943        }
16944
16945        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16946
16947        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16948                "installPackageLI")) {
16949            if (replace) {
16950                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16951                    // Static libs have a synthetic package name containing the version
16952                    // and cannot be updated as an update would get a new package name,
16953                    // unless this is the exact same version code which is useful for
16954                    // development.
16955                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16956                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16957                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16958                                + "static-shared libs cannot be updated");
16959                        return;
16960                    }
16961                }
16962                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16963                        installerPackageName, res, args.installReason);
16964            } else {
16965                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16966                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16967            }
16968        }
16969        synchronized (mPackages) {
16970            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16971            if (ps != null) {
16972                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16973                ps.setUpdateAvailable(false /*updateAvailable*/);
16974            }
16975
16976            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16977            for (int i = 0; i < childCount; i++) {
16978                PackageParser.Package childPkg = pkg.childPackages.get(i);
16979                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16980                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16981                if (childPs != null) {
16982                    childRes.newUsers = childPs.queryInstalledUsers(
16983                            sUserManager.getUserIds(), true);
16984                }
16985            }
16986
16987            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16988                updateSequenceNumberLP(pkgName, res.newUsers);
16989                updateInstantAppInstallerLocked();
16990            }
16991        }
16992    }
16993
16994    private void startIntentFilterVerifications(int userId, boolean replacing,
16995            PackageParser.Package pkg) {
16996        if (mIntentFilterVerifierComponent == null) {
16997            Slog.w(TAG, "No IntentFilter verification will not be done as "
16998                    + "there is no IntentFilterVerifier available!");
16999            return;
17000        }
17001
17002        final int verifierUid = getPackageUid(
17003                mIntentFilterVerifierComponent.getPackageName(),
17004                MATCH_DEBUG_TRIAGED_MISSING,
17005                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17006
17007        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17008        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17009        mHandler.sendMessage(msg);
17010
17011        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17012        for (int i = 0; i < childCount; i++) {
17013            PackageParser.Package childPkg = pkg.childPackages.get(i);
17014            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17015            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17016            mHandler.sendMessage(msg);
17017        }
17018    }
17019
17020    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17021            PackageParser.Package pkg) {
17022        int size = pkg.activities.size();
17023        if (size == 0) {
17024            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17025                    "No activity, so no need to verify any IntentFilter!");
17026            return;
17027        }
17028
17029        final boolean hasDomainURLs = hasDomainURLs(pkg);
17030        if (!hasDomainURLs) {
17031            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17032                    "No domain URLs, so no need to verify any IntentFilter!");
17033            return;
17034        }
17035
17036        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17037                + " if any IntentFilter from the " + size
17038                + " Activities needs verification ...");
17039
17040        int count = 0;
17041        final String packageName = pkg.packageName;
17042
17043        synchronized (mPackages) {
17044            // If this is a new install and we see that we've already run verification for this
17045            // package, we have nothing to do: it means the state was restored from backup.
17046            if (!replacing) {
17047                IntentFilterVerificationInfo ivi =
17048                        mSettings.getIntentFilterVerificationLPr(packageName);
17049                if (ivi != null) {
17050                    if (DEBUG_DOMAIN_VERIFICATION) {
17051                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17052                                + ivi.getStatusString());
17053                    }
17054                    return;
17055                }
17056            }
17057
17058            // If any filters need to be verified, then all need to be.
17059            boolean needToVerify = false;
17060            for (PackageParser.Activity a : pkg.activities) {
17061                for (ActivityIntentInfo filter : a.intents) {
17062                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17063                        if (DEBUG_DOMAIN_VERIFICATION) {
17064                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17065                        }
17066                        needToVerify = true;
17067                        break;
17068                    }
17069                }
17070            }
17071
17072            if (needToVerify) {
17073                final int verificationId = mIntentFilterVerificationToken++;
17074                for (PackageParser.Activity a : pkg.activities) {
17075                    for (ActivityIntentInfo filter : a.intents) {
17076                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17077                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17078                                    "Verification needed for IntentFilter:" + filter.toString());
17079                            mIntentFilterVerifier.addOneIntentFilterVerification(
17080                                    verifierUid, userId, verificationId, filter, packageName);
17081                            count++;
17082                        }
17083                    }
17084                }
17085            }
17086        }
17087
17088        if (count > 0) {
17089            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17090                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17091                    +  " for userId:" + userId);
17092            mIntentFilterVerifier.startVerifications(userId);
17093        } else {
17094            if (DEBUG_DOMAIN_VERIFICATION) {
17095                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17096            }
17097        }
17098    }
17099
17100    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17101        final ComponentName cn  = filter.activity.getComponentName();
17102        final String packageName = cn.getPackageName();
17103
17104        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17105                packageName);
17106        if (ivi == null) {
17107            return true;
17108        }
17109        int status = ivi.getStatus();
17110        switch (status) {
17111            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17112            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17113                return true;
17114
17115            default:
17116                // Nothing to do
17117                return false;
17118        }
17119    }
17120
17121    private static boolean isMultiArch(ApplicationInfo info) {
17122        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17123    }
17124
17125    private static boolean isExternal(PackageParser.Package pkg) {
17126        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17127    }
17128
17129    private static boolean isExternal(PackageSetting ps) {
17130        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17131    }
17132
17133    private static boolean isSystemApp(PackageParser.Package pkg) {
17134        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17135    }
17136
17137    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17138        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17139    }
17140
17141    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17142        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17143    }
17144
17145    private static boolean isSystemApp(PackageSetting ps) {
17146        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17147    }
17148
17149    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17150        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17151    }
17152
17153    private int packageFlagsToInstallFlags(PackageSetting ps) {
17154        int installFlags = 0;
17155        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17156            // This existing package was an external ASEC install when we have
17157            // the external flag without a UUID
17158            installFlags |= PackageManager.INSTALL_EXTERNAL;
17159        }
17160        if (ps.isForwardLocked()) {
17161            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17162        }
17163        return installFlags;
17164    }
17165
17166    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17167        if (isExternal(pkg)) {
17168            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17169                return StorageManager.UUID_PRIMARY_PHYSICAL;
17170            } else {
17171                return pkg.volumeUuid;
17172            }
17173        } else {
17174            return StorageManager.UUID_PRIVATE_INTERNAL;
17175        }
17176    }
17177
17178    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17179        if (isExternal(pkg)) {
17180            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17181                return mSettings.getExternalVersion();
17182            } else {
17183                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17184            }
17185        } else {
17186            return mSettings.getInternalVersion();
17187        }
17188    }
17189
17190    private void deleteTempPackageFiles() {
17191        final FilenameFilter filter = new FilenameFilter() {
17192            public boolean accept(File dir, String name) {
17193                return name.startsWith("vmdl") && name.endsWith(".tmp");
17194            }
17195        };
17196        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17197            file.delete();
17198        }
17199    }
17200
17201    @Override
17202    public void deletePackageAsUser(String packageName, int versionCode,
17203            IPackageDeleteObserver observer, int userId, int flags) {
17204        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17205                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17206    }
17207
17208    @Override
17209    public void deletePackageVersioned(VersionedPackage versionedPackage,
17210            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17211        mContext.enforceCallingOrSelfPermission(
17212                android.Manifest.permission.DELETE_PACKAGES, null);
17213        Preconditions.checkNotNull(versionedPackage);
17214        Preconditions.checkNotNull(observer);
17215        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17216                PackageManager.VERSION_CODE_HIGHEST,
17217                Integer.MAX_VALUE, "versionCode must be >= -1");
17218
17219        final String packageName = versionedPackage.getPackageName();
17220        // TODO: We will change version code to long, so in the new API it is long
17221        final int versionCode = (int) versionedPackage.getVersionCode();
17222        final String internalPackageName;
17223        synchronized (mPackages) {
17224            // Normalize package name to handle renamed packages and static libs
17225            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17226                    // TODO: We will change version code to long, so in the new API it is long
17227                    (int) versionedPackage.getVersionCode());
17228        }
17229
17230        final int uid = Binder.getCallingUid();
17231        if (!isOrphaned(internalPackageName)
17232                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17233            try {
17234                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17235                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17236                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17237                observer.onUserActionRequired(intent);
17238            } catch (RemoteException re) {
17239            }
17240            return;
17241        }
17242        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17243        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17244        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17245            mContext.enforceCallingOrSelfPermission(
17246                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17247                    "deletePackage for user " + userId);
17248        }
17249
17250        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17251            try {
17252                observer.onPackageDeleted(packageName,
17253                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17254            } catch (RemoteException re) {
17255            }
17256            return;
17257        }
17258
17259        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17260            try {
17261                observer.onPackageDeleted(packageName,
17262                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17263            } catch (RemoteException re) {
17264            }
17265            return;
17266        }
17267
17268        if (DEBUG_REMOVE) {
17269            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17270                    + " deleteAllUsers: " + deleteAllUsers + " version="
17271                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17272                    ? "VERSION_CODE_HIGHEST" : versionCode));
17273        }
17274        // Queue up an async operation since the package deletion may take a little while.
17275        mHandler.post(new Runnable() {
17276            public void run() {
17277                mHandler.removeCallbacks(this);
17278                int returnCode;
17279                if (!deleteAllUsers) {
17280                    returnCode = deletePackageX(internalPackageName, versionCode,
17281                            userId, deleteFlags);
17282                } else {
17283                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17284                            internalPackageName, users);
17285                    // If nobody is blocking uninstall, proceed with delete for all users
17286                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17287                        returnCode = deletePackageX(internalPackageName, versionCode,
17288                                userId, deleteFlags);
17289                    } else {
17290                        // Otherwise uninstall individually for users with blockUninstalls=false
17291                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17292                        for (int userId : users) {
17293                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17294                                returnCode = deletePackageX(internalPackageName, versionCode,
17295                                        userId, userFlags);
17296                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17297                                    Slog.w(TAG, "Package delete failed for user " + userId
17298                                            + ", returnCode " + returnCode);
17299                                }
17300                            }
17301                        }
17302                        // The app has only been marked uninstalled for certain users.
17303                        // We still need to report that delete was blocked
17304                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17305                    }
17306                }
17307                try {
17308                    observer.onPackageDeleted(packageName, returnCode, null);
17309                } catch (RemoteException e) {
17310                    Log.i(TAG, "Observer no longer exists.");
17311                } //end catch
17312            } //end run
17313        });
17314    }
17315
17316    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17317        if (pkg.staticSharedLibName != null) {
17318            return pkg.manifestPackageName;
17319        }
17320        return pkg.packageName;
17321    }
17322
17323    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17324        // Handle renamed packages
17325        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17326        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17327
17328        // Is this a static library?
17329        SparseArray<SharedLibraryEntry> versionedLib =
17330                mStaticLibsByDeclaringPackage.get(packageName);
17331        if (versionedLib == null || versionedLib.size() <= 0) {
17332            return packageName;
17333        }
17334
17335        // Figure out which lib versions the caller can see
17336        SparseIntArray versionsCallerCanSee = null;
17337        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17338        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17339                && callingAppId != Process.ROOT_UID) {
17340            versionsCallerCanSee = new SparseIntArray();
17341            String libName = versionedLib.valueAt(0).info.getName();
17342            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17343            if (uidPackages != null) {
17344                for (String uidPackage : uidPackages) {
17345                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17346                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17347                    if (libIdx >= 0) {
17348                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17349                        versionsCallerCanSee.append(libVersion, libVersion);
17350                    }
17351                }
17352            }
17353        }
17354
17355        // Caller can see nothing - done
17356        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17357            return packageName;
17358        }
17359
17360        // Find the version the caller can see and the app version code
17361        SharedLibraryEntry highestVersion = null;
17362        final int versionCount = versionedLib.size();
17363        for (int i = 0; i < versionCount; i++) {
17364            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17365            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17366                    libEntry.info.getVersion()) < 0) {
17367                continue;
17368            }
17369            // TODO: We will change version code to long, so in the new API it is long
17370            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17371            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17372                if (libVersionCode == versionCode) {
17373                    return libEntry.apk;
17374                }
17375            } else if (highestVersion == null) {
17376                highestVersion = libEntry;
17377            } else if (libVersionCode  > highestVersion.info
17378                    .getDeclaringPackage().getVersionCode()) {
17379                highestVersion = libEntry;
17380            }
17381        }
17382
17383        if (highestVersion != null) {
17384            return highestVersion.apk;
17385        }
17386
17387        return packageName;
17388    }
17389
17390    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17391        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17392              || callingUid == Process.SYSTEM_UID) {
17393            return true;
17394        }
17395        final int callingUserId = UserHandle.getUserId(callingUid);
17396        // If the caller installed the pkgName, then allow it to silently uninstall.
17397        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17398            return true;
17399        }
17400
17401        // Allow package verifier to silently uninstall.
17402        if (mRequiredVerifierPackage != null &&
17403                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17404            return true;
17405        }
17406
17407        // Allow package uninstaller to silently uninstall.
17408        if (mRequiredUninstallerPackage != null &&
17409                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17410            return true;
17411        }
17412
17413        // Allow storage manager to silently uninstall.
17414        if (mStorageManagerPackage != null &&
17415                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17416            return true;
17417        }
17418        return false;
17419    }
17420
17421    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17422        int[] result = EMPTY_INT_ARRAY;
17423        for (int userId : userIds) {
17424            if (getBlockUninstallForUser(packageName, userId)) {
17425                result = ArrayUtils.appendInt(result, userId);
17426            }
17427        }
17428        return result;
17429    }
17430
17431    @Override
17432    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17433        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17434    }
17435
17436    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17437        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17438                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17439        try {
17440            if (dpm != null) {
17441                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17442                        /* callingUserOnly =*/ false);
17443                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17444                        : deviceOwnerComponentName.getPackageName();
17445                // Does the package contains the device owner?
17446                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17447                // this check is probably not needed, since DO should be registered as a device
17448                // admin on some user too. (Original bug for this: b/17657954)
17449                if (packageName.equals(deviceOwnerPackageName)) {
17450                    return true;
17451                }
17452                // Does it contain a device admin for any user?
17453                int[] users;
17454                if (userId == UserHandle.USER_ALL) {
17455                    users = sUserManager.getUserIds();
17456                } else {
17457                    users = new int[]{userId};
17458                }
17459                for (int i = 0; i < users.length; ++i) {
17460                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17461                        return true;
17462                    }
17463                }
17464            }
17465        } catch (RemoteException e) {
17466        }
17467        return false;
17468    }
17469
17470    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17471        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17472    }
17473
17474    /**
17475     *  This method is an internal method that could be get invoked either
17476     *  to delete an installed package or to clean up a failed installation.
17477     *  After deleting an installed package, a broadcast is sent to notify any
17478     *  listeners that the package has been removed. For cleaning up a failed
17479     *  installation, the broadcast is not necessary since the package's
17480     *  installation wouldn't have sent the initial broadcast either
17481     *  The key steps in deleting a package are
17482     *  deleting the package information in internal structures like mPackages,
17483     *  deleting the packages base directories through installd
17484     *  updating mSettings to reflect current status
17485     *  persisting settings for later use
17486     *  sending a broadcast if necessary
17487     */
17488    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17489        final PackageRemovedInfo info = new PackageRemovedInfo();
17490        final boolean res;
17491
17492        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17493                ? UserHandle.USER_ALL : userId;
17494
17495        if (isPackageDeviceAdmin(packageName, removeUser)) {
17496            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17497            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17498        }
17499
17500        PackageSetting uninstalledPs = null;
17501        PackageParser.Package pkg = null;
17502
17503        // for the uninstall-updates case and restricted profiles, remember the per-
17504        // user handle installed state
17505        int[] allUsers;
17506        synchronized (mPackages) {
17507            uninstalledPs = mSettings.mPackages.get(packageName);
17508            if (uninstalledPs == null) {
17509                Slog.w(TAG, "Not removing non-existent package " + packageName);
17510                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17511            }
17512
17513            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17514                    && uninstalledPs.versionCode != versionCode) {
17515                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17516                        + uninstalledPs.versionCode + " != " + versionCode);
17517                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17518            }
17519
17520            // Static shared libs can be declared by any package, so let us not
17521            // allow removing a package if it provides a lib others depend on.
17522            pkg = mPackages.get(packageName);
17523            if (pkg != null && pkg.staticSharedLibName != null) {
17524                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17525                        pkg.staticSharedLibVersion);
17526                if (libEntry != null) {
17527                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17528                            libEntry.info, 0, userId);
17529                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17530                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17531                                + " hosting lib " + libEntry.info.getName() + " version "
17532                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17533                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17534                    }
17535                }
17536            }
17537
17538            allUsers = sUserManager.getUserIds();
17539            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17540        }
17541
17542        final int freezeUser;
17543        if (isUpdatedSystemApp(uninstalledPs)
17544                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17545            // We're downgrading a system app, which will apply to all users, so
17546            // freeze them all during the downgrade
17547            freezeUser = UserHandle.USER_ALL;
17548        } else {
17549            freezeUser = removeUser;
17550        }
17551
17552        synchronized (mInstallLock) {
17553            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17554            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17555                    deleteFlags, "deletePackageX")) {
17556                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17557                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17558            }
17559            synchronized (mPackages) {
17560                if (res) {
17561                    if (pkg != null) {
17562                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17563                    }
17564                    updateSequenceNumberLP(packageName, info.removedUsers);
17565                    updateInstantAppInstallerLocked();
17566                }
17567            }
17568        }
17569
17570        if (res) {
17571            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17572            info.sendPackageRemovedBroadcasts(killApp);
17573            info.sendSystemPackageUpdatedBroadcasts();
17574            info.sendSystemPackageAppearedBroadcasts();
17575        }
17576        // Force a gc here.
17577        Runtime.getRuntime().gc();
17578        // Delete the resources here after sending the broadcast to let
17579        // other processes clean up before deleting resources.
17580        if (info.args != null) {
17581            synchronized (mInstallLock) {
17582                info.args.doPostDeleteLI(true);
17583            }
17584        }
17585
17586        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17587    }
17588
17589    class PackageRemovedInfo {
17590        String removedPackage;
17591        int uid = -1;
17592        int removedAppId = -1;
17593        int[] origUsers;
17594        int[] removedUsers = null;
17595        SparseArray<Integer> installReasons;
17596        boolean isRemovedPackageSystemUpdate = false;
17597        boolean isUpdate;
17598        boolean dataRemoved;
17599        boolean removedForAllUsers;
17600        boolean isStaticSharedLib;
17601        // Clean up resources deleted packages.
17602        InstallArgs args = null;
17603        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17604        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17605
17606        void sendPackageRemovedBroadcasts(boolean killApp) {
17607            sendPackageRemovedBroadcastInternal(killApp);
17608            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17609            for (int i = 0; i < childCount; i++) {
17610                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17611                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17612            }
17613        }
17614
17615        void sendSystemPackageUpdatedBroadcasts() {
17616            if (isRemovedPackageSystemUpdate) {
17617                sendSystemPackageUpdatedBroadcastsInternal();
17618                final int childCount = (removedChildPackages != null)
17619                        ? removedChildPackages.size() : 0;
17620                for (int i = 0; i < childCount; i++) {
17621                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17622                    if (childInfo.isRemovedPackageSystemUpdate) {
17623                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17624                    }
17625                }
17626            }
17627        }
17628
17629        void sendSystemPackageAppearedBroadcasts() {
17630            final int packageCount = (appearedChildPackages != null)
17631                    ? appearedChildPackages.size() : 0;
17632            for (int i = 0; i < packageCount; i++) {
17633                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17634                sendPackageAddedForNewUsers(installedInfo.name, true,
17635                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17636            }
17637        }
17638
17639        private void sendSystemPackageUpdatedBroadcastsInternal() {
17640            Bundle extras = new Bundle(2);
17641            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17642            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17643            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17644                    extras, 0, null, null, null);
17645            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17646                    extras, 0, null, null, null);
17647            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17648                    null, 0, removedPackage, null, null);
17649        }
17650
17651        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17652            // Don't send static shared library removal broadcasts as these
17653            // libs are visible only the the apps that depend on them an one
17654            // cannot remove the library if it has a dependency.
17655            if (isStaticSharedLib) {
17656                return;
17657            }
17658            Bundle extras = new Bundle(2);
17659            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17660            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17661            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17662            if (isUpdate || isRemovedPackageSystemUpdate) {
17663                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17664            }
17665            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17666            if (removedPackage != null) {
17667                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17668                        extras, 0, null, null, removedUsers);
17669                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17670                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17671                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17672                            null, null, removedUsers);
17673                }
17674            }
17675            if (removedAppId >= 0) {
17676                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17677                        removedUsers);
17678            }
17679        }
17680    }
17681
17682    /*
17683     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17684     * flag is not set, the data directory is removed as well.
17685     * make sure this flag is set for partially installed apps. If not its meaningless to
17686     * delete a partially installed application.
17687     */
17688    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17689            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17690        String packageName = ps.name;
17691        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17692        // Retrieve object to delete permissions for shared user later on
17693        final PackageParser.Package deletedPkg;
17694        final PackageSetting deletedPs;
17695        // reader
17696        synchronized (mPackages) {
17697            deletedPkg = mPackages.get(packageName);
17698            deletedPs = mSettings.mPackages.get(packageName);
17699            if (outInfo != null) {
17700                outInfo.removedPackage = packageName;
17701                outInfo.isStaticSharedLib = deletedPkg != null
17702                        && deletedPkg.staticSharedLibName != null;
17703                outInfo.removedUsers = deletedPs != null
17704                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17705                        : null;
17706            }
17707        }
17708
17709        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17710
17711        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17712            final PackageParser.Package resolvedPkg;
17713            if (deletedPkg != null) {
17714                resolvedPkg = deletedPkg;
17715            } else {
17716                // We don't have a parsed package when it lives on an ejected
17717                // adopted storage device, so fake something together
17718                resolvedPkg = new PackageParser.Package(ps.name);
17719                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17720            }
17721            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17722                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17723            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17724            if (outInfo != null) {
17725                outInfo.dataRemoved = true;
17726            }
17727            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17728        }
17729
17730        int removedAppId = -1;
17731
17732        // writer
17733        synchronized (mPackages) {
17734            boolean installedStateChanged = false;
17735            if (deletedPs != null) {
17736                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17737                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17738                    clearDefaultBrowserIfNeeded(packageName);
17739                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17740                    removedAppId = mSettings.removePackageLPw(packageName);
17741                    if (outInfo != null) {
17742                        outInfo.removedAppId = removedAppId;
17743                    }
17744                    updatePermissionsLPw(deletedPs.name, null, 0);
17745                    if (deletedPs.sharedUser != null) {
17746                        // Remove permissions associated with package. Since runtime
17747                        // permissions are per user we have to kill the removed package
17748                        // or packages running under the shared user of the removed
17749                        // package if revoking the permissions requested only by the removed
17750                        // package is successful and this causes a change in gids.
17751                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17752                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17753                                    userId);
17754                            if (userIdToKill == UserHandle.USER_ALL
17755                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17756                                // If gids changed for this user, kill all affected packages.
17757                                mHandler.post(new Runnable() {
17758                                    @Override
17759                                    public void run() {
17760                                        // This has to happen with no lock held.
17761                                        killApplication(deletedPs.name, deletedPs.appId,
17762                                                KILL_APP_REASON_GIDS_CHANGED);
17763                                    }
17764                                });
17765                                break;
17766                            }
17767                        }
17768                    }
17769                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17770                }
17771                // make sure to preserve per-user disabled state if this removal was just
17772                // a downgrade of a system app to the factory package
17773                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17774                    if (DEBUG_REMOVE) {
17775                        Slog.d(TAG, "Propagating install state across downgrade");
17776                    }
17777                    for (int userId : allUserHandles) {
17778                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17779                        if (DEBUG_REMOVE) {
17780                            Slog.d(TAG, "    user " + userId + " => " + installed);
17781                        }
17782                        if (installed != ps.getInstalled(userId)) {
17783                            installedStateChanged = true;
17784                        }
17785                        ps.setInstalled(installed, userId);
17786                    }
17787                }
17788            }
17789            // can downgrade to reader
17790            if (writeSettings) {
17791                // Save settings now
17792                mSettings.writeLPr();
17793            }
17794            if (installedStateChanged) {
17795                mSettings.writeKernelMappingLPr(ps);
17796            }
17797        }
17798        if (removedAppId != -1) {
17799            // A user ID was deleted here. Go through all users and remove it
17800            // from KeyStore.
17801            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17802        }
17803    }
17804
17805    static boolean locationIsPrivileged(File path) {
17806        try {
17807            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17808                    .getCanonicalPath();
17809            return path.getCanonicalPath().startsWith(privilegedAppDir);
17810        } catch (IOException e) {
17811            Slog.e(TAG, "Unable to access code path " + path);
17812        }
17813        return false;
17814    }
17815
17816    /*
17817     * Tries to delete system package.
17818     */
17819    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17820            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17821            boolean writeSettings) {
17822        if (deletedPs.parentPackageName != null) {
17823            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17824            return false;
17825        }
17826
17827        final boolean applyUserRestrictions
17828                = (allUserHandles != null) && (outInfo.origUsers != null);
17829        final PackageSetting disabledPs;
17830        // Confirm if the system package has been updated
17831        // An updated system app can be deleted. This will also have to restore
17832        // the system pkg from system partition
17833        // reader
17834        synchronized (mPackages) {
17835            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17836        }
17837
17838        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17839                + " disabledPs=" + disabledPs);
17840
17841        if (disabledPs == null) {
17842            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17843            return false;
17844        } else if (DEBUG_REMOVE) {
17845            Slog.d(TAG, "Deleting system pkg from data partition");
17846        }
17847
17848        if (DEBUG_REMOVE) {
17849            if (applyUserRestrictions) {
17850                Slog.d(TAG, "Remembering install states:");
17851                for (int userId : allUserHandles) {
17852                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17853                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17854                }
17855            }
17856        }
17857
17858        // Delete the updated package
17859        outInfo.isRemovedPackageSystemUpdate = true;
17860        if (outInfo.removedChildPackages != null) {
17861            final int childCount = (deletedPs.childPackageNames != null)
17862                    ? deletedPs.childPackageNames.size() : 0;
17863            for (int i = 0; i < childCount; i++) {
17864                String childPackageName = deletedPs.childPackageNames.get(i);
17865                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17866                        .contains(childPackageName)) {
17867                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17868                            childPackageName);
17869                    if (childInfo != null) {
17870                        childInfo.isRemovedPackageSystemUpdate = true;
17871                    }
17872                }
17873            }
17874        }
17875
17876        if (disabledPs.versionCode < deletedPs.versionCode) {
17877            // Delete data for downgrades
17878            flags &= ~PackageManager.DELETE_KEEP_DATA;
17879        } else {
17880            // Preserve data by setting flag
17881            flags |= PackageManager.DELETE_KEEP_DATA;
17882        }
17883
17884        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17885                outInfo, writeSettings, disabledPs.pkg);
17886        if (!ret) {
17887            return false;
17888        }
17889
17890        // writer
17891        synchronized (mPackages) {
17892            // Reinstate the old system package
17893            enableSystemPackageLPw(disabledPs.pkg);
17894            // Remove any native libraries from the upgraded package.
17895            removeNativeBinariesLI(deletedPs);
17896        }
17897
17898        // Install the system package
17899        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17900        int parseFlags = mDefParseFlags
17901                | PackageParser.PARSE_MUST_BE_APK
17902                | PackageParser.PARSE_IS_SYSTEM
17903                | PackageParser.PARSE_IS_SYSTEM_DIR;
17904        if (locationIsPrivileged(disabledPs.codePath)) {
17905            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17906        }
17907
17908        final PackageParser.Package newPkg;
17909        try {
17910            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17911                0 /* currentTime */, null);
17912        } catch (PackageManagerException e) {
17913            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17914                    + e.getMessage());
17915            return false;
17916        }
17917
17918        try {
17919            // update shared libraries for the newly re-installed system package
17920            updateSharedLibrariesLPr(newPkg, null);
17921        } catch (PackageManagerException e) {
17922            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17923        }
17924
17925        prepareAppDataAfterInstallLIF(newPkg);
17926
17927        // writer
17928        synchronized (mPackages) {
17929            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17930
17931            // Propagate the permissions state as we do not want to drop on the floor
17932            // runtime permissions. The update permissions method below will take
17933            // care of removing obsolete permissions and grant install permissions.
17934            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17935            updatePermissionsLPw(newPkg.packageName, newPkg,
17936                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17937
17938            if (applyUserRestrictions) {
17939                boolean installedStateChanged = false;
17940                if (DEBUG_REMOVE) {
17941                    Slog.d(TAG, "Propagating install state across reinstall");
17942                }
17943                for (int userId : allUserHandles) {
17944                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17945                    if (DEBUG_REMOVE) {
17946                        Slog.d(TAG, "    user " + userId + " => " + installed);
17947                    }
17948                    if (installed != ps.getInstalled(userId)) {
17949                        installedStateChanged = true;
17950                    }
17951                    ps.setInstalled(installed, userId);
17952
17953                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17954                }
17955                // Regardless of writeSettings we need to ensure that this restriction
17956                // state propagation is persisted
17957                mSettings.writeAllUsersPackageRestrictionsLPr();
17958                if (installedStateChanged) {
17959                    mSettings.writeKernelMappingLPr(ps);
17960                }
17961            }
17962            // can downgrade to reader here
17963            if (writeSettings) {
17964                mSettings.writeLPr();
17965            }
17966        }
17967        return true;
17968    }
17969
17970    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17971            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17972            PackageRemovedInfo outInfo, boolean writeSettings,
17973            PackageParser.Package replacingPackage) {
17974        synchronized (mPackages) {
17975            if (outInfo != null) {
17976                outInfo.uid = ps.appId;
17977            }
17978
17979            if (outInfo != null && outInfo.removedChildPackages != null) {
17980                final int childCount = (ps.childPackageNames != null)
17981                        ? ps.childPackageNames.size() : 0;
17982                for (int i = 0; i < childCount; i++) {
17983                    String childPackageName = ps.childPackageNames.get(i);
17984                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17985                    if (childPs == null) {
17986                        return false;
17987                    }
17988                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17989                            childPackageName);
17990                    if (childInfo != null) {
17991                        childInfo.uid = childPs.appId;
17992                    }
17993                }
17994            }
17995        }
17996
17997        // Delete package data from internal structures and also remove data if flag is set
17998        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17999
18000        // Delete the child packages data
18001        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18002        for (int i = 0; i < childCount; i++) {
18003            PackageSetting childPs;
18004            synchronized (mPackages) {
18005                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18006            }
18007            if (childPs != null) {
18008                PackageRemovedInfo childOutInfo = (outInfo != null
18009                        && outInfo.removedChildPackages != null)
18010                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18011                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18012                        && (replacingPackage != null
18013                        && !replacingPackage.hasChildPackage(childPs.name))
18014                        ? flags & ~DELETE_KEEP_DATA : flags;
18015                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18016                        deleteFlags, writeSettings);
18017            }
18018        }
18019
18020        // Delete application code and resources only for parent packages
18021        if (ps.parentPackageName == null) {
18022            if (deleteCodeAndResources && (outInfo != null)) {
18023                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18024                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18025                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18026            }
18027        }
18028
18029        return true;
18030    }
18031
18032    @Override
18033    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18034            int userId) {
18035        mContext.enforceCallingOrSelfPermission(
18036                android.Manifest.permission.DELETE_PACKAGES, null);
18037        synchronized (mPackages) {
18038            PackageSetting ps = mSettings.mPackages.get(packageName);
18039            if (ps == null) {
18040                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18041                return false;
18042            }
18043            // Cannot block uninstall of static shared libs as they are
18044            // considered a part of the using app (emulating static linking).
18045            // Also static libs are installed always on internal storage.
18046            PackageParser.Package pkg = mPackages.get(packageName);
18047            if (pkg != null && pkg.staticSharedLibName != null) {
18048                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18049                        + " providing static shared library: " + pkg.staticSharedLibName);
18050                return false;
18051            }
18052            if (!ps.getInstalled(userId)) {
18053                // Can't block uninstall for an app that is not installed or enabled.
18054                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18055                return false;
18056            }
18057            ps.setBlockUninstall(blockUninstall, userId);
18058            mSettings.writePackageRestrictionsLPr(userId);
18059        }
18060        return true;
18061    }
18062
18063    @Override
18064    public boolean getBlockUninstallForUser(String packageName, int userId) {
18065        synchronized (mPackages) {
18066            PackageSetting ps = mSettings.mPackages.get(packageName);
18067            if (ps == null) {
18068                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18069                return false;
18070            }
18071            return ps.getBlockUninstall(userId);
18072        }
18073    }
18074
18075    @Override
18076    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18077        int callingUid = Binder.getCallingUid();
18078        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18079            throw new SecurityException(
18080                    "setRequiredForSystemUser can only be run by the system or root");
18081        }
18082        synchronized (mPackages) {
18083            PackageSetting ps = mSettings.mPackages.get(packageName);
18084            if (ps == null) {
18085                Log.w(TAG, "Package doesn't exist: " + packageName);
18086                return false;
18087            }
18088            if (systemUserApp) {
18089                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18090            } else {
18091                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18092            }
18093            mSettings.writeLPr();
18094        }
18095        return true;
18096    }
18097
18098    /*
18099     * This method handles package deletion in general
18100     */
18101    private boolean deletePackageLIF(String packageName, UserHandle user,
18102            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18103            PackageRemovedInfo outInfo, boolean writeSettings,
18104            PackageParser.Package replacingPackage) {
18105        if (packageName == null) {
18106            Slog.w(TAG, "Attempt to delete null packageName.");
18107            return false;
18108        }
18109
18110        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18111
18112        PackageSetting ps;
18113        synchronized (mPackages) {
18114            ps = mSettings.mPackages.get(packageName);
18115            if (ps == null) {
18116                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18117                return false;
18118            }
18119
18120            if (ps.parentPackageName != null && (!isSystemApp(ps)
18121                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18122                if (DEBUG_REMOVE) {
18123                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18124                            + ((user == null) ? UserHandle.USER_ALL : user));
18125                }
18126                final int removedUserId = (user != null) ? user.getIdentifier()
18127                        : UserHandle.USER_ALL;
18128                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18129                    return false;
18130                }
18131                markPackageUninstalledForUserLPw(ps, user);
18132                scheduleWritePackageRestrictionsLocked(user);
18133                return true;
18134            }
18135        }
18136
18137        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18138                && user.getIdentifier() != UserHandle.USER_ALL)) {
18139            // The caller is asking that the package only be deleted for a single
18140            // user.  To do this, we just mark its uninstalled state and delete
18141            // its data. If this is a system app, we only allow this to happen if
18142            // they have set the special DELETE_SYSTEM_APP which requests different
18143            // semantics than normal for uninstalling system apps.
18144            markPackageUninstalledForUserLPw(ps, user);
18145
18146            if (!isSystemApp(ps)) {
18147                // Do not uninstall the APK if an app should be cached
18148                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18149                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18150                    // Other user still have this package installed, so all
18151                    // we need to do is clear this user's data and save that
18152                    // it is uninstalled.
18153                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18154                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18155                        return false;
18156                    }
18157                    scheduleWritePackageRestrictionsLocked(user);
18158                    return true;
18159                } else {
18160                    // We need to set it back to 'installed' so the uninstall
18161                    // broadcasts will be sent correctly.
18162                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18163                    ps.setInstalled(true, user.getIdentifier());
18164                    mSettings.writeKernelMappingLPr(ps);
18165                }
18166            } else {
18167                // This is a system app, so we assume that the
18168                // other users still have this package installed, so all
18169                // we need to do is clear this user's data and save that
18170                // it is uninstalled.
18171                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18172                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18173                    return false;
18174                }
18175                scheduleWritePackageRestrictionsLocked(user);
18176                return true;
18177            }
18178        }
18179
18180        // If we are deleting a composite package for all users, keep track
18181        // of result for each child.
18182        if (ps.childPackageNames != null && outInfo != null) {
18183            synchronized (mPackages) {
18184                final int childCount = ps.childPackageNames.size();
18185                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18186                for (int i = 0; i < childCount; i++) {
18187                    String childPackageName = ps.childPackageNames.get(i);
18188                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18189                    childInfo.removedPackage = childPackageName;
18190                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18191                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18192                    if (childPs != null) {
18193                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18194                    }
18195                }
18196            }
18197        }
18198
18199        boolean ret = false;
18200        if (isSystemApp(ps)) {
18201            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18202            // When an updated system application is deleted we delete the existing resources
18203            // as well and fall back to existing code in system partition
18204            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18205        } else {
18206            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18207            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18208                    outInfo, writeSettings, replacingPackage);
18209        }
18210
18211        // Take a note whether we deleted the package for all users
18212        if (outInfo != null) {
18213            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18214            if (outInfo.removedChildPackages != null) {
18215                synchronized (mPackages) {
18216                    final int childCount = outInfo.removedChildPackages.size();
18217                    for (int i = 0; i < childCount; i++) {
18218                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18219                        if (childInfo != null) {
18220                            childInfo.removedForAllUsers = mPackages.get(
18221                                    childInfo.removedPackage) == null;
18222                        }
18223                    }
18224                }
18225            }
18226            // If we uninstalled an update to a system app there may be some
18227            // child packages that appeared as they are declared in the system
18228            // app but were not declared in the update.
18229            if (isSystemApp(ps)) {
18230                synchronized (mPackages) {
18231                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18232                    final int childCount = (updatedPs.childPackageNames != null)
18233                            ? updatedPs.childPackageNames.size() : 0;
18234                    for (int i = 0; i < childCount; i++) {
18235                        String childPackageName = updatedPs.childPackageNames.get(i);
18236                        if (outInfo.removedChildPackages == null
18237                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18238                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18239                            if (childPs == null) {
18240                                continue;
18241                            }
18242                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18243                            installRes.name = childPackageName;
18244                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18245                            installRes.pkg = mPackages.get(childPackageName);
18246                            installRes.uid = childPs.pkg.applicationInfo.uid;
18247                            if (outInfo.appearedChildPackages == null) {
18248                                outInfo.appearedChildPackages = new ArrayMap<>();
18249                            }
18250                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18251                        }
18252                    }
18253                }
18254            }
18255        }
18256
18257        return ret;
18258    }
18259
18260    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18261        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18262                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18263        for (int nextUserId : userIds) {
18264            if (DEBUG_REMOVE) {
18265                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18266            }
18267            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18268                    false /*installed*/,
18269                    true /*stopped*/,
18270                    true /*notLaunched*/,
18271                    false /*hidden*/,
18272                    false /*suspended*/,
18273                    false /*instantApp*/,
18274                    null /*lastDisableAppCaller*/,
18275                    null /*enabledComponents*/,
18276                    null /*disabledComponents*/,
18277                    false /*blockUninstall*/,
18278                    ps.readUserState(nextUserId).domainVerificationStatus,
18279                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18280        }
18281        mSettings.writeKernelMappingLPr(ps);
18282    }
18283
18284    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18285            PackageRemovedInfo outInfo) {
18286        final PackageParser.Package pkg;
18287        synchronized (mPackages) {
18288            pkg = mPackages.get(ps.name);
18289        }
18290
18291        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18292                : new int[] {userId};
18293        for (int nextUserId : userIds) {
18294            if (DEBUG_REMOVE) {
18295                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18296                        + nextUserId);
18297            }
18298
18299            destroyAppDataLIF(pkg, userId,
18300                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18301            destroyAppProfilesLIF(pkg, userId);
18302            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18303            schedulePackageCleaning(ps.name, nextUserId, false);
18304            synchronized (mPackages) {
18305                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18306                    scheduleWritePackageRestrictionsLocked(nextUserId);
18307                }
18308                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18309            }
18310        }
18311
18312        if (outInfo != null) {
18313            outInfo.removedPackage = ps.name;
18314            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18315            outInfo.removedAppId = ps.appId;
18316            outInfo.removedUsers = userIds;
18317        }
18318
18319        return true;
18320    }
18321
18322    private final class ClearStorageConnection implements ServiceConnection {
18323        IMediaContainerService mContainerService;
18324
18325        @Override
18326        public void onServiceConnected(ComponentName name, IBinder service) {
18327            synchronized (this) {
18328                mContainerService = IMediaContainerService.Stub
18329                        .asInterface(Binder.allowBlocking(service));
18330                notifyAll();
18331            }
18332        }
18333
18334        @Override
18335        public void onServiceDisconnected(ComponentName name) {
18336        }
18337    }
18338
18339    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18340        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18341
18342        final boolean mounted;
18343        if (Environment.isExternalStorageEmulated()) {
18344            mounted = true;
18345        } else {
18346            final String status = Environment.getExternalStorageState();
18347
18348            mounted = status.equals(Environment.MEDIA_MOUNTED)
18349                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18350        }
18351
18352        if (!mounted) {
18353            return;
18354        }
18355
18356        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18357        int[] users;
18358        if (userId == UserHandle.USER_ALL) {
18359            users = sUserManager.getUserIds();
18360        } else {
18361            users = new int[] { userId };
18362        }
18363        final ClearStorageConnection conn = new ClearStorageConnection();
18364        if (mContext.bindServiceAsUser(
18365                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18366            try {
18367                for (int curUser : users) {
18368                    long timeout = SystemClock.uptimeMillis() + 5000;
18369                    synchronized (conn) {
18370                        long now;
18371                        while (conn.mContainerService == null &&
18372                                (now = SystemClock.uptimeMillis()) < timeout) {
18373                            try {
18374                                conn.wait(timeout - now);
18375                            } catch (InterruptedException e) {
18376                            }
18377                        }
18378                    }
18379                    if (conn.mContainerService == null) {
18380                        return;
18381                    }
18382
18383                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18384                    clearDirectory(conn.mContainerService,
18385                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18386                    if (allData) {
18387                        clearDirectory(conn.mContainerService,
18388                                userEnv.buildExternalStorageAppDataDirs(packageName));
18389                        clearDirectory(conn.mContainerService,
18390                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18391                    }
18392                }
18393            } finally {
18394                mContext.unbindService(conn);
18395            }
18396        }
18397    }
18398
18399    @Override
18400    public void clearApplicationProfileData(String packageName) {
18401        enforceSystemOrRoot("Only the system can clear all profile data");
18402
18403        final PackageParser.Package pkg;
18404        synchronized (mPackages) {
18405            pkg = mPackages.get(packageName);
18406        }
18407
18408        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18409            synchronized (mInstallLock) {
18410                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18411            }
18412        }
18413    }
18414
18415    @Override
18416    public void clearApplicationUserData(final String packageName,
18417            final IPackageDataObserver observer, final int userId) {
18418        mContext.enforceCallingOrSelfPermission(
18419                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18420
18421        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18422                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18423
18424        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18425            throw new SecurityException("Cannot clear data for a protected package: "
18426                    + packageName);
18427        }
18428        // Queue up an async operation since the package deletion may take a little while.
18429        mHandler.post(new Runnable() {
18430            public void run() {
18431                mHandler.removeCallbacks(this);
18432                final boolean succeeded;
18433                try (PackageFreezer freezer = freezePackage(packageName,
18434                        "clearApplicationUserData")) {
18435                    synchronized (mInstallLock) {
18436                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18437                    }
18438                    clearExternalStorageDataSync(packageName, userId, true);
18439                    synchronized (mPackages) {
18440                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18441                                packageName, userId);
18442                    }
18443                }
18444                if (succeeded) {
18445                    // invoke DeviceStorageMonitor's update method to clear any notifications
18446                    DeviceStorageMonitorInternal dsm = LocalServices
18447                            .getService(DeviceStorageMonitorInternal.class);
18448                    if (dsm != null) {
18449                        dsm.checkMemory();
18450                    }
18451                }
18452                if(observer != null) {
18453                    try {
18454                        observer.onRemoveCompleted(packageName, succeeded);
18455                    } catch (RemoteException e) {
18456                        Log.i(TAG, "Observer no longer exists.");
18457                    }
18458                } //end if observer
18459            } //end run
18460        });
18461    }
18462
18463    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18464        if (packageName == null) {
18465            Slog.w(TAG, "Attempt to delete null packageName.");
18466            return false;
18467        }
18468
18469        // Try finding details about the requested package
18470        PackageParser.Package pkg;
18471        synchronized (mPackages) {
18472            pkg = mPackages.get(packageName);
18473            if (pkg == null) {
18474                final PackageSetting ps = mSettings.mPackages.get(packageName);
18475                if (ps != null) {
18476                    pkg = ps.pkg;
18477                }
18478            }
18479
18480            if (pkg == null) {
18481                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18482                return false;
18483            }
18484
18485            PackageSetting ps = (PackageSetting) pkg.mExtras;
18486            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18487        }
18488
18489        clearAppDataLIF(pkg, userId,
18490                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18491
18492        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18493        removeKeystoreDataIfNeeded(userId, appId);
18494
18495        UserManagerInternal umInternal = getUserManagerInternal();
18496        final int flags;
18497        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18498            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18499        } else if (umInternal.isUserRunning(userId)) {
18500            flags = StorageManager.FLAG_STORAGE_DE;
18501        } else {
18502            flags = 0;
18503        }
18504        prepareAppDataContentsLIF(pkg, userId, flags);
18505
18506        return true;
18507    }
18508
18509    /**
18510     * Reverts user permission state changes (permissions and flags) in
18511     * all packages for a given user.
18512     *
18513     * @param userId The device user for which to do a reset.
18514     */
18515    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18516        final int packageCount = mPackages.size();
18517        for (int i = 0; i < packageCount; i++) {
18518            PackageParser.Package pkg = mPackages.valueAt(i);
18519            PackageSetting ps = (PackageSetting) pkg.mExtras;
18520            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18521        }
18522    }
18523
18524    private void resetNetworkPolicies(int userId) {
18525        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18526    }
18527
18528    /**
18529     * Reverts user permission state changes (permissions and flags).
18530     *
18531     * @param ps The package for which to reset.
18532     * @param userId The device user for which to do a reset.
18533     */
18534    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18535            final PackageSetting ps, final int userId) {
18536        if (ps.pkg == null) {
18537            return;
18538        }
18539
18540        // These are flags that can change base on user actions.
18541        final int userSettableMask = FLAG_PERMISSION_USER_SET
18542                | FLAG_PERMISSION_USER_FIXED
18543                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18544                | FLAG_PERMISSION_REVIEW_REQUIRED;
18545
18546        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18547                | FLAG_PERMISSION_POLICY_FIXED;
18548
18549        boolean writeInstallPermissions = false;
18550        boolean writeRuntimePermissions = false;
18551
18552        final int permissionCount = ps.pkg.requestedPermissions.size();
18553        for (int i = 0; i < permissionCount; i++) {
18554            String permission = ps.pkg.requestedPermissions.get(i);
18555
18556            BasePermission bp = mSettings.mPermissions.get(permission);
18557            if (bp == null) {
18558                continue;
18559            }
18560
18561            // If shared user we just reset the state to which only this app contributed.
18562            if (ps.sharedUser != null) {
18563                boolean used = false;
18564                final int packageCount = ps.sharedUser.packages.size();
18565                for (int j = 0; j < packageCount; j++) {
18566                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18567                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18568                            && pkg.pkg.requestedPermissions.contains(permission)) {
18569                        used = true;
18570                        break;
18571                    }
18572                }
18573                if (used) {
18574                    continue;
18575                }
18576            }
18577
18578            PermissionsState permissionsState = ps.getPermissionsState();
18579
18580            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18581
18582            // Always clear the user settable flags.
18583            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18584                    bp.name) != null;
18585            // If permission review is enabled and this is a legacy app, mark the
18586            // permission as requiring a review as this is the initial state.
18587            int flags = 0;
18588            if (mPermissionReviewRequired
18589                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18590                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18591            }
18592            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18593                if (hasInstallState) {
18594                    writeInstallPermissions = true;
18595                } else {
18596                    writeRuntimePermissions = true;
18597                }
18598            }
18599
18600            // Below is only runtime permission handling.
18601            if (!bp.isRuntime()) {
18602                continue;
18603            }
18604
18605            // Never clobber system or policy.
18606            if ((oldFlags & policyOrSystemFlags) != 0) {
18607                continue;
18608            }
18609
18610            // If this permission was granted by default, make sure it is.
18611            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18612                if (permissionsState.grantRuntimePermission(bp, userId)
18613                        != PERMISSION_OPERATION_FAILURE) {
18614                    writeRuntimePermissions = true;
18615                }
18616            // If permission review is enabled the permissions for a legacy apps
18617            // are represented as constantly granted runtime ones, so don't revoke.
18618            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18619                // Otherwise, reset the permission.
18620                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18621                switch (revokeResult) {
18622                    case PERMISSION_OPERATION_SUCCESS:
18623                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18624                        writeRuntimePermissions = true;
18625                        final int appId = ps.appId;
18626                        mHandler.post(new Runnable() {
18627                            @Override
18628                            public void run() {
18629                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18630                            }
18631                        });
18632                    } break;
18633                }
18634            }
18635        }
18636
18637        // Synchronously write as we are taking permissions away.
18638        if (writeRuntimePermissions) {
18639            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18640        }
18641
18642        // Synchronously write as we are taking permissions away.
18643        if (writeInstallPermissions) {
18644            mSettings.writeLPr();
18645        }
18646    }
18647
18648    /**
18649     * Remove entries from the keystore daemon. Will only remove it if the
18650     * {@code appId} is valid.
18651     */
18652    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18653        if (appId < 0) {
18654            return;
18655        }
18656
18657        final KeyStore keyStore = KeyStore.getInstance();
18658        if (keyStore != null) {
18659            if (userId == UserHandle.USER_ALL) {
18660                for (final int individual : sUserManager.getUserIds()) {
18661                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18662                }
18663            } else {
18664                keyStore.clearUid(UserHandle.getUid(userId, appId));
18665            }
18666        } else {
18667            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18668        }
18669    }
18670
18671    @Override
18672    public void deleteApplicationCacheFiles(final String packageName,
18673            final IPackageDataObserver observer) {
18674        final int userId = UserHandle.getCallingUserId();
18675        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18676    }
18677
18678    @Override
18679    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18680            final IPackageDataObserver observer) {
18681        mContext.enforceCallingOrSelfPermission(
18682                android.Manifest.permission.DELETE_CACHE_FILES, null);
18683        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18684                /* requireFullPermission= */ true, /* checkShell= */ false,
18685                "delete application cache files");
18686
18687        final PackageParser.Package pkg;
18688        synchronized (mPackages) {
18689            pkg = mPackages.get(packageName);
18690        }
18691
18692        // Queue up an async operation since the package deletion may take a little while.
18693        mHandler.post(new Runnable() {
18694            public void run() {
18695                synchronized (mInstallLock) {
18696                    final int flags = StorageManager.FLAG_STORAGE_DE
18697                            | StorageManager.FLAG_STORAGE_CE;
18698                    // We're only clearing cache files, so we don't care if the
18699                    // app is unfrozen and still able to run
18700                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18701                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18702                }
18703                clearExternalStorageDataSync(packageName, userId, false);
18704                if (observer != null) {
18705                    try {
18706                        observer.onRemoveCompleted(packageName, true);
18707                    } catch (RemoteException e) {
18708                        Log.i(TAG, "Observer no longer exists.");
18709                    }
18710                }
18711            }
18712        });
18713    }
18714
18715    @Override
18716    public void getPackageSizeInfo(final String packageName, int userHandle,
18717            final IPackageStatsObserver observer) {
18718        throw new UnsupportedOperationException(
18719                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18720    }
18721
18722    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18723        final PackageSetting ps;
18724        synchronized (mPackages) {
18725            ps = mSettings.mPackages.get(packageName);
18726            if (ps == null) {
18727                Slog.w(TAG, "Failed to find settings for " + packageName);
18728                return false;
18729            }
18730        }
18731
18732        final String[] packageNames = { packageName };
18733        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18734        final String[] codePaths = { ps.codePathString };
18735
18736        try {
18737            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18738                    ps.appId, ceDataInodes, codePaths, stats);
18739
18740            // For now, ignore code size of packages on system partition
18741            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18742                stats.codeSize = 0;
18743            }
18744
18745            // External clients expect these to be tracked separately
18746            stats.dataSize -= stats.cacheSize;
18747
18748        } catch (InstallerException e) {
18749            Slog.w(TAG, String.valueOf(e));
18750            return false;
18751        }
18752
18753        return true;
18754    }
18755
18756    private int getUidTargetSdkVersionLockedLPr(int uid) {
18757        Object obj = mSettings.getUserIdLPr(uid);
18758        if (obj instanceof SharedUserSetting) {
18759            final SharedUserSetting sus = (SharedUserSetting) obj;
18760            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18761            final Iterator<PackageSetting> it = sus.packages.iterator();
18762            while (it.hasNext()) {
18763                final PackageSetting ps = it.next();
18764                if (ps.pkg != null) {
18765                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18766                    if (v < vers) vers = v;
18767                }
18768            }
18769            return vers;
18770        } else if (obj instanceof PackageSetting) {
18771            final PackageSetting ps = (PackageSetting) obj;
18772            if (ps.pkg != null) {
18773                return ps.pkg.applicationInfo.targetSdkVersion;
18774            }
18775        }
18776        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18777    }
18778
18779    @Override
18780    public void addPreferredActivity(IntentFilter filter, int match,
18781            ComponentName[] set, ComponentName activity, int userId) {
18782        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18783                "Adding preferred");
18784    }
18785
18786    private void addPreferredActivityInternal(IntentFilter filter, int match,
18787            ComponentName[] set, ComponentName activity, boolean always, int userId,
18788            String opname) {
18789        // writer
18790        int callingUid = Binder.getCallingUid();
18791        enforceCrossUserPermission(callingUid, userId,
18792                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18793        if (filter.countActions() == 0) {
18794            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18795            return;
18796        }
18797        synchronized (mPackages) {
18798            if (mContext.checkCallingOrSelfPermission(
18799                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18800                    != PackageManager.PERMISSION_GRANTED) {
18801                if (getUidTargetSdkVersionLockedLPr(callingUid)
18802                        < Build.VERSION_CODES.FROYO) {
18803                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18804                            + callingUid);
18805                    return;
18806                }
18807                mContext.enforceCallingOrSelfPermission(
18808                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18809            }
18810
18811            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18812            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18813                    + userId + ":");
18814            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18815            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18816            scheduleWritePackageRestrictionsLocked(userId);
18817            postPreferredActivityChangedBroadcast(userId);
18818        }
18819    }
18820
18821    private void postPreferredActivityChangedBroadcast(int userId) {
18822        mHandler.post(() -> {
18823            final IActivityManager am = ActivityManager.getService();
18824            if (am == null) {
18825                return;
18826            }
18827
18828            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18829            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18830            try {
18831                am.broadcastIntent(null, intent, null, null,
18832                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18833                        null, false, false, userId);
18834            } catch (RemoteException e) {
18835            }
18836        });
18837    }
18838
18839    @Override
18840    public void replacePreferredActivity(IntentFilter filter, int match,
18841            ComponentName[] set, ComponentName activity, int userId) {
18842        if (filter.countActions() != 1) {
18843            throw new IllegalArgumentException(
18844                    "replacePreferredActivity expects filter to have only 1 action.");
18845        }
18846        if (filter.countDataAuthorities() != 0
18847                || filter.countDataPaths() != 0
18848                || filter.countDataSchemes() > 1
18849                || filter.countDataTypes() != 0) {
18850            throw new IllegalArgumentException(
18851                    "replacePreferredActivity expects filter to have no data authorities, " +
18852                    "paths, or types; and at most one scheme.");
18853        }
18854
18855        final int callingUid = Binder.getCallingUid();
18856        enforceCrossUserPermission(callingUid, userId,
18857                true /* requireFullPermission */, false /* checkShell */,
18858                "replace preferred activity");
18859        synchronized (mPackages) {
18860            if (mContext.checkCallingOrSelfPermission(
18861                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18862                    != PackageManager.PERMISSION_GRANTED) {
18863                if (getUidTargetSdkVersionLockedLPr(callingUid)
18864                        < Build.VERSION_CODES.FROYO) {
18865                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18866                            + Binder.getCallingUid());
18867                    return;
18868                }
18869                mContext.enforceCallingOrSelfPermission(
18870                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18871            }
18872
18873            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18874            if (pir != null) {
18875                // Get all of the existing entries that exactly match this filter.
18876                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18877                if (existing != null && existing.size() == 1) {
18878                    PreferredActivity cur = existing.get(0);
18879                    if (DEBUG_PREFERRED) {
18880                        Slog.i(TAG, "Checking replace of preferred:");
18881                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18882                        if (!cur.mPref.mAlways) {
18883                            Slog.i(TAG, "  -- CUR; not mAlways!");
18884                        } else {
18885                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18886                            Slog.i(TAG, "  -- CUR: mSet="
18887                                    + Arrays.toString(cur.mPref.mSetComponents));
18888                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18889                            Slog.i(TAG, "  -- NEW: mMatch="
18890                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18891                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18892                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18893                        }
18894                    }
18895                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18896                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18897                            && cur.mPref.sameSet(set)) {
18898                        // Setting the preferred activity to what it happens to be already
18899                        if (DEBUG_PREFERRED) {
18900                            Slog.i(TAG, "Replacing with same preferred activity "
18901                                    + cur.mPref.mShortComponent + " for user "
18902                                    + userId + ":");
18903                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18904                        }
18905                        return;
18906                    }
18907                }
18908
18909                if (existing != null) {
18910                    if (DEBUG_PREFERRED) {
18911                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18912                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18913                    }
18914                    for (int i = 0; i < existing.size(); i++) {
18915                        PreferredActivity pa = existing.get(i);
18916                        if (DEBUG_PREFERRED) {
18917                            Slog.i(TAG, "Removing existing preferred activity "
18918                                    + pa.mPref.mComponent + ":");
18919                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18920                        }
18921                        pir.removeFilter(pa);
18922                    }
18923                }
18924            }
18925            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18926                    "Replacing preferred");
18927        }
18928    }
18929
18930    @Override
18931    public void clearPackagePreferredActivities(String packageName) {
18932        final int uid = Binder.getCallingUid();
18933        // writer
18934        synchronized (mPackages) {
18935            PackageParser.Package pkg = mPackages.get(packageName);
18936            if (pkg == null || pkg.applicationInfo.uid != uid) {
18937                if (mContext.checkCallingOrSelfPermission(
18938                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18939                        != PackageManager.PERMISSION_GRANTED) {
18940                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18941                            < Build.VERSION_CODES.FROYO) {
18942                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18943                                + Binder.getCallingUid());
18944                        return;
18945                    }
18946                    mContext.enforceCallingOrSelfPermission(
18947                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18948                }
18949            }
18950
18951            int user = UserHandle.getCallingUserId();
18952            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18953                scheduleWritePackageRestrictionsLocked(user);
18954            }
18955        }
18956    }
18957
18958    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18959    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18960        ArrayList<PreferredActivity> removed = null;
18961        boolean changed = false;
18962        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18963            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18964            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18965            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18966                continue;
18967            }
18968            Iterator<PreferredActivity> it = pir.filterIterator();
18969            while (it.hasNext()) {
18970                PreferredActivity pa = it.next();
18971                // Mark entry for removal only if it matches the package name
18972                // and the entry is of type "always".
18973                if (packageName == null ||
18974                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18975                                && pa.mPref.mAlways)) {
18976                    if (removed == null) {
18977                        removed = new ArrayList<PreferredActivity>();
18978                    }
18979                    removed.add(pa);
18980                }
18981            }
18982            if (removed != null) {
18983                for (int j=0; j<removed.size(); j++) {
18984                    PreferredActivity pa = removed.get(j);
18985                    pir.removeFilter(pa);
18986                }
18987                changed = true;
18988            }
18989        }
18990        if (changed) {
18991            postPreferredActivityChangedBroadcast(userId);
18992        }
18993        return changed;
18994    }
18995
18996    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18997    private void clearIntentFilterVerificationsLPw(int userId) {
18998        final int packageCount = mPackages.size();
18999        for (int i = 0; i < packageCount; i++) {
19000            PackageParser.Package pkg = mPackages.valueAt(i);
19001            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19002        }
19003    }
19004
19005    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19006    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19007        if (userId == UserHandle.USER_ALL) {
19008            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19009                    sUserManager.getUserIds())) {
19010                for (int oneUserId : sUserManager.getUserIds()) {
19011                    scheduleWritePackageRestrictionsLocked(oneUserId);
19012                }
19013            }
19014        } else {
19015            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19016                scheduleWritePackageRestrictionsLocked(userId);
19017            }
19018        }
19019    }
19020
19021    void clearDefaultBrowserIfNeeded(String packageName) {
19022        for (int oneUserId : sUserManager.getUserIds()) {
19023            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19024            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19025            if (packageName.equals(defaultBrowserPackageName)) {
19026                setDefaultBrowserPackageName(null, oneUserId);
19027            }
19028        }
19029    }
19030
19031    @Override
19032    public void resetApplicationPreferences(int userId) {
19033        mContext.enforceCallingOrSelfPermission(
19034                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19035        final long identity = Binder.clearCallingIdentity();
19036        // writer
19037        try {
19038            synchronized (mPackages) {
19039                clearPackagePreferredActivitiesLPw(null, userId);
19040                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19041                // TODO: We have to reset the default SMS and Phone. This requires
19042                // significant refactoring to keep all default apps in the package
19043                // manager (cleaner but more work) or have the services provide
19044                // callbacks to the package manager to request a default app reset.
19045                applyFactoryDefaultBrowserLPw(userId);
19046                clearIntentFilterVerificationsLPw(userId);
19047                primeDomainVerificationsLPw(userId);
19048                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19049                scheduleWritePackageRestrictionsLocked(userId);
19050            }
19051            resetNetworkPolicies(userId);
19052        } finally {
19053            Binder.restoreCallingIdentity(identity);
19054        }
19055    }
19056
19057    @Override
19058    public int getPreferredActivities(List<IntentFilter> outFilters,
19059            List<ComponentName> outActivities, String packageName) {
19060
19061        int num = 0;
19062        final int userId = UserHandle.getCallingUserId();
19063        // reader
19064        synchronized (mPackages) {
19065            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19066            if (pir != null) {
19067                final Iterator<PreferredActivity> it = pir.filterIterator();
19068                while (it.hasNext()) {
19069                    final PreferredActivity pa = it.next();
19070                    if (packageName == null
19071                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19072                                    && pa.mPref.mAlways)) {
19073                        if (outFilters != null) {
19074                            outFilters.add(new IntentFilter(pa));
19075                        }
19076                        if (outActivities != null) {
19077                            outActivities.add(pa.mPref.mComponent);
19078                        }
19079                    }
19080                }
19081            }
19082        }
19083
19084        return num;
19085    }
19086
19087    @Override
19088    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19089            int userId) {
19090        int callingUid = Binder.getCallingUid();
19091        if (callingUid != Process.SYSTEM_UID) {
19092            throw new SecurityException(
19093                    "addPersistentPreferredActivity can only be run by the system");
19094        }
19095        if (filter.countActions() == 0) {
19096            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19097            return;
19098        }
19099        synchronized (mPackages) {
19100            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19101                    ":");
19102            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19103            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19104                    new PersistentPreferredActivity(filter, activity));
19105            scheduleWritePackageRestrictionsLocked(userId);
19106            postPreferredActivityChangedBroadcast(userId);
19107        }
19108    }
19109
19110    @Override
19111    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19112        int callingUid = Binder.getCallingUid();
19113        if (callingUid != Process.SYSTEM_UID) {
19114            throw new SecurityException(
19115                    "clearPackagePersistentPreferredActivities can only be run by the system");
19116        }
19117        ArrayList<PersistentPreferredActivity> removed = null;
19118        boolean changed = false;
19119        synchronized (mPackages) {
19120            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19121                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19122                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19123                        .valueAt(i);
19124                if (userId != thisUserId) {
19125                    continue;
19126                }
19127                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19128                while (it.hasNext()) {
19129                    PersistentPreferredActivity ppa = it.next();
19130                    // Mark entry for removal only if it matches the package name.
19131                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19132                        if (removed == null) {
19133                            removed = new ArrayList<PersistentPreferredActivity>();
19134                        }
19135                        removed.add(ppa);
19136                    }
19137                }
19138                if (removed != null) {
19139                    for (int j=0; j<removed.size(); j++) {
19140                        PersistentPreferredActivity ppa = removed.get(j);
19141                        ppir.removeFilter(ppa);
19142                    }
19143                    changed = true;
19144                }
19145            }
19146
19147            if (changed) {
19148                scheduleWritePackageRestrictionsLocked(userId);
19149                postPreferredActivityChangedBroadcast(userId);
19150            }
19151        }
19152    }
19153
19154    /**
19155     * Common machinery for picking apart a restored XML blob and passing
19156     * it to a caller-supplied functor to be applied to the running system.
19157     */
19158    private void restoreFromXml(XmlPullParser parser, int userId,
19159            String expectedStartTag, BlobXmlRestorer functor)
19160            throws IOException, XmlPullParserException {
19161        int type;
19162        while ((type = parser.next()) != XmlPullParser.START_TAG
19163                && type != XmlPullParser.END_DOCUMENT) {
19164        }
19165        if (type != XmlPullParser.START_TAG) {
19166            // oops didn't find a start tag?!
19167            if (DEBUG_BACKUP) {
19168                Slog.e(TAG, "Didn't find start tag during restore");
19169            }
19170            return;
19171        }
19172Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19173        // this is supposed to be TAG_PREFERRED_BACKUP
19174        if (!expectedStartTag.equals(parser.getName())) {
19175            if (DEBUG_BACKUP) {
19176                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19177            }
19178            return;
19179        }
19180
19181        // skip interfering stuff, then we're aligned with the backing implementation
19182        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19183Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19184        functor.apply(parser, userId);
19185    }
19186
19187    private interface BlobXmlRestorer {
19188        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19189    }
19190
19191    /**
19192     * Non-Binder method, support for the backup/restore mechanism: write the
19193     * full set of preferred activities in its canonical XML format.  Returns the
19194     * XML output as a byte array, or null if there is none.
19195     */
19196    @Override
19197    public byte[] getPreferredActivityBackup(int userId) {
19198        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19199            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19200        }
19201
19202        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19203        try {
19204            final XmlSerializer serializer = new FastXmlSerializer();
19205            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19206            serializer.startDocument(null, true);
19207            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19208
19209            synchronized (mPackages) {
19210                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19211            }
19212
19213            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19214            serializer.endDocument();
19215            serializer.flush();
19216        } catch (Exception e) {
19217            if (DEBUG_BACKUP) {
19218                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19219            }
19220            return null;
19221        }
19222
19223        return dataStream.toByteArray();
19224    }
19225
19226    @Override
19227    public void restorePreferredActivities(byte[] backup, int userId) {
19228        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19229            throw new SecurityException("Only the system may call restorePreferredActivities()");
19230        }
19231
19232        try {
19233            final XmlPullParser parser = Xml.newPullParser();
19234            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19235            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19236                    new BlobXmlRestorer() {
19237                        @Override
19238                        public void apply(XmlPullParser parser, int userId)
19239                                throws XmlPullParserException, IOException {
19240                            synchronized (mPackages) {
19241                                mSettings.readPreferredActivitiesLPw(parser, userId);
19242                            }
19243                        }
19244                    } );
19245        } catch (Exception e) {
19246            if (DEBUG_BACKUP) {
19247                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19248            }
19249        }
19250    }
19251
19252    /**
19253     * Non-Binder method, support for the backup/restore mechanism: write the
19254     * default browser (etc) settings in its canonical XML format.  Returns the default
19255     * browser XML representation as a byte array, or null if there is none.
19256     */
19257    @Override
19258    public byte[] getDefaultAppsBackup(int userId) {
19259        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19260            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19261        }
19262
19263        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19264        try {
19265            final XmlSerializer serializer = new FastXmlSerializer();
19266            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19267            serializer.startDocument(null, true);
19268            serializer.startTag(null, TAG_DEFAULT_APPS);
19269
19270            synchronized (mPackages) {
19271                mSettings.writeDefaultAppsLPr(serializer, userId);
19272            }
19273
19274            serializer.endTag(null, TAG_DEFAULT_APPS);
19275            serializer.endDocument();
19276            serializer.flush();
19277        } catch (Exception e) {
19278            if (DEBUG_BACKUP) {
19279                Slog.e(TAG, "Unable to write default apps for backup", e);
19280            }
19281            return null;
19282        }
19283
19284        return dataStream.toByteArray();
19285    }
19286
19287    @Override
19288    public void restoreDefaultApps(byte[] backup, int userId) {
19289        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19290            throw new SecurityException("Only the system may call restoreDefaultApps()");
19291        }
19292
19293        try {
19294            final XmlPullParser parser = Xml.newPullParser();
19295            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19296            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19297                    new BlobXmlRestorer() {
19298                        @Override
19299                        public void apply(XmlPullParser parser, int userId)
19300                                throws XmlPullParserException, IOException {
19301                            synchronized (mPackages) {
19302                                mSettings.readDefaultAppsLPw(parser, userId);
19303                            }
19304                        }
19305                    } );
19306        } catch (Exception e) {
19307            if (DEBUG_BACKUP) {
19308                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19309            }
19310        }
19311    }
19312
19313    @Override
19314    public byte[] getIntentFilterVerificationBackup(int userId) {
19315        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19316            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19317        }
19318
19319        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19320        try {
19321            final XmlSerializer serializer = new FastXmlSerializer();
19322            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19323            serializer.startDocument(null, true);
19324            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19325
19326            synchronized (mPackages) {
19327                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19328            }
19329
19330            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19331            serializer.endDocument();
19332            serializer.flush();
19333        } catch (Exception e) {
19334            if (DEBUG_BACKUP) {
19335                Slog.e(TAG, "Unable to write default apps for backup", e);
19336            }
19337            return null;
19338        }
19339
19340        return dataStream.toByteArray();
19341    }
19342
19343    @Override
19344    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19345        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19346            throw new SecurityException("Only the system may call restorePreferredActivities()");
19347        }
19348
19349        try {
19350            final XmlPullParser parser = Xml.newPullParser();
19351            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19352            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19353                    new BlobXmlRestorer() {
19354                        @Override
19355                        public void apply(XmlPullParser parser, int userId)
19356                                throws XmlPullParserException, IOException {
19357                            synchronized (mPackages) {
19358                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19359                                mSettings.writeLPr();
19360                            }
19361                        }
19362                    } );
19363        } catch (Exception e) {
19364            if (DEBUG_BACKUP) {
19365                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19366            }
19367        }
19368    }
19369
19370    @Override
19371    public byte[] getPermissionGrantBackup(int userId) {
19372        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19373            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19374        }
19375
19376        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19377        try {
19378            final XmlSerializer serializer = new FastXmlSerializer();
19379            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19380            serializer.startDocument(null, true);
19381            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19382
19383            synchronized (mPackages) {
19384                serializeRuntimePermissionGrantsLPr(serializer, userId);
19385            }
19386
19387            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19388            serializer.endDocument();
19389            serializer.flush();
19390        } catch (Exception e) {
19391            if (DEBUG_BACKUP) {
19392                Slog.e(TAG, "Unable to write default apps for backup", e);
19393            }
19394            return null;
19395        }
19396
19397        return dataStream.toByteArray();
19398    }
19399
19400    @Override
19401    public void restorePermissionGrants(byte[] backup, int userId) {
19402        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19403            throw new SecurityException("Only the system may call restorePermissionGrants()");
19404        }
19405
19406        try {
19407            final XmlPullParser parser = Xml.newPullParser();
19408            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19409            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19410                    new BlobXmlRestorer() {
19411                        @Override
19412                        public void apply(XmlPullParser parser, int userId)
19413                                throws XmlPullParserException, IOException {
19414                            synchronized (mPackages) {
19415                                processRestoredPermissionGrantsLPr(parser, userId);
19416                            }
19417                        }
19418                    } );
19419        } catch (Exception e) {
19420            if (DEBUG_BACKUP) {
19421                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19422            }
19423        }
19424    }
19425
19426    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19427            throws IOException {
19428        serializer.startTag(null, TAG_ALL_GRANTS);
19429
19430        final int N = mSettings.mPackages.size();
19431        for (int i = 0; i < N; i++) {
19432            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19433            boolean pkgGrantsKnown = false;
19434
19435            PermissionsState packagePerms = ps.getPermissionsState();
19436
19437            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19438                final int grantFlags = state.getFlags();
19439                // only look at grants that are not system/policy fixed
19440                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19441                    final boolean isGranted = state.isGranted();
19442                    // And only back up the user-twiddled state bits
19443                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19444                        final String packageName = mSettings.mPackages.keyAt(i);
19445                        if (!pkgGrantsKnown) {
19446                            serializer.startTag(null, TAG_GRANT);
19447                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19448                            pkgGrantsKnown = true;
19449                        }
19450
19451                        final boolean userSet =
19452                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19453                        final boolean userFixed =
19454                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19455                        final boolean revoke =
19456                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19457
19458                        serializer.startTag(null, TAG_PERMISSION);
19459                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19460                        if (isGranted) {
19461                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19462                        }
19463                        if (userSet) {
19464                            serializer.attribute(null, ATTR_USER_SET, "true");
19465                        }
19466                        if (userFixed) {
19467                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19468                        }
19469                        if (revoke) {
19470                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19471                        }
19472                        serializer.endTag(null, TAG_PERMISSION);
19473                    }
19474                }
19475            }
19476
19477            if (pkgGrantsKnown) {
19478                serializer.endTag(null, TAG_GRANT);
19479            }
19480        }
19481
19482        serializer.endTag(null, TAG_ALL_GRANTS);
19483    }
19484
19485    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19486            throws XmlPullParserException, IOException {
19487        String pkgName = null;
19488        int outerDepth = parser.getDepth();
19489        int type;
19490        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19491                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19492            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19493                continue;
19494            }
19495
19496            final String tagName = parser.getName();
19497            if (tagName.equals(TAG_GRANT)) {
19498                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19499                if (DEBUG_BACKUP) {
19500                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19501                }
19502            } else if (tagName.equals(TAG_PERMISSION)) {
19503
19504                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19505                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19506
19507                int newFlagSet = 0;
19508                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19509                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19510                }
19511                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19512                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19513                }
19514                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19515                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19516                }
19517                if (DEBUG_BACKUP) {
19518                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19519                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19520                }
19521                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19522                if (ps != null) {
19523                    // Already installed so we apply the grant immediately
19524                    if (DEBUG_BACKUP) {
19525                        Slog.v(TAG, "        + already installed; applying");
19526                    }
19527                    PermissionsState perms = ps.getPermissionsState();
19528                    BasePermission bp = mSettings.mPermissions.get(permName);
19529                    if (bp != null) {
19530                        if (isGranted) {
19531                            perms.grantRuntimePermission(bp, userId);
19532                        }
19533                        if (newFlagSet != 0) {
19534                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19535                        }
19536                    }
19537                } else {
19538                    // Need to wait for post-restore install to apply the grant
19539                    if (DEBUG_BACKUP) {
19540                        Slog.v(TAG, "        - not yet installed; saving for later");
19541                    }
19542                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19543                            isGranted, newFlagSet, userId);
19544                }
19545            } else {
19546                PackageManagerService.reportSettingsProblem(Log.WARN,
19547                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19548                XmlUtils.skipCurrentTag(parser);
19549            }
19550        }
19551
19552        scheduleWriteSettingsLocked();
19553        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19554    }
19555
19556    @Override
19557    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19558            int sourceUserId, int targetUserId, int flags) {
19559        mContext.enforceCallingOrSelfPermission(
19560                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19561        int callingUid = Binder.getCallingUid();
19562        enforceOwnerRights(ownerPackage, callingUid);
19563        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19564        if (intentFilter.countActions() == 0) {
19565            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19566            return;
19567        }
19568        synchronized (mPackages) {
19569            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19570                    ownerPackage, targetUserId, flags);
19571            CrossProfileIntentResolver resolver =
19572                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19573            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19574            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19575            if (existing != null) {
19576                int size = existing.size();
19577                for (int i = 0; i < size; i++) {
19578                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19579                        return;
19580                    }
19581                }
19582            }
19583            resolver.addFilter(newFilter);
19584            scheduleWritePackageRestrictionsLocked(sourceUserId);
19585        }
19586    }
19587
19588    @Override
19589    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19590        mContext.enforceCallingOrSelfPermission(
19591                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19592        int callingUid = Binder.getCallingUid();
19593        enforceOwnerRights(ownerPackage, callingUid);
19594        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19595        synchronized (mPackages) {
19596            CrossProfileIntentResolver resolver =
19597                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19598            ArraySet<CrossProfileIntentFilter> set =
19599                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19600            for (CrossProfileIntentFilter filter : set) {
19601                if (filter.getOwnerPackage().equals(ownerPackage)) {
19602                    resolver.removeFilter(filter);
19603                }
19604            }
19605            scheduleWritePackageRestrictionsLocked(sourceUserId);
19606        }
19607    }
19608
19609    // Enforcing that callingUid is owning pkg on userId
19610    private void enforceOwnerRights(String pkg, int callingUid) {
19611        // The system owns everything.
19612        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19613            return;
19614        }
19615        int callingUserId = UserHandle.getUserId(callingUid);
19616        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19617        if (pi == null) {
19618            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19619                    + callingUserId);
19620        }
19621        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19622            throw new SecurityException("Calling uid " + callingUid
19623                    + " does not own package " + pkg);
19624        }
19625    }
19626
19627    @Override
19628    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19629        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19630    }
19631
19632    /**
19633     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19634     * then reports the most likely home activity or null if there are more than one.
19635     */
19636    public ComponentName getDefaultHomeActivity(int userId) {
19637        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19638        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19639        if (cn != null) {
19640            return cn;
19641        }
19642
19643        // Find the launcher with the highest priority and return that component if there are no
19644        // other home activity with the same priority.
19645        int lastPriority = Integer.MIN_VALUE;
19646        ComponentName lastComponent = null;
19647        final int size = allHomeCandidates.size();
19648        for (int i = 0; i < size; i++) {
19649            final ResolveInfo ri = allHomeCandidates.get(i);
19650            if (ri.priority > lastPriority) {
19651                lastComponent = ri.activityInfo.getComponentName();
19652                lastPriority = ri.priority;
19653            } else if (ri.priority == lastPriority) {
19654                // Two components found with same priority.
19655                lastComponent = null;
19656            }
19657        }
19658        return lastComponent;
19659    }
19660
19661    private Intent getHomeIntent() {
19662        Intent intent = new Intent(Intent.ACTION_MAIN);
19663        intent.addCategory(Intent.CATEGORY_HOME);
19664        intent.addCategory(Intent.CATEGORY_DEFAULT);
19665        return intent;
19666    }
19667
19668    private IntentFilter getHomeFilter() {
19669        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19670        filter.addCategory(Intent.CATEGORY_HOME);
19671        filter.addCategory(Intent.CATEGORY_DEFAULT);
19672        return filter;
19673    }
19674
19675    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19676            int userId) {
19677        Intent intent  = getHomeIntent();
19678        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19679                PackageManager.GET_META_DATA, userId);
19680        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19681                true, false, false, userId);
19682
19683        allHomeCandidates.clear();
19684        if (list != null) {
19685            for (ResolveInfo ri : list) {
19686                allHomeCandidates.add(ri);
19687            }
19688        }
19689        return (preferred == null || preferred.activityInfo == null)
19690                ? null
19691                : new ComponentName(preferred.activityInfo.packageName,
19692                        preferred.activityInfo.name);
19693    }
19694
19695    @Override
19696    public void setHomeActivity(ComponentName comp, int userId) {
19697        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19698        getHomeActivitiesAsUser(homeActivities, userId);
19699
19700        boolean found = false;
19701
19702        final int size = homeActivities.size();
19703        final ComponentName[] set = new ComponentName[size];
19704        for (int i = 0; i < size; i++) {
19705            final ResolveInfo candidate = homeActivities.get(i);
19706            final ActivityInfo info = candidate.activityInfo;
19707            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19708            set[i] = activityName;
19709            if (!found && activityName.equals(comp)) {
19710                found = true;
19711            }
19712        }
19713        if (!found) {
19714            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19715                    + userId);
19716        }
19717        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19718                set, comp, userId);
19719    }
19720
19721    private @Nullable String getSetupWizardPackageName() {
19722        final Intent intent = new Intent(Intent.ACTION_MAIN);
19723        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19724
19725        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19726                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19727                        | MATCH_DISABLED_COMPONENTS,
19728                UserHandle.myUserId());
19729        if (matches.size() == 1) {
19730            return matches.get(0).getComponentInfo().packageName;
19731        } else {
19732            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19733                    + ": matches=" + matches);
19734            return null;
19735        }
19736    }
19737
19738    private @Nullable String getStorageManagerPackageName() {
19739        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19740
19741        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19742                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19743                        | MATCH_DISABLED_COMPONENTS,
19744                UserHandle.myUserId());
19745        if (matches.size() == 1) {
19746            return matches.get(0).getComponentInfo().packageName;
19747        } else {
19748            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19749                    + matches.size() + ": matches=" + matches);
19750            return null;
19751        }
19752    }
19753
19754    @Override
19755    public void setApplicationEnabledSetting(String appPackageName,
19756            int newState, int flags, int userId, String callingPackage) {
19757        if (!sUserManager.exists(userId)) return;
19758        if (callingPackage == null) {
19759            callingPackage = Integer.toString(Binder.getCallingUid());
19760        }
19761        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19762    }
19763
19764    @Override
19765    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19766        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19767        synchronized (mPackages) {
19768            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19769            if (pkgSetting != null) {
19770                pkgSetting.setUpdateAvailable(updateAvailable);
19771            }
19772        }
19773    }
19774
19775    @Override
19776    public void setComponentEnabledSetting(ComponentName componentName,
19777            int newState, int flags, int userId) {
19778        if (!sUserManager.exists(userId)) return;
19779        setEnabledSetting(componentName.getPackageName(),
19780                componentName.getClassName(), newState, flags, userId, null);
19781    }
19782
19783    private void setEnabledSetting(final String packageName, String className, int newState,
19784            final int flags, int userId, String callingPackage) {
19785        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19786              || newState == COMPONENT_ENABLED_STATE_ENABLED
19787              || newState == COMPONENT_ENABLED_STATE_DISABLED
19788              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19789              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19790            throw new IllegalArgumentException("Invalid new component state: "
19791                    + newState);
19792        }
19793        PackageSetting pkgSetting;
19794        final int uid = Binder.getCallingUid();
19795        final int permission;
19796        if (uid == Process.SYSTEM_UID) {
19797            permission = PackageManager.PERMISSION_GRANTED;
19798        } else {
19799            permission = mContext.checkCallingOrSelfPermission(
19800                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19801        }
19802        enforceCrossUserPermission(uid, userId,
19803                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19804        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19805        boolean sendNow = false;
19806        boolean isApp = (className == null);
19807        String componentName = isApp ? packageName : className;
19808        int packageUid = -1;
19809        ArrayList<String> components;
19810
19811        // writer
19812        synchronized (mPackages) {
19813            pkgSetting = mSettings.mPackages.get(packageName);
19814            if (pkgSetting == null) {
19815                if (className == null) {
19816                    throw new IllegalArgumentException("Unknown package: " + packageName);
19817                }
19818                throw new IllegalArgumentException(
19819                        "Unknown component: " + packageName + "/" + className);
19820            }
19821        }
19822
19823        // Limit who can change which apps
19824        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19825            // Don't allow apps that don't have permission to modify other apps
19826            if (!allowedByPermission) {
19827                throw new SecurityException(
19828                        "Permission Denial: attempt to change component state from pid="
19829                        + Binder.getCallingPid()
19830                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19831            }
19832            // Don't allow changing protected packages.
19833            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19834                throw new SecurityException("Cannot disable a protected package: " + packageName);
19835            }
19836        }
19837
19838        synchronized (mPackages) {
19839            if (uid == Process.SHELL_UID
19840                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19841                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19842                // unless it is a test package.
19843                int oldState = pkgSetting.getEnabled(userId);
19844                if (className == null
19845                    &&
19846                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19847                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19848                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19849                    &&
19850                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19851                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19852                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19853                    // ok
19854                } else {
19855                    throw new SecurityException(
19856                            "Shell cannot change component state for " + packageName + "/"
19857                            + className + " to " + newState);
19858                }
19859            }
19860            if (className == null) {
19861                // We're dealing with an application/package level state change
19862                if (pkgSetting.getEnabled(userId) == newState) {
19863                    // Nothing to do
19864                    return;
19865                }
19866                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19867                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19868                    // Don't care about who enables an app.
19869                    callingPackage = null;
19870                }
19871                pkgSetting.setEnabled(newState, userId, callingPackage);
19872                // pkgSetting.pkg.mSetEnabled = newState;
19873            } else {
19874                // We're dealing with a component level state change
19875                // First, verify that this is a valid class name.
19876                PackageParser.Package pkg = pkgSetting.pkg;
19877                if (pkg == null || !pkg.hasComponentClassName(className)) {
19878                    if (pkg != null &&
19879                            pkg.applicationInfo.targetSdkVersion >=
19880                                    Build.VERSION_CODES.JELLY_BEAN) {
19881                        throw new IllegalArgumentException("Component class " + className
19882                                + " does not exist in " + packageName);
19883                    } else {
19884                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19885                                + className + " does not exist in " + packageName);
19886                    }
19887                }
19888                switch (newState) {
19889                case COMPONENT_ENABLED_STATE_ENABLED:
19890                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19891                        return;
19892                    }
19893                    break;
19894                case COMPONENT_ENABLED_STATE_DISABLED:
19895                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19896                        return;
19897                    }
19898                    break;
19899                case COMPONENT_ENABLED_STATE_DEFAULT:
19900                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19901                        return;
19902                    }
19903                    break;
19904                default:
19905                    Slog.e(TAG, "Invalid new component state: " + newState);
19906                    return;
19907                }
19908            }
19909            scheduleWritePackageRestrictionsLocked(userId);
19910            updateSequenceNumberLP(packageName, new int[] { userId });
19911            final long callingId = Binder.clearCallingIdentity();
19912            try {
19913                updateInstantAppInstallerLocked();
19914            } finally {
19915                Binder.restoreCallingIdentity(callingId);
19916            }
19917            components = mPendingBroadcasts.get(userId, packageName);
19918            final boolean newPackage = components == null;
19919            if (newPackage) {
19920                components = new ArrayList<String>();
19921            }
19922            if (!components.contains(componentName)) {
19923                components.add(componentName);
19924            }
19925            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19926                sendNow = true;
19927                // Purge entry from pending broadcast list if another one exists already
19928                // since we are sending one right away.
19929                mPendingBroadcasts.remove(userId, packageName);
19930            } else {
19931                if (newPackage) {
19932                    mPendingBroadcasts.put(userId, packageName, components);
19933                }
19934                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19935                    // Schedule a message
19936                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19937                }
19938            }
19939        }
19940
19941        long callingId = Binder.clearCallingIdentity();
19942        try {
19943            if (sendNow) {
19944                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19945                sendPackageChangedBroadcast(packageName,
19946                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19947            }
19948        } finally {
19949            Binder.restoreCallingIdentity(callingId);
19950        }
19951    }
19952
19953    @Override
19954    public void flushPackageRestrictionsAsUser(int userId) {
19955        if (!sUserManager.exists(userId)) {
19956            return;
19957        }
19958        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19959                false /* checkShell */, "flushPackageRestrictions");
19960        synchronized (mPackages) {
19961            mSettings.writePackageRestrictionsLPr(userId);
19962            mDirtyUsers.remove(userId);
19963            if (mDirtyUsers.isEmpty()) {
19964                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19965            }
19966        }
19967    }
19968
19969    private void sendPackageChangedBroadcast(String packageName,
19970            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19971        if (DEBUG_INSTALL)
19972            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19973                    + componentNames);
19974        Bundle extras = new Bundle(4);
19975        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19976        String nameList[] = new String[componentNames.size()];
19977        componentNames.toArray(nameList);
19978        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19979        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19980        extras.putInt(Intent.EXTRA_UID, packageUid);
19981        // If this is not reporting a change of the overall package, then only send it
19982        // to registered receivers.  We don't want to launch a swath of apps for every
19983        // little component state change.
19984        final int flags = !componentNames.contains(packageName)
19985                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19986        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19987                new int[] {UserHandle.getUserId(packageUid)});
19988    }
19989
19990    @Override
19991    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19992        if (!sUserManager.exists(userId)) return;
19993        final int uid = Binder.getCallingUid();
19994        final int permission = mContext.checkCallingOrSelfPermission(
19995                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19996        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19997        enforceCrossUserPermission(uid, userId,
19998                true /* requireFullPermission */, true /* checkShell */, "stop package");
19999        // writer
20000        synchronized (mPackages) {
20001            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20002                    allowedByPermission, uid, userId)) {
20003                scheduleWritePackageRestrictionsLocked(userId);
20004            }
20005        }
20006    }
20007
20008    @Override
20009    public String getInstallerPackageName(String packageName) {
20010        // reader
20011        synchronized (mPackages) {
20012            return mSettings.getInstallerPackageNameLPr(packageName);
20013        }
20014    }
20015
20016    public boolean isOrphaned(String packageName) {
20017        // reader
20018        synchronized (mPackages) {
20019            return mSettings.isOrphaned(packageName);
20020        }
20021    }
20022
20023    @Override
20024    public int getApplicationEnabledSetting(String packageName, int userId) {
20025        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20026        int uid = Binder.getCallingUid();
20027        enforceCrossUserPermission(uid, userId,
20028                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20029        // reader
20030        synchronized (mPackages) {
20031            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20032        }
20033    }
20034
20035    @Override
20036    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20037        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20038        int uid = Binder.getCallingUid();
20039        enforceCrossUserPermission(uid, userId,
20040                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20041        // reader
20042        synchronized (mPackages) {
20043            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20044        }
20045    }
20046
20047    @Override
20048    public void enterSafeMode() {
20049        enforceSystemOrRoot("Only the system can request entering safe mode");
20050
20051        if (!mSystemReady) {
20052            mSafeMode = true;
20053        }
20054    }
20055
20056    @Override
20057    public void systemReady() {
20058        mSystemReady = true;
20059
20060        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20061        // disabled after already being started.
20062        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20063                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20064
20065        // Read the compatibilty setting when the system is ready.
20066        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20067                mContext.getContentResolver(),
20068                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20069        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20070        if (DEBUG_SETTINGS) {
20071            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20072        }
20073
20074        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20075
20076        synchronized (mPackages) {
20077            // Verify that all of the preferred activity components actually
20078            // exist.  It is possible for applications to be updated and at
20079            // that point remove a previously declared activity component that
20080            // had been set as a preferred activity.  We try to clean this up
20081            // the next time we encounter that preferred activity, but it is
20082            // possible for the user flow to never be able to return to that
20083            // situation so here we do a sanity check to make sure we haven't
20084            // left any junk around.
20085            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20086            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20087                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20088                removed.clear();
20089                for (PreferredActivity pa : pir.filterSet()) {
20090                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20091                        removed.add(pa);
20092                    }
20093                }
20094                if (removed.size() > 0) {
20095                    for (int r=0; r<removed.size(); r++) {
20096                        PreferredActivity pa = removed.get(r);
20097                        Slog.w(TAG, "Removing dangling preferred activity: "
20098                                + pa.mPref.mComponent);
20099                        pir.removeFilter(pa);
20100                    }
20101                    mSettings.writePackageRestrictionsLPr(
20102                            mSettings.mPreferredActivities.keyAt(i));
20103                }
20104            }
20105
20106            for (int userId : UserManagerService.getInstance().getUserIds()) {
20107                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20108                    grantPermissionsUserIds = ArrayUtils.appendInt(
20109                            grantPermissionsUserIds, userId);
20110                }
20111            }
20112        }
20113        sUserManager.systemReady();
20114
20115        // If we upgraded grant all default permissions before kicking off.
20116        for (int userId : grantPermissionsUserIds) {
20117            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20118        }
20119
20120        // If we did not grant default permissions, we preload from this the
20121        // default permission exceptions lazily to ensure we don't hit the
20122        // disk on a new user creation.
20123        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20124            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20125        }
20126
20127        // Kick off any messages waiting for system ready
20128        if (mPostSystemReadyMessages != null) {
20129            for (Message msg : mPostSystemReadyMessages) {
20130                msg.sendToTarget();
20131            }
20132            mPostSystemReadyMessages = null;
20133        }
20134
20135        // Watch for external volumes that come and go over time
20136        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20137        storage.registerListener(mStorageListener);
20138
20139        mInstallerService.systemReady();
20140        mPackageDexOptimizer.systemReady();
20141
20142        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20143                StorageManagerInternal.class);
20144        StorageManagerInternal.addExternalStoragePolicy(
20145                new StorageManagerInternal.ExternalStorageMountPolicy() {
20146            @Override
20147            public int getMountMode(int uid, String packageName) {
20148                if (Process.isIsolated(uid)) {
20149                    return Zygote.MOUNT_EXTERNAL_NONE;
20150                }
20151                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20152                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20153                }
20154                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20155                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20156                }
20157                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20158                    return Zygote.MOUNT_EXTERNAL_READ;
20159                }
20160                return Zygote.MOUNT_EXTERNAL_WRITE;
20161            }
20162
20163            @Override
20164            public boolean hasExternalStorage(int uid, String packageName) {
20165                return true;
20166            }
20167        });
20168
20169        // Now that we're mostly running, clean up stale users and apps
20170        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20171        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20172
20173        if (mPrivappPermissionsViolations != null) {
20174            Slog.wtf(TAG,"Signature|privileged permissions not in "
20175                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20176            mPrivappPermissionsViolations = null;
20177        }
20178    }
20179
20180    public void waitForAppDataPrepared() {
20181        if (mPrepareAppDataFuture == null) {
20182            return;
20183        }
20184        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20185        mPrepareAppDataFuture = null;
20186    }
20187
20188    @Override
20189    public boolean isSafeMode() {
20190        return mSafeMode;
20191    }
20192
20193    @Override
20194    public boolean hasSystemUidErrors() {
20195        return mHasSystemUidErrors;
20196    }
20197
20198    static String arrayToString(int[] array) {
20199        StringBuffer buf = new StringBuffer(128);
20200        buf.append('[');
20201        if (array != null) {
20202            for (int i=0; i<array.length; i++) {
20203                if (i > 0) buf.append(", ");
20204                buf.append(array[i]);
20205            }
20206        }
20207        buf.append(']');
20208        return buf.toString();
20209    }
20210
20211    static class DumpState {
20212        public static final int DUMP_LIBS = 1 << 0;
20213        public static final int DUMP_FEATURES = 1 << 1;
20214        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20215        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20216        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20217        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20218        public static final int DUMP_PERMISSIONS = 1 << 6;
20219        public static final int DUMP_PACKAGES = 1 << 7;
20220        public static final int DUMP_SHARED_USERS = 1 << 8;
20221        public static final int DUMP_MESSAGES = 1 << 9;
20222        public static final int DUMP_PROVIDERS = 1 << 10;
20223        public static final int DUMP_VERIFIERS = 1 << 11;
20224        public static final int DUMP_PREFERRED = 1 << 12;
20225        public static final int DUMP_PREFERRED_XML = 1 << 13;
20226        public static final int DUMP_KEYSETS = 1 << 14;
20227        public static final int DUMP_VERSION = 1 << 15;
20228        public static final int DUMP_INSTALLS = 1 << 16;
20229        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20230        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20231        public static final int DUMP_FROZEN = 1 << 19;
20232        public static final int DUMP_DEXOPT = 1 << 20;
20233        public static final int DUMP_COMPILER_STATS = 1 << 21;
20234        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20235
20236        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20237
20238        private int mTypes;
20239
20240        private int mOptions;
20241
20242        private boolean mTitlePrinted;
20243
20244        private SharedUserSetting mSharedUser;
20245
20246        public boolean isDumping(int type) {
20247            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20248                return true;
20249            }
20250
20251            return (mTypes & type) != 0;
20252        }
20253
20254        public void setDump(int type) {
20255            mTypes |= type;
20256        }
20257
20258        public boolean isOptionEnabled(int option) {
20259            return (mOptions & option) != 0;
20260        }
20261
20262        public void setOptionEnabled(int option) {
20263            mOptions |= option;
20264        }
20265
20266        public boolean onTitlePrinted() {
20267            final boolean printed = mTitlePrinted;
20268            mTitlePrinted = true;
20269            return printed;
20270        }
20271
20272        public boolean getTitlePrinted() {
20273            return mTitlePrinted;
20274        }
20275
20276        public void setTitlePrinted(boolean enabled) {
20277            mTitlePrinted = enabled;
20278        }
20279
20280        public SharedUserSetting getSharedUser() {
20281            return mSharedUser;
20282        }
20283
20284        public void setSharedUser(SharedUserSetting user) {
20285            mSharedUser = user;
20286        }
20287    }
20288
20289    @Override
20290    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20291            FileDescriptor err, String[] args, ShellCallback callback,
20292            ResultReceiver resultReceiver) {
20293        (new PackageManagerShellCommand(this)).exec(
20294                this, in, out, err, args, callback, resultReceiver);
20295    }
20296
20297    @Override
20298    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20299        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20300                != PackageManager.PERMISSION_GRANTED) {
20301            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20302                    + Binder.getCallingPid()
20303                    + ", uid=" + Binder.getCallingUid()
20304                    + " without permission "
20305                    + android.Manifest.permission.DUMP);
20306            return;
20307        }
20308
20309        DumpState dumpState = new DumpState();
20310        boolean fullPreferred = false;
20311        boolean checkin = false;
20312
20313        String packageName = null;
20314        ArraySet<String> permissionNames = null;
20315
20316        int opti = 0;
20317        while (opti < args.length) {
20318            String opt = args[opti];
20319            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20320                break;
20321            }
20322            opti++;
20323
20324            if ("-a".equals(opt)) {
20325                // Right now we only know how to print all.
20326            } else if ("-h".equals(opt)) {
20327                pw.println("Package manager dump options:");
20328                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20329                pw.println("    --checkin: dump for a checkin");
20330                pw.println("    -f: print details of intent filters");
20331                pw.println("    -h: print this help");
20332                pw.println("  cmd may be one of:");
20333                pw.println("    l[ibraries]: list known shared libraries");
20334                pw.println("    f[eatures]: list device features");
20335                pw.println("    k[eysets]: print known keysets");
20336                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20337                pw.println("    perm[issions]: dump permissions");
20338                pw.println("    permission [name ...]: dump declaration and use of given permission");
20339                pw.println("    pref[erred]: print preferred package settings");
20340                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20341                pw.println("    prov[iders]: dump content providers");
20342                pw.println("    p[ackages]: dump installed packages");
20343                pw.println("    s[hared-users]: dump shared user IDs");
20344                pw.println("    m[essages]: print collected runtime messages");
20345                pw.println("    v[erifiers]: print package verifier info");
20346                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20347                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20348                pw.println("    version: print database version info");
20349                pw.println("    write: write current settings now");
20350                pw.println("    installs: details about install sessions");
20351                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20352                pw.println("    dexopt: dump dexopt state");
20353                pw.println("    compiler-stats: dump compiler statistics");
20354                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20355                pw.println("    <package.name>: info about given package");
20356                return;
20357            } else if ("--checkin".equals(opt)) {
20358                checkin = true;
20359            } else if ("-f".equals(opt)) {
20360                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20361            } else if ("--proto".equals(opt)) {
20362                dumpProto(fd);
20363                return;
20364            } else {
20365                pw.println("Unknown argument: " + opt + "; use -h for help");
20366            }
20367        }
20368
20369        // Is the caller requesting to dump a particular piece of data?
20370        if (opti < args.length) {
20371            String cmd = args[opti];
20372            opti++;
20373            // Is this a package name?
20374            if ("android".equals(cmd) || cmd.contains(".")) {
20375                packageName = cmd;
20376                // When dumping a single package, we always dump all of its
20377                // filter information since the amount of data will be reasonable.
20378                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20379            } else if ("check-permission".equals(cmd)) {
20380                if (opti >= args.length) {
20381                    pw.println("Error: check-permission missing permission argument");
20382                    return;
20383                }
20384                String perm = args[opti];
20385                opti++;
20386                if (opti >= args.length) {
20387                    pw.println("Error: check-permission missing package argument");
20388                    return;
20389                }
20390
20391                String pkg = args[opti];
20392                opti++;
20393                int user = UserHandle.getUserId(Binder.getCallingUid());
20394                if (opti < args.length) {
20395                    try {
20396                        user = Integer.parseInt(args[opti]);
20397                    } catch (NumberFormatException e) {
20398                        pw.println("Error: check-permission user argument is not a number: "
20399                                + args[opti]);
20400                        return;
20401                    }
20402                }
20403
20404                // Normalize package name to handle renamed packages and static libs
20405                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20406
20407                pw.println(checkPermission(perm, pkg, user));
20408                return;
20409            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20410                dumpState.setDump(DumpState.DUMP_LIBS);
20411            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20412                dumpState.setDump(DumpState.DUMP_FEATURES);
20413            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20414                if (opti >= args.length) {
20415                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20416                            | DumpState.DUMP_SERVICE_RESOLVERS
20417                            | DumpState.DUMP_RECEIVER_RESOLVERS
20418                            | DumpState.DUMP_CONTENT_RESOLVERS);
20419                } else {
20420                    while (opti < args.length) {
20421                        String name = args[opti];
20422                        if ("a".equals(name) || "activity".equals(name)) {
20423                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20424                        } else if ("s".equals(name) || "service".equals(name)) {
20425                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20426                        } else if ("r".equals(name) || "receiver".equals(name)) {
20427                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20428                        } else if ("c".equals(name) || "content".equals(name)) {
20429                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20430                        } else {
20431                            pw.println("Error: unknown resolver table type: " + name);
20432                            return;
20433                        }
20434                        opti++;
20435                    }
20436                }
20437            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20438                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20439            } else if ("permission".equals(cmd)) {
20440                if (opti >= args.length) {
20441                    pw.println("Error: permission requires permission name");
20442                    return;
20443                }
20444                permissionNames = new ArraySet<>();
20445                while (opti < args.length) {
20446                    permissionNames.add(args[opti]);
20447                    opti++;
20448                }
20449                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20450                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20451            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20452                dumpState.setDump(DumpState.DUMP_PREFERRED);
20453            } else if ("preferred-xml".equals(cmd)) {
20454                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20455                if (opti < args.length && "--full".equals(args[opti])) {
20456                    fullPreferred = true;
20457                    opti++;
20458                }
20459            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20460                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20461            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20462                dumpState.setDump(DumpState.DUMP_PACKAGES);
20463            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20464                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20465            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20466                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20467            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20468                dumpState.setDump(DumpState.DUMP_MESSAGES);
20469            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20470                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20471            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20472                    || "intent-filter-verifiers".equals(cmd)) {
20473                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20474            } else if ("version".equals(cmd)) {
20475                dumpState.setDump(DumpState.DUMP_VERSION);
20476            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20477                dumpState.setDump(DumpState.DUMP_KEYSETS);
20478            } else if ("installs".equals(cmd)) {
20479                dumpState.setDump(DumpState.DUMP_INSTALLS);
20480            } else if ("frozen".equals(cmd)) {
20481                dumpState.setDump(DumpState.DUMP_FROZEN);
20482            } else if ("dexopt".equals(cmd)) {
20483                dumpState.setDump(DumpState.DUMP_DEXOPT);
20484            } else if ("compiler-stats".equals(cmd)) {
20485                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20486            } else if ("enabled-overlays".equals(cmd)) {
20487                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20488            } else if ("write".equals(cmd)) {
20489                synchronized (mPackages) {
20490                    mSettings.writeLPr();
20491                    pw.println("Settings written.");
20492                    return;
20493                }
20494            }
20495        }
20496
20497        if (checkin) {
20498            pw.println("vers,1");
20499        }
20500
20501        // reader
20502        synchronized (mPackages) {
20503            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20504                if (!checkin) {
20505                    if (dumpState.onTitlePrinted())
20506                        pw.println();
20507                    pw.println("Database versions:");
20508                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20509                }
20510            }
20511
20512            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20513                if (!checkin) {
20514                    if (dumpState.onTitlePrinted())
20515                        pw.println();
20516                    pw.println("Verifiers:");
20517                    pw.print("  Required: ");
20518                    pw.print(mRequiredVerifierPackage);
20519                    pw.print(" (uid=");
20520                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20521                            UserHandle.USER_SYSTEM));
20522                    pw.println(")");
20523                } else if (mRequiredVerifierPackage != null) {
20524                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20525                    pw.print(",");
20526                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20527                            UserHandle.USER_SYSTEM));
20528                }
20529            }
20530
20531            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20532                    packageName == null) {
20533                if (mIntentFilterVerifierComponent != null) {
20534                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20535                    if (!checkin) {
20536                        if (dumpState.onTitlePrinted())
20537                            pw.println();
20538                        pw.println("Intent Filter Verifier:");
20539                        pw.print("  Using: ");
20540                        pw.print(verifierPackageName);
20541                        pw.print(" (uid=");
20542                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20543                                UserHandle.USER_SYSTEM));
20544                        pw.println(")");
20545                    } else if (verifierPackageName != null) {
20546                        pw.print("ifv,"); pw.print(verifierPackageName);
20547                        pw.print(",");
20548                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20549                                UserHandle.USER_SYSTEM));
20550                    }
20551                } else {
20552                    pw.println();
20553                    pw.println("No Intent Filter Verifier available!");
20554                }
20555            }
20556
20557            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20558                boolean printedHeader = false;
20559                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20560                while (it.hasNext()) {
20561                    String libName = it.next();
20562                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20563                    if (versionedLib == null) {
20564                        continue;
20565                    }
20566                    final int versionCount = versionedLib.size();
20567                    for (int i = 0; i < versionCount; i++) {
20568                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20569                        if (!checkin) {
20570                            if (!printedHeader) {
20571                                if (dumpState.onTitlePrinted())
20572                                    pw.println();
20573                                pw.println("Libraries:");
20574                                printedHeader = true;
20575                            }
20576                            pw.print("  ");
20577                        } else {
20578                            pw.print("lib,");
20579                        }
20580                        pw.print(libEntry.info.getName());
20581                        if (libEntry.info.isStatic()) {
20582                            pw.print(" version=" + libEntry.info.getVersion());
20583                        }
20584                        if (!checkin) {
20585                            pw.print(" -> ");
20586                        }
20587                        if (libEntry.path != null) {
20588                            pw.print(" (jar) ");
20589                            pw.print(libEntry.path);
20590                        } else {
20591                            pw.print(" (apk) ");
20592                            pw.print(libEntry.apk);
20593                        }
20594                        pw.println();
20595                    }
20596                }
20597            }
20598
20599            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20600                if (dumpState.onTitlePrinted())
20601                    pw.println();
20602                if (!checkin) {
20603                    pw.println("Features:");
20604                }
20605
20606                synchronized (mAvailableFeatures) {
20607                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20608                        if (checkin) {
20609                            pw.print("feat,");
20610                            pw.print(feat.name);
20611                            pw.print(",");
20612                            pw.println(feat.version);
20613                        } else {
20614                            pw.print("  ");
20615                            pw.print(feat.name);
20616                            if (feat.version > 0) {
20617                                pw.print(" version=");
20618                                pw.print(feat.version);
20619                            }
20620                            pw.println();
20621                        }
20622                    }
20623                }
20624            }
20625
20626            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20627                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20628                        : "Activity Resolver Table:", "  ", packageName,
20629                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20630                    dumpState.setTitlePrinted(true);
20631                }
20632            }
20633            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20634                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20635                        : "Receiver Resolver Table:", "  ", packageName,
20636                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20637                    dumpState.setTitlePrinted(true);
20638                }
20639            }
20640            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20641                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20642                        : "Service Resolver Table:", "  ", packageName,
20643                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20644                    dumpState.setTitlePrinted(true);
20645                }
20646            }
20647            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20648                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20649                        : "Provider Resolver Table:", "  ", packageName,
20650                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20651                    dumpState.setTitlePrinted(true);
20652                }
20653            }
20654
20655            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20656                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20657                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20658                    int user = mSettings.mPreferredActivities.keyAt(i);
20659                    if (pir.dump(pw,
20660                            dumpState.getTitlePrinted()
20661                                ? "\nPreferred Activities User " + user + ":"
20662                                : "Preferred Activities User " + user + ":", "  ",
20663                            packageName, true, false)) {
20664                        dumpState.setTitlePrinted(true);
20665                    }
20666                }
20667            }
20668
20669            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20670                pw.flush();
20671                FileOutputStream fout = new FileOutputStream(fd);
20672                BufferedOutputStream str = new BufferedOutputStream(fout);
20673                XmlSerializer serializer = new FastXmlSerializer();
20674                try {
20675                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20676                    serializer.startDocument(null, true);
20677                    serializer.setFeature(
20678                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20679                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20680                    serializer.endDocument();
20681                    serializer.flush();
20682                } catch (IllegalArgumentException e) {
20683                    pw.println("Failed writing: " + e);
20684                } catch (IllegalStateException e) {
20685                    pw.println("Failed writing: " + e);
20686                } catch (IOException e) {
20687                    pw.println("Failed writing: " + e);
20688                }
20689            }
20690
20691            if (!checkin
20692                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20693                    && packageName == null) {
20694                pw.println();
20695                int count = mSettings.mPackages.size();
20696                if (count == 0) {
20697                    pw.println("No applications!");
20698                    pw.println();
20699                } else {
20700                    final String prefix = "  ";
20701                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20702                    if (allPackageSettings.size() == 0) {
20703                        pw.println("No domain preferred apps!");
20704                        pw.println();
20705                    } else {
20706                        pw.println("App verification status:");
20707                        pw.println();
20708                        count = 0;
20709                        for (PackageSetting ps : allPackageSettings) {
20710                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20711                            if (ivi == null || ivi.getPackageName() == null) continue;
20712                            pw.println(prefix + "Package: " + ivi.getPackageName());
20713                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20714                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20715                            pw.println();
20716                            count++;
20717                        }
20718                        if (count == 0) {
20719                            pw.println(prefix + "No app verification established.");
20720                            pw.println();
20721                        }
20722                        for (int userId : sUserManager.getUserIds()) {
20723                            pw.println("App linkages for user " + userId + ":");
20724                            pw.println();
20725                            count = 0;
20726                            for (PackageSetting ps : allPackageSettings) {
20727                                final long status = ps.getDomainVerificationStatusForUser(userId);
20728                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20729                                        && !DEBUG_DOMAIN_VERIFICATION) {
20730                                    continue;
20731                                }
20732                                pw.println(prefix + "Package: " + ps.name);
20733                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20734                                String statusStr = IntentFilterVerificationInfo.
20735                                        getStatusStringFromValue(status);
20736                                pw.println(prefix + "Status:  " + statusStr);
20737                                pw.println();
20738                                count++;
20739                            }
20740                            if (count == 0) {
20741                                pw.println(prefix + "No configured app linkages.");
20742                                pw.println();
20743                            }
20744                        }
20745                    }
20746                }
20747            }
20748
20749            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20750                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20751                if (packageName == null && permissionNames == null) {
20752                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20753                        if (iperm == 0) {
20754                            if (dumpState.onTitlePrinted())
20755                                pw.println();
20756                            pw.println("AppOp Permissions:");
20757                        }
20758                        pw.print("  AppOp Permission ");
20759                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20760                        pw.println(":");
20761                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20762                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20763                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20764                        }
20765                    }
20766                }
20767            }
20768
20769            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20770                boolean printedSomething = false;
20771                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20772                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20773                        continue;
20774                    }
20775                    if (!printedSomething) {
20776                        if (dumpState.onTitlePrinted())
20777                            pw.println();
20778                        pw.println("Registered ContentProviders:");
20779                        printedSomething = true;
20780                    }
20781                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20782                    pw.print("    "); pw.println(p.toString());
20783                }
20784                printedSomething = false;
20785                for (Map.Entry<String, PackageParser.Provider> entry :
20786                        mProvidersByAuthority.entrySet()) {
20787                    PackageParser.Provider p = entry.getValue();
20788                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20789                        continue;
20790                    }
20791                    if (!printedSomething) {
20792                        if (dumpState.onTitlePrinted())
20793                            pw.println();
20794                        pw.println("ContentProvider Authorities:");
20795                        printedSomething = true;
20796                    }
20797                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20798                    pw.print("    "); pw.println(p.toString());
20799                    if (p.info != null && p.info.applicationInfo != null) {
20800                        final String appInfo = p.info.applicationInfo.toString();
20801                        pw.print("      applicationInfo="); pw.println(appInfo);
20802                    }
20803                }
20804            }
20805
20806            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20807                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20808            }
20809
20810            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20811                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20812            }
20813
20814            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20815                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20816            }
20817
20818            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20819                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20820            }
20821
20822            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20823                // XXX should handle packageName != null by dumping only install data that
20824                // the given package is involved with.
20825                if (dumpState.onTitlePrinted()) pw.println();
20826                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20827            }
20828
20829            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20830                // XXX should handle packageName != null by dumping only install data that
20831                // the given package is involved with.
20832                if (dumpState.onTitlePrinted()) pw.println();
20833
20834                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20835                ipw.println();
20836                ipw.println("Frozen packages:");
20837                ipw.increaseIndent();
20838                if (mFrozenPackages.size() == 0) {
20839                    ipw.println("(none)");
20840                } else {
20841                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20842                        ipw.println(mFrozenPackages.valueAt(i));
20843                    }
20844                }
20845                ipw.decreaseIndent();
20846            }
20847
20848            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20849                if (dumpState.onTitlePrinted()) pw.println();
20850                dumpDexoptStateLPr(pw, packageName);
20851            }
20852
20853            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20854                if (dumpState.onTitlePrinted()) pw.println();
20855                dumpCompilerStatsLPr(pw, packageName);
20856            }
20857
20858            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20859                if (dumpState.onTitlePrinted()) pw.println();
20860                dumpEnabledOverlaysLPr(pw);
20861            }
20862
20863            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20864                if (dumpState.onTitlePrinted()) pw.println();
20865                mSettings.dumpReadMessagesLPr(pw, dumpState);
20866
20867                pw.println();
20868                pw.println("Package warning messages:");
20869                BufferedReader in = null;
20870                String line = null;
20871                try {
20872                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20873                    while ((line = in.readLine()) != null) {
20874                        if (line.contains("ignored: updated version")) continue;
20875                        pw.println(line);
20876                    }
20877                } catch (IOException ignored) {
20878                } finally {
20879                    IoUtils.closeQuietly(in);
20880                }
20881            }
20882
20883            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20884                BufferedReader in = null;
20885                String line = null;
20886                try {
20887                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20888                    while ((line = in.readLine()) != null) {
20889                        if (line.contains("ignored: updated version")) continue;
20890                        pw.print("msg,");
20891                        pw.println(line);
20892                    }
20893                } catch (IOException ignored) {
20894                } finally {
20895                    IoUtils.closeQuietly(in);
20896                }
20897            }
20898        }
20899    }
20900
20901    private void dumpProto(FileDescriptor fd) {
20902        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20903
20904        synchronized (mPackages) {
20905            final long requiredVerifierPackageToken =
20906                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20907            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20908            proto.write(
20909                    PackageServiceDumpProto.PackageShortProto.UID,
20910                    getPackageUid(
20911                            mRequiredVerifierPackage,
20912                            MATCH_DEBUG_TRIAGED_MISSING,
20913                            UserHandle.USER_SYSTEM));
20914            proto.end(requiredVerifierPackageToken);
20915
20916            if (mIntentFilterVerifierComponent != null) {
20917                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20918                final long verifierPackageToken =
20919                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20920                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20921                proto.write(
20922                        PackageServiceDumpProto.PackageShortProto.UID,
20923                        getPackageUid(
20924                                verifierPackageName,
20925                                MATCH_DEBUG_TRIAGED_MISSING,
20926                                UserHandle.USER_SYSTEM));
20927                proto.end(verifierPackageToken);
20928            }
20929
20930            dumpSharedLibrariesProto(proto);
20931            dumpFeaturesProto(proto);
20932            mSettings.dumpPackagesProto(proto);
20933            mSettings.dumpSharedUsersProto(proto);
20934            dumpMessagesProto(proto);
20935        }
20936        proto.flush();
20937    }
20938
20939    private void dumpMessagesProto(ProtoOutputStream proto) {
20940        BufferedReader in = null;
20941        String line = null;
20942        try {
20943            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20944            while ((line = in.readLine()) != null) {
20945                if (line.contains("ignored: updated version")) continue;
20946                proto.write(PackageServiceDumpProto.MESSAGES, line);
20947            }
20948        } catch (IOException ignored) {
20949        } finally {
20950            IoUtils.closeQuietly(in);
20951        }
20952    }
20953
20954    private void dumpFeaturesProto(ProtoOutputStream proto) {
20955        synchronized (mAvailableFeatures) {
20956            final int count = mAvailableFeatures.size();
20957            for (int i = 0; i < count; i++) {
20958                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20959                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20960                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20961                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20962                proto.end(featureToken);
20963            }
20964        }
20965    }
20966
20967    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20968        final int count = mSharedLibraries.size();
20969        for (int i = 0; i < count; i++) {
20970            final String libName = mSharedLibraries.keyAt(i);
20971            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20972            if (versionedLib == null) {
20973                continue;
20974            }
20975            final int versionCount = versionedLib.size();
20976            for (int j = 0; j < versionCount; j++) {
20977                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20978                final long sharedLibraryToken =
20979                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20980                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20981                final boolean isJar = (libEntry.path != null);
20982                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20983                if (isJar) {
20984                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20985                } else {
20986                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20987                }
20988                proto.end(sharedLibraryToken);
20989            }
20990        }
20991    }
20992
20993    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20994        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20995        ipw.println();
20996        ipw.println("Dexopt state:");
20997        ipw.increaseIndent();
20998        Collection<PackageParser.Package> packages = null;
20999        if (packageName != null) {
21000            PackageParser.Package targetPackage = mPackages.get(packageName);
21001            if (targetPackage != null) {
21002                packages = Collections.singletonList(targetPackage);
21003            } else {
21004                ipw.println("Unable to find package: " + packageName);
21005                return;
21006            }
21007        } else {
21008            packages = mPackages.values();
21009        }
21010
21011        for (PackageParser.Package pkg : packages) {
21012            ipw.println("[" + pkg.packageName + "]");
21013            ipw.increaseIndent();
21014            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21015            ipw.decreaseIndent();
21016        }
21017    }
21018
21019    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21020        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21021        ipw.println();
21022        ipw.println("Compiler stats:");
21023        ipw.increaseIndent();
21024        Collection<PackageParser.Package> packages = null;
21025        if (packageName != null) {
21026            PackageParser.Package targetPackage = mPackages.get(packageName);
21027            if (targetPackage != null) {
21028                packages = Collections.singletonList(targetPackage);
21029            } else {
21030                ipw.println("Unable to find package: " + packageName);
21031                return;
21032            }
21033        } else {
21034            packages = mPackages.values();
21035        }
21036
21037        for (PackageParser.Package pkg : packages) {
21038            ipw.println("[" + pkg.packageName + "]");
21039            ipw.increaseIndent();
21040
21041            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21042            if (stats == null) {
21043                ipw.println("(No recorded stats)");
21044            } else {
21045                stats.dump(ipw);
21046            }
21047            ipw.decreaseIndent();
21048        }
21049    }
21050
21051    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21052        pw.println("Enabled overlay paths:");
21053        final int N = mEnabledOverlayPaths.size();
21054        for (int i = 0; i < N; i++) {
21055            final int userId = mEnabledOverlayPaths.keyAt(i);
21056            pw.println(String.format("    User %d:", userId));
21057            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21058                mEnabledOverlayPaths.valueAt(i);
21059            final int M = userSpecificOverlays.size();
21060            for (int j = 0; j < M; j++) {
21061                final String targetPackageName = userSpecificOverlays.keyAt(j);
21062                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21063                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21064            }
21065        }
21066    }
21067
21068    private String dumpDomainString(String packageName) {
21069        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21070                .getList();
21071        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21072
21073        ArraySet<String> result = new ArraySet<>();
21074        if (iviList.size() > 0) {
21075            for (IntentFilterVerificationInfo ivi : iviList) {
21076                for (String host : ivi.getDomains()) {
21077                    result.add(host);
21078                }
21079            }
21080        }
21081        if (filters != null && filters.size() > 0) {
21082            for (IntentFilter filter : filters) {
21083                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21084                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21085                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21086                    result.addAll(filter.getHostsList());
21087                }
21088            }
21089        }
21090
21091        StringBuilder sb = new StringBuilder(result.size() * 16);
21092        for (String domain : result) {
21093            if (sb.length() > 0) sb.append(" ");
21094            sb.append(domain);
21095        }
21096        return sb.toString();
21097    }
21098
21099    // ------- apps on sdcard specific code -------
21100    static final boolean DEBUG_SD_INSTALL = false;
21101
21102    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21103
21104    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21105
21106    private boolean mMediaMounted = false;
21107
21108    static String getEncryptKey() {
21109        try {
21110            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21111                    SD_ENCRYPTION_KEYSTORE_NAME);
21112            if (sdEncKey == null) {
21113                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21114                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21115                if (sdEncKey == null) {
21116                    Slog.e(TAG, "Failed to create encryption keys");
21117                    return null;
21118                }
21119            }
21120            return sdEncKey;
21121        } catch (NoSuchAlgorithmException nsae) {
21122            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21123            return null;
21124        } catch (IOException ioe) {
21125            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21126            return null;
21127        }
21128    }
21129
21130    /*
21131     * Update media status on PackageManager.
21132     */
21133    @Override
21134    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21135        int callingUid = Binder.getCallingUid();
21136        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21137            throw new SecurityException("Media status can only be updated by the system");
21138        }
21139        // reader; this apparently protects mMediaMounted, but should probably
21140        // be a different lock in that case.
21141        synchronized (mPackages) {
21142            Log.i(TAG, "Updating external media status from "
21143                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21144                    + (mediaStatus ? "mounted" : "unmounted"));
21145            if (DEBUG_SD_INSTALL)
21146                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21147                        + ", mMediaMounted=" + mMediaMounted);
21148            if (mediaStatus == mMediaMounted) {
21149                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21150                        : 0, -1);
21151                mHandler.sendMessage(msg);
21152                return;
21153            }
21154            mMediaMounted = mediaStatus;
21155        }
21156        // Queue up an async operation since the package installation may take a
21157        // little while.
21158        mHandler.post(new Runnable() {
21159            public void run() {
21160                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21161            }
21162        });
21163    }
21164
21165    /**
21166     * Called by StorageManagerService when the initial ASECs to scan are available.
21167     * Should block until all the ASEC containers are finished being scanned.
21168     */
21169    public void scanAvailableAsecs() {
21170        updateExternalMediaStatusInner(true, false, false);
21171    }
21172
21173    /*
21174     * Collect information of applications on external media, map them against
21175     * existing containers and update information based on current mount status.
21176     * Please note that we always have to report status if reportStatus has been
21177     * set to true especially when unloading packages.
21178     */
21179    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21180            boolean externalStorage) {
21181        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21182        int[] uidArr = EmptyArray.INT;
21183
21184        final String[] list = PackageHelper.getSecureContainerList();
21185        if (ArrayUtils.isEmpty(list)) {
21186            Log.i(TAG, "No secure containers found");
21187        } else {
21188            // Process list of secure containers and categorize them
21189            // as active or stale based on their package internal state.
21190
21191            // reader
21192            synchronized (mPackages) {
21193                for (String cid : list) {
21194                    // Leave stages untouched for now; installer service owns them
21195                    if (PackageInstallerService.isStageName(cid)) continue;
21196
21197                    if (DEBUG_SD_INSTALL)
21198                        Log.i(TAG, "Processing container " + cid);
21199                    String pkgName = getAsecPackageName(cid);
21200                    if (pkgName == null) {
21201                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21202                        continue;
21203                    }
21204                    if (DEBUG_SD_INSTALL)
21205                        Log.i(TAG, "Looking for pkg : " + pkgName);
21206
21207                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21208                    if (ps == null) {
21209                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21210                        continue;
21211                    }
21212
21213                    /*
21214                     * Skip packages that are not external if we're unmounting
21215                     * external storage.
21216                     */
21217                    if (externalStorage && !isMounted && !isExternal(ps)) {
21218                        continue;
21219                    }
21220
21221                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21222                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21223                    // The package status is changed only if the code path
21224                    // matches between settings and the container id.
21225                    if (ps.codePathString != null
21226                            && ps.codePathString.startsWith(args.getCodePath())) {
21227                        if (DEBUG_SD_INSTALL) {
21228                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21229                                    + " at code path: " + ps.codePathString);
21230                        }
21231
21232                        // We do have a valid package installed on sdcard
21233                        processCids.put(args, ps.codePathString);
21234                        final int uid = ps.appId;
21235                        if (uid != -1) {
21236                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21237                        }
21238                    } else {
21239                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21240                                + ps.codePathString);
21241                    }
21242                }
21243            }
21244
21245            Arrays.sort(uidArr);
21246        }
21247
21248        // Process packages with valid entries.
21249        if (isMounted) {
21250            if (DEBUG_SD_INSTALL)
21251                Log.i(TAG, "Loading packages");
21252            loadMediaPackages(processCids, uidArr, externalStorage);
21253            startCleaningPackages();
21254            mInstallerService.onSecureContainersAvailable();
21255        } else {
21256            if (DEBUG_SD_INSTALL)
21257                Log.i(TAG, "Unloading packages");
21258            unloadMediaPackages(processCids, uidArr, reportStatus);
21259        }
21260    }
21261
21262    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21263            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21264        final int size = infos.size();
21265        final String[] packageNames = new String[size];
21266        final int[] packageUids = new int[size];
21267        for (int i = 0; i < size; i++) {
21268            final ApplicationInfo info = infos.get(i);
21269            packageNames[i] = info.packageName;
21270            packageUids[i] = info.uid;
21271        }
21272        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21273                finishedReceiver);
21274    }
21275
21276    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21277            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21278        sendResourcesChangedBroadcast(mediaStatus, replacing,
21279                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21280    }
21281
21282    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21283            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21284        int size = pkgList.length;
21285        if (size > 0) {
21286            // Send broadcasts here
21287            Bundle extras = new Bundle();
21288            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21289            if (uidArr != null) {
21290                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21291            }
21292            if (replacing) {
21293                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21294            }
21295            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21296                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21297            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21298        }
21299    }
21300
21301   /*
21302     * Look at potentially valid container ids from processCids If package
21303     * information doesn't match the one on record or package scanning fails,
21304     * the cid is added to list of removeCids. We currently don't delete stale
21305     * containers.
21306     */
21307    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21308            boolean externalStorage) {
21309        ArrayList<String> pkgList = new ArrayList<String>();
21310        Set<AsecInstallArgs> keys = processCids.keySet();
21311
21312        for (AsecInstallArgs args : keys) {
21313            String codePath = processCids.get(args);
21314            if (DEBUG_SD_INSTALL)
21315                Log.i(TAG, "Loading container : " + args.cid);
21316            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21317            try {
21318                // Make sure there are no container errors first.
21319                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21320                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21321                            + " when installing from sdcard");
21322                    continue;
21323                }
21324                // Check code path here.
21325                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21326                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21327                            + " does not match one in settings " + codePath);
21328                    continue;
21329                }
21330                // Parse package
21331                int parseFlags = mDefParseFlags;
21332                if (args.isExternalAsec()) {
21333                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21334                }
21335                if (args.isFwdLocked()) {
21336                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21337                }
21338
21339                synchronized (mInstallLock) {
21340                    PackageParser.Package pkg = null;
21341                    try {
21342                        // Sadly we don't know the package name yet to freeze it
21343                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21344                                SCAN_IGNORE_FROZEN, 0, null);
21345                    } catch (PackageManagerException e) {
21346                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21347                    }
21348                    // Scan the package
21349                    if (pkg != null) {
21350                        /*
21351                         * TODO why is the lock being held? doPostInstall is
21352                         * called in other places without the lock. This needs
21353                         * to be straightened out.
21354                         */
21355                        // writer
21356                        synchronized (mPackages) {
21357                            retCode = PackageManager.INSTALL_SUCCEEDED;
21358                            pkgList.add(pkg.packageName);
21359                            // Post process args
21360                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21361                                    pkg.applicationInfo.uid);
21362                        }
21363                    } else {
21364                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21365                    }
21366                }
21367
21368            } finally {
21369                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21370                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21371                }
21372            }
21373        }
21374        // writer
21375        synchronized (mPackages) {
21376            // If the platform SDK has changed since the last time we booted,
21377            // we need to re-grant app permission to catch any new ones that
21378            // appear. This is really a hack, and means that apps can in some
21379            // cases get permissions that the user didn't initially explicitly
21380            // allow... it would be nice to have some better way to handle
21381            // this situation.
21382            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21383                    : mSettings.getInternalVersion();
21384            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21385                    : StorageManager.UUID_PRIVATE_INTERNAL;
21386
21387            int updateFlags = UPDATE_PERMISSIONS_ALL;
21388            if (ver.sdkVersion != mSdkVersion) {
21389                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21390                        + mSdkVersion + "; regranting permissions for external");
21391                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21392            }
21393            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21394
21395            // Yay, everything is now upgraded
21396            ver.forceCurrent();
21397
21398            // can downgrade to reader
21399            // Persist settings
21400            mSettings.writeLPr();
21401        }
21402        // Send a broadcast to let everyone know we are done processing
21403        if (pkgList.size() > 0) {
21404            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21405        }
21406    }
21407
21408   /*
21409     * Utility method to unload a list of specified containers
21410     */
21411    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21412        // Just unmount all valid containers.
21413        for (AsecInstallArgs arg : cidArgs) {
21414            synchronized (mInstallLock) {
21415                arg.doPostDeleteLI(false);
21416           }
21417       }
21418   }
21419
21420    /*
21421     * Unload packages mounted on external media. This involves deleting package
21422     * data from internal structures, sending broadcasts about disabled packages,
21423     * gc'ing to free up references, unmounting all secure containers
21424     * corresponding to packages on external media, and posting a
21425     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21426     * that we always have to post this message if status has been requested no
21427     * matter what.
21428     */
21429    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21430            final boolean reportStatus) {
21431        if (DEBUG_SD_INSTALL)
21432            Log.i(TAG, "unloading media packages");
21433        ArrayList<String> pkgList = new ArrayList<String>();
21434        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21435        final Set<AsecInstallArgs> keys = processCids.keySet();
21436        for (AsecInstallArgs args : keys) {
21437            String pkgName = args.getPackageName();
21438            if (DEBUG_SD_INSTALL)
21439                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21440            // Delete package internally
21441            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21442            synchronized (mInstallLock) {
21443                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21444                final boolean res;
21445                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21446                        "unloadMediaPackages")) {
21447                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21448                            null);
21449                }
21450                if (res) {
21451                    pkgList.add(pkgName);
21452                } else {
21453                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21454                    failedList.add(args);
21455                }
21456            }
21457        }
21458
21459        // reader
21460        synchronized (mPackages) {
21461            // We didn't update the settings after removing each package;
21462            // write them now for all packages.
21463            mSettings.writeLPr();
21464        }
21465
21466        // We have to absolutely send UPDATED_MEDIA_STATUS only
21467        // after confirming that all the receivers processed the ordered
21468        // broadcast when packages get disabled, force a gc to clean things up.
21469        // and unload all the containers.
21470        if (pkgList.size() > 0) {
21471            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21472                    new IIntentReceiver.Stub() {
21473                public void performReceive(Intent intent, int resultCode, String data,
21474                        Bundle extras, boolean ordered, boolean sticky,
21475                        int sendingUser) throws RemoteException {
21476                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21477                            reportStatus ? 1 : 0, 1, keys);
21478                    mHandler.sendMessage(msg);
21479                }
21480            });
21481        } else {
21482            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21483                    keys);
21484            mHandler.sendMessage(msg);
21485        }
21486    }
21487
21488    private void loadPrivatePackages(final VolumeInfo vol) {
21489        mHandler.post(new Runnable() {
21490            @Override
21491            public void run() {
21492                loadPrivatePackagesInner(vol);
21493            }
21494        });
21495    }
21496
21497    private void loadPrivatePackagesInner(VolumeInfo vol) {
21498        final String volumeUuid = vol.fsUuid;
21499        if (TextUtils.isEmpty(volumeUuid)) {
21500            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21501            return;
21502        }
21503
21504        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21505        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21506        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21507
21508        final VersionInfo ver;
21509        final List<PackageSetting> packages;
21510        synchronized (mPackages) {
21511            ver = mSettings.findOrCreateVersion(volumeUuid);
21512            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21513        }
21514
21515        for (PackageSetting ps : packages) {
21516            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21517            synchronized (mInstallLock) {
21518                final PackageParser.Package pkg;
21519                try {
21520                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21521                    loaded.add(pkg.applicationInfo);
21522
21523                } catch (PackageManagerException e) {
21524                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21525                }
21526
21527                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21528                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21529                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21530                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21531                }
21532            }
21533        }
21534
21535        // Reconcile app data for all started/unlocked users
21536        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21537        final UserManager um = mContext.getSystemService(UserManager.class);
21538        UserManagerInternal umInternal = getUserManagerInternal();
21539        for (UserInfo user : um.getUsers()) {
21540            final int flags;
21541            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21542                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21543            } else if (umInternal.isUserRunning(user.id)) {
21544                flags = StorageManager.FLAG_STORAGE_DE;
21545            } else {
21546                continue;
21547            }
21548
21549            try {
21550                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21551                synchronized (mInstallLock) {
21552                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21553                }
21554            } catch (IllegalStateException e) {
21555                // Device was probably ejected, and we'll process that event momentarily
21556                Slog.w(TAG, "Failed to prepare storage: " + e);
21557            }
21558        }
21559
21560        synchronized (mPackages) {
21561            int updateFlags = UPDATE_PERMISSIONS_ALL;
21562            if (ver.sdkVersion != mSdkVersion) {
21563                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21564                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21565                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21566            }
21567            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21568
21569            // Yay, everything is now upgraded
21570            ver.forceCurrent();
21571
21572            mSettings.writeLPr();
21573        }
21574
21575        for (PackageFreezer freezer : freezers) {
21576            freezer.close();
21577        }
21578
21579        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21580        sendResourcesChangedBroadcast(true, false, loaded, null);
21581    }
21582
21583    private void unloadPrivatePackages(final VolumeInfo vol) {
21584        mHandler.post(new Runnable() {
21585            @Override
21586            public void run() {
21587                unloadPrivatePackagesInner(vol);
21588            }
21589        });
21590    }
21591
21592    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21593        final String volumeUuid = vol.fsUuid;
21594        if (TextUtils.isEmpty(volumeUuid)) {
21595            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21596            return;
21597        }
21598
21599        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21600        synchronized (mInstallLock) {
21601        synchronized (mPackages) {
21602            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21603            for (PackageSetting ps : packages) {
21604                if (ps.pkg == null) continue;
21605
21606                final ApplicationInfo info = ps.pkg.applicationInfo;
21607                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21608                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21609
21610                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21611                        "unloadPrivatePackagesInner")) {
21612                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21613                            false, null)) {
21614                        unloaded.add(info);
21615                    } else {
21616                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21617                    }
21618                }
21619
21620                // Try very hard to release any references to this package
21621                // so we don't risk the system server being killed due to
21622                // open FDs
21623                AttributeCache.instance().removePackage(ps.name);
21624            }
21625
21626            mSettings.writeLPr();
21627        }
21628        }
21629
21630        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21631        sendResourcesChangedBroadcast(false, false, unloaded, null);
21632
21633        // Try very hard to release any references to this path so we don't risk
21634        // the system server being killed due to open FDs
21635        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21636
21637        for (int i = 0; i < 3; i++) {
21638            System.gc();
21639            System.runFinalization();
21640        }
21641    }
21642
21643    private void assertPackageKnown(String volumeUuid, String packageName)
21644            throws PackageManagerException {
21645        synchronized (mPackages) {
21646            // Normalize package name to handle renamed packages
21647            packageName = normalizePackageNameLPr(packageName);
21648
21649            final PackageSetting ps = mSettings.mPackages.get(packageName);
21650            if (ps == null) {
21651                throw new PackageManagerException("Package " + packageName + " is unknown");
21652            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21653                throw new PackageManagerException(
21654                        "Package " + packageName + " found on unknown volume " + volumeUuid
21655                                + "; expected volume " + ps.volumeUuid);
21656            }
21657        }
21658    }
21659
21660    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21661            throws PackageManagerException {
21662        synchronized (mPackages) {
21663            // Normalize package name to handle renamed packages
21664            packageName = normalizePackageNameLPr(packageName);
21665
21666            final PackageSetting ps = mSettings.mPackages.get(packageName);
21667            if (ps == null) {
21668                throw new PackageManagerException("Package " + packageName + " is unknown");
21669            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21670                throw new PackageManagerException(
21671                        "Package " + packageName + " found on unknown volume " + volumeUuid
21672                                + "; expected volume " + ps.volumeUuid);
21673            } else if (!ps.getInstalled(userId)) {
21674                throw new PackageManagerException(
21675                        "Package " + packageName + " not installed for user " + userId);
21676            }
21677        }
21678    }
21679
21680    private List<String> collectAbsoluteCodePaths() {
21681        synchronized (mPackages) {
21682            List<String> codePaths = new ArrayList<>();
21683            final int packageCount = mSettings.mPackages.size();
21684            for (int i = 0; i < packageCount; i++) {
21685                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21686                codePaths.add(ps.codePath.getAbsolutePath());
21687            }
21688            return codePaths;
21689        }
21690    }
21691
21692    /**
21693     * Examine all apps present on given mounted volume, and destroy apps that
21694     * aren't expected, either due to uninstallation or reinstallation on
21695     * another volume.
21696     */
21697    private void reconcileApps(String volumeUuid) {
21698        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21699        List<File> filesToDelete = null;
21700
21701        final File[] files = FileUtils.listFilesOrEmpty(
21702                Environment.getDataAppDirectory(volumeUuid));
21703        for (File file : files) {
21704            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21705                    && !PackageInstallerService.isStageName(file.getName());
21706            if (!isPackage) {
21707                // Ignore entries which are not packages
21708                continue;
21709            }
21710
21711            String absolutePath = file.getAbsolutePath();
21712
21713            boolean pathValid = false;
21714            final int absoluteCodePathCount = absoluteCodePaths.size();
21715            for (int i = 0; i < absoluteCodePathCount; i++) {
21716                String absoluteCodePath = absoluteCodePaths.get(i);
21717                if (absolutePath.startsWith(absoluteCodePath)) {
21718                    pathValid = true;
21719                    break;
21720                }
21721            }
21722
21723            if (!pathValid) {
21724                if (filesToDelete == null) {
21725                    filesToDelete = new ArrayList<>();
21726                }
21727                filesToDelete.add(file);
21728            }
21729        }
21730
21731        if (filesToDelete != null) {
21732            final int fileToDeleteCount = filesToDelete.size();
21733            for (int i = 0; i < fileToDeleteCount; i++) {
21734                File fileToDelete = filesToDelete.get(i);
21735                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21736                synchronized (mInstallLock) {
21737                    removeCodePathLI(fileToDelete);
21738                }
21739            }
21740        }
21741    }
21742
21743    /**
21744     * Reconcile all app data for the given user.
21745     * <p>
21746     * Verifies that directories exist and that ownership and labeling is
21747     * correct for all installed apps on all mounted volumes.
21748     */
21749    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21750        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21751        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21752            final String volumeUuid = vol.getFsUuid();
21753            synchronized (mInstallLock) {
21754                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21755            }
21756        }
21757    }
21758
21759    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21760            boolean migrateAppData) {
21761        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21762    }
21763
21764    /**
21765     * Reconcile all app data on given mounted volume.
21766     * <p>
21767     * Destroys app data that isn't expected, either due to uninstallation or
21768     * reinstallation on another volume.
21769     * <p>
21770     * Verifies that directories exist and that ownership and labeling is
21771     * correct for all installed apps.
21772     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21773     */
21774    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21775            boolean migrateAppData, boolean onlyCoreApps) {
21776        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21777                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21778        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21779
21780        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21781        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21782
21783        // First look for stale data that doesn't belong, and check if things
21784        // have changed since we did our last restorecon
21785        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21786            if (StorageManager.isFileEncryptedNativeOrEmulated()
21787                    && !StorageManager.isUserKeyUnlocked(userId)) {
21788                throw new RuntimeException(
21789                        "Yikes, someone asked us to reconcile CE storage while " + userId
21790                                + " was still locked; this would have caused massive data loss!");
21791            }
21792
21793            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21794            for (File file : files) {
21795                final String packageName = file.getName();
21796                try {
21797                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21798                } catch (PackageManagerException e) {
21799                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21800                    try {
21801                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21802                                StorageManager.FLAG_STORAGE_CE, 0);
21803                    } catch (InstallerException e2) {
21804                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21805                    }
21806                }
21807            }
21808        }
21809        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21810            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21811            for (File file : files) {
21812                final String packageName = file.getName();
21813                try {
21814                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21815                } catch (PackageManagerException e) {
21816                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21817                    try {
21818                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21819                                StorageManager.FLAG_STORAGE_DE, 0);
21820                    } catch (InstallerException e2) {
21821                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21822                    }
21823                }
21824            }
21825        }
21826
21827        // Ensure that data directories are ready to roll for all packages
21828        // installed for this volume and user
21829        final List<PackageSetting> packages;
21830        synchronized (mPackages) {
21831            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21832        }
21833        int preparedCount = 0;
21834        for (PackageSetting ps : packages) {
21835            final String packageName = ps.name;
21836            if (ps.pkg == null) {
21837                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21838                // TODO: might be due to legacy ASEC apps; we should circle back
21839                // and reconcile again once they're scanned
21840                continue;
21841            }
21842            // Skip non-core apps if requested
21843            if (onlyCoreApps && !ps.pkg.coreApp) {
21844                result.add(packageName);
21845                continue;
21846            }
21847
21848            if (ps.getInstalled(userId)) {
21849                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21850                preparedCount++;
21851            }
21852        }
21853
21854        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21855        return result;
21856    }
21857
21858    /**
21859     * Prepare app data for the given app just after it was installed or
21860     * upgraded. This method carefully only touches users that it's installed
21861     * for, and it forces a restorecon to handle any seinfo changes.
21862     * <p>
21863     * Verifies that directories exist and that ownership and labeling is
21864     * correct for all installed apps. If there is an ownership mismatch, it
21865     * will try recovering system apps by wiping data; third-party app data is
21866     * left intact.
21867     * <p>
21868     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21869     */
21870    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21871        final PackageSetting ps;
21872        synchronized (mPackages) {
21873            ps = mSettings.mPackages.get(pkg.packageName);
21874            mSettings.writeKernelMappingLPr(ps);
21875        }
21876
21877        final UserManager um = mContext.getSystemService(UserManager.class);
21878        UserManagerInternal umInternal = getUserManagerInternal();
21879        for (UserInfo user : um.getUsers()) {
21880            final int flags;
21881            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21882                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21883            } else if (umInternal.isUserRunning(user.id)) {
21884                flags = StorageManager.FLAG_STORAGE_DE;
21885            } else {
21886                continue;
21887            }
21888
21889            if (ps.getInstalled(user.id)) {
21890                // TODO: when user data is locked, mark that we're still dirty
21891                prepareAppDataLIF(pkg, user.id, flags);
21892            }
21893        }
21894    }
21895
21896    /**
21897     * Prepare app data for the given app.
21898     * <p>
21899     * Verifies that directories exist and that ownership and labeling is
21900     * correct for all installed apps. If there is an ownership mismatch, this
21901     * will try recovering system apps by wiping data; third-party app data is
21902     * left intact.
21903     */
21904    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21905        if (pkg == null) {
21906            Slog.wtf(TAG, "Package was null!", new Throwable());
21907            return;
21908        }
21909        prepareAppDataLeafLIF(pkg, userId, flags);
21910        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21911        for (int i = 0; i < childCount; i++) {
21912            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21913        }
21914    }
21915
21916    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21917            boolean maybeMigrateAppData) {
21918        prepareAppDataLIF(pkg, userId, flags);
21919
21920        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21921            // We may have just shuffled around app data directories, so
21922            // prepare them one more time
21923            prepareAppDataLIF(pkg, userId, flags);
21924        }
21925    }
21926
21927    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21928        if (DEBUG_APP_DATA) {
21929            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21930                    + Integer.toHexString(flags));
21931        }
21932
21933        final String volumeUuid = pkg.volumeUuid;
21934        final String packageName = pkg.packageName;
21935        final ApplicationInfo app = pkg.applicationInfo;
21936        final int appId = UserHandle.getAppId(app.uid);
21937
21938        Preconditions.checkNotNull(app.seInfo);
21939
21940        long ceDataInode = -1;
21941        try {
21942            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21943                    appId, app.seInfo, app.targetSdkVersion);
21944        } catch (InstallerException e) {
21945            if (app.isSystemApp()) {
21946                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21947                        + ", but trying to recover: " + e);
21948                destroyAppDataLeafLIF(pkg, userId, flags);
21949                try {
21950                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21951                            appId, app.seInfo, app.targetSdkVersion);
21952                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21953                } catch (InstallerException e2) {
21954                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21955                }
21956            } else {
21957                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21958            }
21959        }
21960
21961        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21962            // TODO: mark this structure as dirty so we persist it!
21963            synchronized (mPackages) {
21964                final PackageSetting ps = mSettings.mPackages.get(packageName);
21965                if (ps != null) {
21966                    ps.setCeDataInode(ceDataInode, userId);
21967                }
21968            }
21969        }
21970
21971        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21972    }
21973
21974    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21975        if (pkg == null) {
21976            Slog.wtf(TAG, "Package was null!", new Throwable());
21977            return;
21978        }
21979        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21980        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21981        for (int i = 0; i < childCount; i++) {
21982            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21983        }
21984    }
21985
21986    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21987        final String volumeUuid = pkg.volumeUuid;
21988        final String packageName = pkg.packageName;
21989        final ApplicationInfo app = pkg.applicationInfo;
21990
21991        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21992            // Create a native library symlink only if we have native libraries
21993            // and if the native libraries are 32 bit libraries. We do not provide
21994            // this symlink for 64 bit libraries.
21995            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21996                final String nativeLibPath = app.nativeLibraryDir;
21997                try {
21998                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21999                            nativeLibPath, userId);
22000                } catch (InstallerException e) {
22001                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22002                }
22003            }
22004        }
22005    }
22006
22007    /**
22008     * For system apps on non-FBE devices, this method migrates any existing
22009     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22010     * requested by the app.
22011     */
22012    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22013        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22014                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22015            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22016                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22017            try {
22018                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22019                        storageTarget);
22020            } catch (InstallerException e) {
22021                logCriticalInfo(Log.WARN,
22022                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22023            }
22024            return true;
22025        } else {
22026            return false;
22027        }
22028    }
22029
22030    public PackageFreezer freezePackage(String packageName, String killReason) {
22031        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22032    }
22033
22034    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22035        return new PackageFreezer(packageName, userId, killReason);
22036    }
22037
22038    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22039            String killReason) {
22040        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22041    }
22042
22043    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22044            String killReason) {
22045        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22046            return new PackageFreezer();
22047        } else {
22048            return freezePackage(packageName, userId, killReason);
22049        }
22050    }
22051
22052    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22053            String killReason) {
22054        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22055    }
22056
22057    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22058            String killReason) {
22059        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22060            return new PackageFreezer();
22061        } else {
22062            return freezePackage(packageName, userId, killReason);
22063        }
22064    }
22065
22066    /**
22067     * Class that freezes and kills the given package upon creation, and
22068     * unfreezes it upon closing. This is typically used when doing surgery on
22069     * app code/data to prevent the app from running while you're working.
22070     */
22071    private class PackageFreezer implements AutoCloseable {
22072        private final String mPackageName;
22073        private final PackageFreezer[] mChildren;
22074
22075        private final boolean mWeFroze;
22076
22077        private final AtomicBoolean mClosed = new AtomicBoolean();
22078        private final CloseGuard mCloseGuard = CloseGuard.get();
22079
22080        /**
22081         * Create and return a stub freezer that doesn't actually do anything,
22082         * typically used when someone requested
22083         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22084         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22085         */
22086        public PackageFreezer() {
22087            mPackageName = null;
22088            mChildren = null;
22089            mWeFroze = false;
22090            mCloseGuard.open("close");
22091        }
22092
22093        public PackageFreezer(String packageName, int userId, String killReason) {
22094            synchronized (mPackages) {
22095                mPackageName = packageName;
22096                mWeFroze = mFrozenPackages.add(mPackageName);
22097
22098                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22099                if (ps != null) {
22100                    killApplication(ps.name, ps.appId, userId, killReason);
22101                }
22102
22103                final PackageParser.Package p = mPackages.get(packageName);
22104                if (p != null && p.childPackages != null) {
22105                    final int N = p.childPackages.size();
22106                    mChildren = new PackageFreezer[N];
22107                    for (int i = 0; i < N; i++) {
22108                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22109                                userId, killReason);
22110                    }
22111                } else {
22112                    mChildren = null;
22113                }
22114            }
22115            mCloseGuard.open("close");
22116        }
22117
22118        @Override
22119        protected void finalize() throws Throwable {
22120            try {
22121                mCloseGuard.warnIfOpen();
22122                close();
22123            } finally {
22124                super.finalize();
22125            }
22126        }
22127
22128        @Override
22129        public void close() {
22130            mCloseGuard.close();
22131            if (mClosed.compareAndSet(false, true)) {
22132                synchronized (mPackages) {
22133                    if (mWeFroze) {
22134                        mFrozenPackages.remove(mPackageName);
22135                    }
22136
22137                    if (mChildren != null) {
22138                        for (PackageFreezer freezer : mChildren) {
22139                            freezer.close();
22140                        }
22141                    }
22142                }
22143            }
22144        }
22145    }
22146
22147    /**
22148     * Verify that given package is currently frozen.
22149     */
22150    private void checkPackageFrozen(String packageName) {
22151        synchronized (mPackages) {
22152            if (!mFrozenPackages.contains(packageName)) {
22153                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22154            }
22155        }
22156    }
22157
22158    @Override
22159    public int movePackage(final String packageName, final String volumeUuid) {
22160        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22161
22162        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22163        final int moveId = mNextMoveId.getAndIncrement();
22164        mHandler.post(new Runnable() {
22165            @Override
22166            public void run() {
22167                try {
22168                    movePackageInternal(packageName, volumeUuid, moveId, user);
22169                } catch (PackageManagerException e) {
22170                    Slog.w(TAG, "Failed to move " + packageName, e);
22171                    mMoveCallbacks.notifyStatusChanged(moveId,
22172                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22173                }
22174            }
22175        });
22176        return moveId;
22177    }
22178
22179    private void movePackageInternal(final String packageName, final String volumeUuid,
22180            final int moveId, UserHandle user) throws PackageManagerException {
22181        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22182        final PackageManager pm = mContext.getPackageManager();
22183
22184        final boolean currentAsec;
22185        final String currentVolumeUuid;
22186        final File codeFile;
22187        final String installerPackageName;
22188        final String packageAbiOverride;
22189        final int appId;
22190        final String seinfo;
22191        final String label;
22192        final int targetSdkVersion;
22193        final PackageFreezer freezer;
22194        final int[] installedUserIds;
22195
22196        // reader
22197        synchronized (mPackages) {
22198            final PackageParser.Package pkg = mPackages.get(packageName);
22199            final PackageSetting ps = mSettings.mPackages.get(packageName);
22200            if (pkg == null || ps == null) {
22201                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22202            }
22203
22204            if (pkg.applicationInfo.isSystemApp()) {
22205                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22206                        "Cannot move system application");
22207            }
22208
22209            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22210            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22211                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22212            if (isInternalStorage && !allow3rdPartyOnInternal) {
22213                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22214                        "3rd party apps are not allowed on internal storage");
22215            }
22216
22217            if (pkg.applicationInfo.isExternalAsec()) {
22218                currentAsec = true;
22219                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22220            } else if (pkg.applicationInfo.isForwardLocked()) {
22221                currentAsec = true;
22222                currentVolumeUuid = "forward_locked";
22223            } else {
22224                currentAsec = false;
22225                currentVolumeUuid = ps.volumeUuid;
22226
22227                final File probe = new File(pkg.codePath);
22228                final File probeOat = new File(probe, "oat");
22229                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22230                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22231                            "Move only supported for modern cluster style installs");
22232                }
22233            }
22234
22235            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22236                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22237                        "Package already moved to " + volumeUuid);
22238            }
22239            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22240                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22241                        "Device admin cannot be moved");
22242            }
22243
22244            if (mFrozenPackages.contains(packageName)) {
22245                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22246                        "Failed to move already frozen package");
22247            }
22248
22249            codeFile = new File(pkg.codePath);
22250            installerPackageName = ps.installerPackageName;
22251            packageAbiOverride = ps.cpuAbiOverrideString;
22252            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22253            seinfo = pkg.applicationInfo.seInfo;
22254            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22255            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22256            freezer = freezePackage(packageName, "movePackageInternal");
22257            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22258        }
22259
22260        final Bundle extras = new Bundle();
22261        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22262        extras.putString(Intent.EXTRA_TITLE, label);
22263        mMoveCallbacks.notifyCreated(moveId, extras);
22264
22265        int installFlags;
22266        final boolean moveCompleteApp;
22267        final File measurePath;
22268
22269        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22270            installFlags = INSTALL_INTERNAL;
22271            moveCompleteApp = !currentAsec;
22272            measurePath = Environment.getDataAppDirectory(volumeUuid);
22273        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22274            installFlags = INSTALL_EXTERNAL;
22275            moveCompleteApp = false;
22276            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22277        } else {
22278            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22279            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22280                    || !volume.isMountedWritable()) {
22281                freezer.close();
22282                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22283                        "Move location not mounted private volume");
22284            }
22285
22286            Preconditions.checkState(!currentAsec);
22287
22288            installFlags = INSTALL_INTERNAL;
22289            moveCompleteApp = true;
22290            measurePath = Environment.getDataAppDirectory(volumeUuid);
22291        }
22292
22293        final PackageStats stats = new PackageStats(null, -1);
22294        synchronized (mInstaller) {
22295            for (int userId : installedUserIds) {
22296                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22297                    freezer.close();
22298                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22299                            "Failed to measure package size");
22300                }
22301            }
22302        }
22303
22304        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22305                + stats.dataSize);
22306
22307        final long startFreeBytes = measurePath.getFreeSpace();
22308        final long sizeBytes;
22309        if (moveCompleteApp) {
22310            sizeBytes = stats.codeSize + stats.dataSize;
22311        } else {
22312            sizeBytes = stats.codeSize;
22313        }
22314
22315        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22316            freezer.close();
22317            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22318                    "Not enough free space to move");
22319        }
22320
22321        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22322
22323        final CountDownLatch installedLatch = new CountDownLatch(1);
22324        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22325            @Override
22326            public void onUserActionRequired(Intent intent) throws RemoteException {
22327                throw new IllegalStateException();
22328            }
22329
22330            @Override
22331            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22332                    Bundle extras) throws RemoteException {
22333                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22334                        + PackageManager.installStatusToString(returnCode, msg));
22335
22336                installedLatch.countDown();
22337                freezer.close();
22338
22339                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22340                switch (status) {
22341                    case PackageInstaller.STATUS_SUCCESS:
22342                        mMoveCallbacks.notifyStatusChanged(moveId,
22343                                PackageManager.MOVE_SUCCEEDED);
22344                        break;
22345                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22346                        mMoveCallbacks.notifyStatusChanged(moveId,
22347                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22348                        break;
22349                    default:
22350                        mMoveCallbacks.notifyStatusChanged(moveId,
22351                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22352                        break;
22353                }
22354            }
22355        };
22356
22357        final MoveInfo move;
22358        if (moveCompleteApp) {
22359            // Kick off a thread to report progress estimates
22360            new Thread() {
22361                @Override
22362                public void run() {
22363                    while (true) {
22364                        try {
22365                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22366                                break;
22367                            }
22368                        } catch (InterruptedException ignored) {
22369                        }
22370
22371                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22372                        final int progress = 10 + (int) MathUtils.constrain(
22373                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22374                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22375                    }
22376                }
22377            }.start();
22378
22379            final String dataAppName = codeFile.getName();
22380            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22381                    dataAppName, appId, seinfo, targetSdkVersion);
22382        } else {
22383            move = null;
22384        }
22385
22386        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22387
22388        final Message msg = mHandler.obtainMessage(INIT_COPY);
22389        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22390        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22391                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22392                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22393                PackageManager.INSTALL_REASON_UNKNOWN);
22394        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22395        msg.obj = params;
22396
22397        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22398                System.identityHashCode(msg.obj));
22399        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22400                System.identityHashCode(msg.obj));
22401
22402        mHandler.sendMessage(msg);
22403    }
22404
22405    @Override
22406    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22407        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22408
22409        final int realMoveId = mNextMoveId.getAndIncrement();
22410        final Bundle extras = new Bundle();
22411        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22412        mMoveCallbacks.notifyCreated(realMoveId, extras);
22413
22414        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22415            @Override
22416            public void onCreated(int moveId, Bundle extras) {
22417                // Ignored
22418            }
22419
22420            @Override
22421            public void onStatusChanged(int moveId, int status, long estMillis) {
22422                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22423            }
22424        };
22425
22426        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22427        storage.setPrimaryStorageUuid(volumeUuid, callback);
22428        return realMoveId;
22429    }
22430
22431    @Override
22432    public int getMoveStatus(int moveId) {
22433        mContext.enforceCallingOrSelfPermission(
22434                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22435        return mMoveCallbacks.mLastStatus.get(moveId);
22436    }
22437
22438    @Override
22439    public void registerMoveCallback(IPackageMoveObserver callback) {
22440        mContext.enforceCallingOrSelfPermission(
22441                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22442        mMoveCallbacks.register(callback);
22443    }
22444
22445    @Override
22446    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22447        mContext.enforceCallingOrSelfPermission(
22448                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22449        mMoveCallbacks.unregister(callback);
22450    }
22451
22452    @Override
22453    public boolean setInstallLocation(int loc) {
22454        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22455                null);
22456        if (getInstallLocation() == loc) {
22457            return true;
22458        }
22459        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22460                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22461            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22462                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22463            return true;
22464        }
22465        return false;
22466   }
22467
22468    @Override
22469    public int getInstallLocation() {
22470        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22471                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22472                PackageHelper.APP_INSTALL_AUTO);
22473    }
22474
22475    /** Called by UserManagerService */
22476    void cleanUpUser(UserManagerService userManager, int userHandle) {
22477        synchronized (mPackages) {
22478            mDirtyUsers.remove(userHandle);
22479            mUserNeedsBadging.delete(userHandle);
22480            mSettings.removeUserLPw(userHandle);
22481            mPendingBroadcasts.remove(userHandle);
22482            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22483            removeUnusedPackagesLPw(userManager, userHandle);
22484        }
22485    }
22486
22487    /**
22488     * We're removing userHandle and would like to remove any downloaded packages
22489     * that are no longer in use by any other user.
22490     * @param userHandle the user being removed
22491     */
22492    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22493        final boolean DEBUG_CLEAN_APKS = false;
22494        int [] users = userManager.getUserIds();
22495        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22496        while (psit.hasNext()) {
22497            PackageSetting ps = psit.next();
22498            if (ps.pkg == null) {
22499                continue;
22500            }
22501            final String packageName = ps.pkg.packageName;
22502            // Skip over if system app
22503            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22504                continue;
22505            }
22506            if (DEBUG_CLEAN_APKS) {
22507                Slog.i(TAG, "Checking package " + packageName);
22508            }
22509            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22510            if (keep) {
22511                if (DEBUG_CLEAN_APKS) {
22512                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22513                }
22514            } else {
22515                for (int i = 0; i < users.length; i++) {
22516                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22517                        keep = true;
22518                        if (DEBUG_CLEAN_APKS) {
22519                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22520                                    + users[i]);
22521                        }
22522                        break;
22523                    }
22524                }
22525            }
22526            if (!keep) {
22527                if (DEBUG_CLEAN_APKS) {
22528                    Slog.i(TAG, "  Removing package " + packageName);
22529                }
22530                mHandler.post(new Runnable() {
22531                    public void run() {
22532                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22533                                userHandle, 0);
22534                    } //end run
22535                });
22536            }
22537        }
22538    }
22539
22540    /** Called by UserManagerService */
22541    void createNewUser(int userId, String[] disallowedPackages) {
22542        synchronized (mInstallLock) {
22543            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22544        }
22545        synchronized (mPackages) {
22546            scheduleWritePackageRestrictionsLocked(userId);
22547            scheduleWritePackageListLocked(userId);
22548            applyFactoryDefaultBrowserLPw(userId);
22549            primeDomainVerificationsLPw(userId);
22550        }
22551    }
22552
22553    void onNewUserCreated(final int userId) {
22554        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22555        // If permission review for legacy apps is required, we represent
22556        // dagerous permissions for such apps as always granted runtime
22557        // permissions to keep per user flag state whether review is needed.
22558        // Hence, if a new user is added we have to propagate dangerous
22559        // permission grants for these legacy apps.
22560        if (mPermissionReviewRequired) {
22561            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22562                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22563        }
22564    }
22565
22566    @Override
22567    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22568        mContext.enforceCallingOrSelfPermission(
22569                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22570                "Only package verification agents can read the verifier device identity");
22571
22572        synchronized (mPackages) {
22573            return mSettings.getVerifierDeviceIdentityLPw();
22574        }
22575    }
22576
22577    @Override
22578    public void setPermissionEnforced(String permission, boolean enforced) {
22579        // TODO: Now that we no longer change GID for storage, this should to away.
22580        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22581                "setPermissionEnforced");
22582        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22583            synchronized (mPackages) {
22584                if (mSettings.mReadExternalStorageEnforced == null
22585                        || mSettings.mReadExternalStorageEnforced != enforced) {
22586                    mSettings.mReadExternalStorageEnforced = enforced;
22587                    mSettings.writeLPr();
22588                }
22589            }
22590            // kill any non-foreground processes so we restart them and
22591            // grant/revoke the GID.
22592            final IActivityManager am = ActivityManager.getService();
22593            if (am != null) {
22594                final long token = Binder.clearCallingIdentity();
22595                try {
22596                    am.killProcessesBelowForeground("setPermissionEnforcement");
22597                } catch (RemoteException e) {
22598                } finally {
22599                    Binder.restoreCallingIdentity(token);
22600                }
22601            }
22602        } else {
22603            throw new IllegalArgumentException("No selective enforcement for " + permission);
22604        }
22605    }
22606
22607    @Override
22608    @Deprecated
22609    public boolean isPermissionEnforced(String permission) {
22610        return true;
22611    }
22612
22613    @Override
22614    public boolean isStorageLow() {
22615        final long token = Binder.clearCallingIdentity();
22616        try {
22617            final DeviceStorageMonitorInternal
22618                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22619            if (dsm != null) {
22620                return dsm.isMemoryLow();
22621            } else {
22622                return false;
22623            }
22624        } finally {
22625            Binder.restoreCallingIdentity(token);
22626        }
22627    }
22628
22629    @Override
22630    public IPackageInstaller getPackageInstaller() {
22631        return mInstallerService;
22632    }
22633
22634    private boolean userNeedsBadging(int userId) {
22635        int index = mUserNeedsBadging.indexOfKey(userId);
22636        if (index < 0) {
22637            final UserInfo userInfo;
22638            final long token = Binder.clearCallingIdentity();
22639            try {
22640                userInfo = sUserManager.getUserInfo(userId);
22641            } finally {
22642                Binder.restoreCallingIdentity(token);
22643            }
22644            final boolean b;
22645            if (userInfo != null && userInfo.isManagedProfile()) {
22646                b = true;
22647            } else {
22648                b = false;
22649            }
22650            mUserNeedsBadging.put(userId, b);
22651            return b;
22652        }
22653        return mUserNeedsBadging.valueAt(index);
22654    }
22655
22656    @Override
22657    public KeySet getKeySetByAlias(String packageName, String alias) {
22658        if (packageName == null || alias == null) {
22659            return null;
22660        }
22661        synchronized(mPackages) {
22662            final PackageParser.Package pkg = mPackages.get(packageName);
22663            if (pkg == null) {
22664                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22665                throw new IllegalArgumentException("Unknown package: " + packageName);
22666            }
22667            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22668            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22669        }
22670    }
22671
22672    @Override
22673    public KeySet getSigningKeySet(String packageName) {
22674        if (packageName == null) {
22675            return null;
22676        }
22677        synchronized(mPackages) {
22678            final PackageParser.Package pkg = mPackages.get(packageName);
22679            if (pkg == null) {
22680                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22681                throw new IllegalArgumentException("Unknown package: " + packageName);
22682            }
22683            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22684                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22685                throw new SecurityException("May not access signing KeySet of other apps.");
22686            }
22687            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22688            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22689        }
22690    }
22691
22692    @Override
22693    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22694        if (packageName == null || ks == null) {
22695            return false;
22696        }
22697        synchronized(mPackages) {
22698            final PackageParser.Package pkg = mPackages.get(packageName);
22699            if (pkg == null) {
22700                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22701                throw new IllegalArgumentException("Unknown package: " + packageName);
22702            }
22703            IBinder ksh = ks.getToken();
22704            if (ksh instanceof KeySetHandle) {
22705                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22706                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22707            }
22708            return false;
22709        }
22710    }
22711
22712    @Override
22713    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22714        if (packageName == null || ks == null) {
22715            return false;
22716        }
22717        synchronized(mPackages) {
22718            final PackageParser.Package pkg = mPackages.get(packageName);
22719            if (pkg == null) {
22720                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22721                throw new IllegalArgumentException("Unknown package: " + packageName);
22722            }
22723            IBinder ksh = ks.getToken();
22724            if (ksh instanceof KeySetHandle) {
22725                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22726                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22727            }
22728            return false;
22729        }
22730    }
22731
22732    private void deletePackageIfUnusedLPr(final String packageName) {
22733        PackageSetting ps = mSettings.mPackages.get(packageName);
22734        if (ps == null) {
22735            return;
22736        }
22737        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22738            // TODO Implement atomic delete if package is unused
22739            // It is currently possible that the package will be deleted even if it is installed
22740            // after this method returns.
22741            mHandler.post(new Runnable() {
22742                public void run() {
22743                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22744                            0, PackageManager.DELETE_ALL_USERS);
22745                }
22746            });
22747        }
22748    }
22749
22750    /**
22751     * Check and throw if the given before/after packages would be considered a
22752     * downgrade.
22753     */
22754    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22755            throws PackageManagerException {
22756        if (after.versionCode < before.mVersionCode) {
22757            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22758                    "Update version code " + after.versionCode + " is older than current "
22759                    + before.mVersionCode);
22760        } else if (after.versionCode == before.mVersionCode) {
22761            if (after.baseRevisionCode < before.baseRevisionCode) {
22762                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22763                        "Update base revision code " + after.baseRevisionCode
22764                        + " is older than current " + before.baseRevisionCode);
22765            }
22766
22767            if (!ArrayUtils.isEmpty(after.splitNames)) {
22768                for (int i = 0; i < after.splitNames.length; i++) {
22769                    final String splitName = after.splitNames[i];
22770                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22771                    if (j != -1) {
22772                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22773                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22774                                    "Update split " + splitName + " revision code "
22775                                    + after.splitRevisionCodes[i] + " is older than current "
22776                                    + before.splitRevisionCodes[j]);
22777                        }
22778                    }
22779                }
22780            }
22781        }
22782    }
22783
22784    private static class MoveCallbacks extends Handler {
22785        private static final int MSG_CREATED = 1;
22786        private static final int MSG_STATUS_CHANGED = 2;
22787
22788        private final RemoteCallbackList<IPackageMoveObserver>
22789                mCallbacks = new RemoteCallbackList<>();
22790
22791        private final SparseIntArray mLastStatus = new SparseIntArray();
22792
22793        public MoveCallbacks(Looper looper) {
22794            super(looper);
22795        }
22796
22797        public void register(IPackageMoveObserver callback) {
22798            mCallbacks.register(callback);
22799        }
22800
22801        public void unregister(IPackageMoveObserver callback) {
22802            mCallbacks.unregister(callback);
22803        }
22804
22805        @Override
22806        public void handleMessage(Message msg) {
22807            final SomeArgs args = (SomeArgs) msg.obj;
22808            final int n = mCallbacks.beginBroadcast();
22809            for (int i = 0; i < n; i++) {
22810                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22811                try {
22812                    invokeCallback(callback, msg.what, args);
22813                } catch (RemoteException ignored) {
22814                }
22815            }
22816            mCallbacks.finishBroadcast();
22817            args.recycle();
22818        }
22819
22820        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22821                throws RemoteException {
22822            switch (what) {
22823                case MSG_CREATED: {
22824                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22825                    break;
22826                }
22827                case MSG_STATUS_CHANGED: {
22828                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22829                    break;
22830                }
22831            }
22832        }
22833
22834        private void notifyCreated(int moveId, Bundle extras) {
22835            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22836
22837            final SomeArgs args = SomeArgs.obtain();
22838            args.argi1 = moveId;
22839            args.arg2 = extras;
22840            obtainMessage(MSG_CREATED, args).sendToTarget();
22841        }
22842
22843        private void notifyStatusChanged(int moveId, int status) {
22844            notifyStatusChanged(moveId, status, -1);
22845        }
22846
22847        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22848            Slog.v(TAG, "Move " + moveId + " status " + status);
22849
22850            final SomeArgs args = SomeArgs.obtain();
22851            args.argi1 = moveId;
22852            args.argi2 = status;
22853            args.arg3 = estMillis;
22854            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22855
22856            synchronized (mLastStatus) {
22857                mLastStatus.put(moveId, status);
22858            }
22859        }
22860    }
22861
22862    private final static class OnPermissionChangeListeners extends Handler {
22863        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22864
22865        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22866                new RemoteCallbackList<>();
22867
22868        public OnPermissionChangeListeners(Looper looper) {
22869            super(looper);
22870        }
22871
22872        @Override
22873        public void handleMessage(Message msg) {
22874            switch (msg.what) {
22875                case MSG_ON_PERMISSIONS_CHANGED: {
22876                    final int uid = msg.arg1;
22877                    handleOnPermissionsChanged(uid);
22878                } break;
22879            }
22880        }
22881
22882        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22883            mPermissionListeners.register(listener);
22884
22885        }
22886
22887        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22888            mPermissionListeners.unregister(listener);
22889        }
22890
22891        public void onPermissionsChanged(int uid) {
22892            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22893                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22894            }
22895        }
22896
22897        private void handleOnPermissionsChanged(int uid) {
22898            final int count = mPermissionListeners.beginBroadcast();
22899            try {
22900                for (int i = 0; i < count; i++) {
22901                    IOnPermissionsChangeListener callback = mPermissionListeners
22902                            .getBroadcastItem(i);
22903                    try {
22904                        callback.onPermissionsChanged(uid);
22905                    } catch (RemoteException e) {
22906                        Log.e(TAG, "Permission listener is dead", e);
22907                    }
22908                }
22909            } finally {
22910                mPermissionListeners.finishBroadcast();
22911            }
22912        }
22913    }
22914
22915    private class PackageManagerInternalImpl extends PackageManagerInternal {
22916        @Override
22917        public void setLocationPackagesProvider(PackagesProvider provider) {
22918            synchronized (mPackages) {
22919                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22920            }
22921        }
22922
22923        @Override
22924        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22925            synchronized (mPackages) {
22926                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22927            }
22928        }
22929
22930        @Override
22931        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22932            synchronized (mPackages) {
22933                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22934            }
22935        }
22936
22937        @Override
22938        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22939            synchronized (mPackages) {
22940                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22941            }
22942        }
22943
22944        @Override
22945        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22946            synchronized (mPackages) {
22947                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22948            }
22949        }
22950
22951        @Override
22952        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22953            synchronized (mPackages) {
22954                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22955            }
22956        }
22957
22958        @Override
22959        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22960            synchronized (mPackages) {
22961                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22962                        packageName, userId);
22963            }
22964        }
22965
22966        @Override
22967        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22968            synchronized (mPackages) {
22969                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22970                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22971                        packageName, userId);
22972            }
22973        }
22974
22975        @Override
22976        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22977            synchronized (mPackages) {
22978                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22979                        packageName, userId);
22980            }
22981        }
22982
22983        @Override
22984        public void setKeepUninstalledPackages(final List<String> packageList) {
22985            Preconditions.checkNotNull(packageList);
22986            List<String> removedFromList = null;
22987            synchronized (mPackages) {
22988                if (mKeepUninstalledPackages != null) {
22989                    final int packagesCount = mKeepUninstalledPackages.size();
22990                    for (int i = 0; i < packagesCount; i++) {
22991                        String oldPackage = mKeepUninstalledPackages.get(i);
22992                        if (packageList != null && packageList.contains(oldPackage)) {
22993                            continue;
22994                        }
22995                        if (removedFromList == null) {
22996                            removedFromList = new ArrayList<>();
22997                        }
22998                        removedFromList.add(oldPackage);
22999                    }
23000                }
23001                mKeepUninstalledPackages = new ArrayList<>(packageList);
23002                if (removedFromList != null) {
23003                    final int removedCount = removedFromList.size();
23004                    for (int i = 0; i < removedCount; i++) {
23005                        deletePackageIfUnusedLPr(removedFromList.get(i));
23006                    }
23007                }
23008            }
23009        }
23010
23011        @Override
23012        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23013            synchronized (mPackages) {
23014                // If we do not support permission review, done.
23015                if (!mPermissionReviewRequired) {
23016                    return false;
23017                }
23018
23019                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23020                if (packageSetting == null) {
23021                    return false;
23022                }
23023
23024                // Permission review applies only to apps not supporting the new permission model.
23025                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23026                    return false;
23027                }
23028
23029                // Legacy apps have the permission and get user consent on launch.
23030                PermissionsState permissionsState = packageSetting.getPermissionsState();
23031                return permissionsState.isPermissionReviewRequired(userId);
23032            }
23033        }
23034
23035        @Override
23036        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23037            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23038        }
23039
23040        @Override
23041        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23042                int userId) {
23043            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23044        }
23045
23046        @Override
23047        public void setDeviceAndProfileOwnerPackages(
23048                int deviceOwnerUserId, String deviceOwnerPackage,
23049                SparseArray<String> profileOwnerPackages) {
23050            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23051                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23052        }
23053
23054        @Override
23055        public boolean isPackageDataProtected(int userId, String packageName) {
23056            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23057        }
23058
23059        @Override
23060        public boolean isPackageEphemeral(int userId, String packageName) {
23061            synchronized (mPackages) {
23062                final PackageSetting ps = mSettings.mPackages.get(packageName);
23063                return ps != null ? ps.getInstantApp(userId) : false;
23064            }
23065        }
23066
23067        @Override
23068        public boolean wasPackageEverLaunched(String packageName, int userId) {
23069            synchronized (mPackages) {
23070                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23071            }
23072        }
23073
23074        @Override
23075        public void grantRuntimePermission(String packageName, String name, int userId,
23076                boolean overridePolicy) {
23077            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23078                    overridePolicy);
23079        }
23080
23081        @Override
23082        public void revokeRuntimePermission(String packageName, String name, int userId,
23083                boolean overridePolicy) {
23084            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23085                    overridePolicy);
23086        }
23087
23088        @Override
23089        public String getNameForUid(int uid) {
23090            return PackageManagerService.this.getNameForUid(uid);
23091        }
23092
23093        @Override
23094        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23095                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23096            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23097                    responseObj, origIntent, resolvedType, callingPackage, userId);
23098        }
23099
23100        @Override
23101        public void grantEphemeralAccess(int userId, Intent intent,
23102                int targetAppId, int ephemeralAppId) {
23103            synchronized (mPackages) {
23104                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23105                        targetAppId, ephemeralAppId);
23106            }
23107        }
23108
23109        @Override
23110        public void pruneInstantApps() {
23111            synchronized (mPackages) {
23112                mInstantAppRegistry.pruneInstantAppsLPw();
23113            }
23114        }
23115
23116        @Override
23117        public String getSetupWizardPackageName() {
23118            return mSetupWizardPackage;
23119        }
23120
23121        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23122            if (policy != null) {
23123                mExternalSourcesPolicy = policy;
23124            }
23125        }
23126
23127        @Override
23128        public boolean isPackagePersistent(String packageName) {
23129            synchronized (mPackages) {
23130                PackageParser.Package pkg = mPackages.get(packageName);
23131                return pkg != null
23132                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23133                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23134                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23135                        : false;
23136            }
23137        }
23138
23139        @Override
23140        public List<PackageInfo> getOverlayPackages(int userId) {
23141            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23142            synchronized (mPackages) {
23143                for (PackageParser.Package p : mPackages.values()) {
23144                    if (p.mOverlayTarget != null) {
23145                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23146                        if (pkg != null) {
23147                            overlayPackages.add(pkg);
23148                        }
23149                    }
23150                }
23151            }
23152            return overlayPackages;
23153        }
23154
23155        @Override
23156        public List<String> getTargetPackageNames(int userId) {
23157            List<String> targetPackages = new ArrayList<>();
23158            synchronized (mPackages) {
23159                for (PackageParser.Package p : mPackages.values()) {
23160                    if (p.mOverlayTarget == null) {
23161                        targetPackages.add(p.packageName);
23162                    }
23163                }
23164            }
23165            return targetPackages;
23166        }
23167
23168        @Override
23169        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23170                @Nullable List<String> overlayPackageNames) {
23171            synchronized (mPackages) {
23172                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23173                    Slog.e(TAG, "failed to find package " + targetPackageName);
23174                    return false;
23175                }
23176
23177                ArrayList<String> paths = null;
23178                if (overlayPackageNames != null) {
23179                    final int N = overlayPackageNames.size();
23180                    paths = new ArrayList<>(N);
23181                    for (int i = 0; i < N; i++) {
23182                        final String packageName = overlayPackageNames.get(i);
23183                        final PackageParser.Package pkg = mPackages.get(packageName);
23184                        if (pkg == null) {
23185                            Slog.e(TAG, "failed to find package " + packageName);
23186                            return false;
23187                        }
23188                        paths.add(pkg.baseCodePath);
23189                    }
23190                }
23191
23192                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23193                    mEnabledOverlayPaths.get(userId);
23194                if (userSpecificOverlays == null) {
23195                    userSpecificOverlays = new ArrayMap<>();
23196                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23197                }
23198
23199                if (paths != null && paths.size() > 0) {
23200                    userSpecificOverlays.put(targetPackageName, paths);
23201                } else {
23202                    userSpecificOverlays.remove(targetPackageName);
23203                }
23204                return true;
23205            }
23206        }
23207
23208        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23209                int flags, int userId) {
23210            return resolveIntentInternal(
23211                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23212        }
23213    }
23214
23215    @Override
23216    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23217        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23218        synchronized (mPackages) {
23219            final long identity = Binder.clearCallingIdentity();
23220            try {
23221                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23222                        packageNames, userId);
23223            } finally {
23224                Binder.restoreCallingIdentity(identity);
23225            }
23226        }
23227    }
23228
23229    @Override
23230    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23231        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23232        synchronized (mPackages) {
23233            final long identity = Binder.clearCallingIdentity();
23234            try {
23235                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23236                        packageNames, userId);
23237            } finally {
23238                Binder.restoreCallingIdentity(identity);
23239            }
23240        }
23241    }
23242
23243    private static void enforceSystemOrPhoneCaller(String tag) {
23244        int callingUid = Binder.getCallingUid();
23245        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23246            throw new SecurityException(
23247                    "Cannot call " + tag + " from UID " + callingUid);
23248        }
23249    }
23250
23251    boolean isHistoricalPackageUsageAvailable() {
23252        return mPackageUsage.isHistoricalPackageUsageAvailable();
23253    }
23254
23255    /**
23256     * Return a <b>copy</b> of the collection of packages known to the package manager.
23257     * @return A copy of the values of mPackages.
23258     */
23259    Collection<PackageParser.Package> getPackages() {
23260        synchronized (mPackages) {
23261            return new ArrayList<>(mPackages.values());
23262        }
23263    }
23264
23265    /**
23266     * Logs process start information (including base APK hash) to the security log.
23267     * @hide
23268     */
23269    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23270            String apkFile, int pid) {
23271        if (!SecurityLog.isLoggingEnabled()) {
23272            return;
23273        }
23274        Bundle data = new Bundle();
23275        data.putLong("startTimestamp", System.currentTimeMillis());
23276        data.putString("processName", processName);
23277        data.putInt("uid", uid);
23278        data.putString("seinfo", seinfo);
23279        data.putString("apkFile", apkFile);
23280        data.putInt("pid", pid);
23281        Message msg = mProcessLoggingHandler.obtainMessage(
23282                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23283        msg.setData(data);
23284        mProcessLoggingHandler.sendMessage(msg);
23285    }
23286
23287    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23288        return mCompilerStats.getPackageStats(pkgName);
23289    }
23290
23291    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23292        return getOrCreateCompilerPackageStats(pkg.packageName);
23293    }
23294
23295    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23296        return mCompilerStats.getOrCreatePackageStats(pkgName);
23297    }
23298
23299    public void deleteCompilerPackageStats(String pkgName) {
23300        mCompilerStats.deletePackageStats(pkgName);
23301    }
23302
23303    @Override
23304    public int getInstallReason(String packageName, int userId) {
23305        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23306                true /* requireFullPermission */, false /* checkShell */,
23307                "get install reason");
23308        synchronized (mPackages) {
23309            final PackageSetting ps = mSettings.mPackages.get(packageName);
23310            if (ps != null) {
23311                return ps.getInstallReason(userId);
23312            }
23313        }
23314        return PackageManager.INSTALL_REASON_UNKNOWN;
23315    }
23316
23317    @Override
23318    public boolean canRequestPackageInstalls(String packageName, int userId) {
23319        int callingUid = Binder.getCallingUid();
23320        int uid = getPackageUid(packageName, 0, userId);
23321        if (callingUid != uid && callingUid != Process.ROOT_UID
23322                && callingUid != Process.SYSTEM_UID) {
23323            throw new SecurityException(
23324                    "Caller uid " + callingUid + " does not own package " + packageName);
23325        }
23326        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23327        if (info == null) {
23328            return false;
23329        }
23330        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23331            throw new UnsupportedOperationException(
23332                    "Operation only supported on apps targeting Android O or higher");
23333        }
23334        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23335        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23336        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23337            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23338        }
23339        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23340            return false;
23341        }
23342        if (mExternalSourcesPolicy != null) {
23343            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23344            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23345                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23346            }
23347        }
23348        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23349    }
23350
23351    @Override
23352    public ComponentName getInstantAppResolverSettingsComponent() {
23353        return mInstantAppResolverSettingsComponent;
23354    }
23355}
23356