PackageManagerService.java revision 64814139ada90b09ce85c3c71ffd6df99133e5e5
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.BackgroundDexOptJobService;
264import com.android.server.DeviceIdleController;
265import com.android.server.EventLogTags;
266import com.android.server.FgThread;
267import com.android.server.IntentResolver;
268import com.android.server.LocalServices;
269import com.android.server.LockGuard;
270import com.android.server.ServiceThread;
271import com.android.server.SystemConfig;
272import com.android.server.SystemServerInitThreadPool;
273import com.android.server.Watchdog;
274import com.android.server.net.NetworkPolicyManagerInternal;
275import com.android.server.pm.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
300import java.io.FileNotFoundException;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
398    private static final boolean DISABLE_EPHEMERAL_APPS = false;
399    private static final boolean HIDE_EPHEMERAL_APIS = false;
400
401    private static final boolean ENABLE_FREE_CACHE_V2 =
402            SystemProperties.getBoolean("fw.free_cache_v2", true);
403
404    private static final int RADIO_UID = Process.PHONE_UID;
405    private static final int LOG_UID = Process.LOG_UID;
406    private static final int NFC_UID = Process.NFC_UID;
407    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
408    private static final int SHELL_UID = Process.SHELL_UID;
409
410    // Cap the size of permission trees that 3rd party apps can define
411    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
412
413    // Suffix used during package installation when copying/moving
414    // package apks to install directory.
415    private static final String INSTALL_PACKAGE_SUFFIX = "-";
416
417    static final int SCAN_NO_DEX = 1<<1;
418    static final int SCAN_FORCE_DEX = 1<<2;
419    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
420    static final int SCAN_NEW_INSTALL = 1<<4;
421    static final int SCAN_UPDATE_TIME = 1<<5;
422    static final int SCAN_BOOTING = 1<<6;
423    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
424    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
425    static final int SCAN_REPLACING = 1<<9;
426    static final int SCAN_REQUIRE_KNOWN = 1<<10;
427    static final int SCAN_MOVE = 1<<11;
428    static final int SCAN_INITIAL = 1<<12;
429    static final int SCAN_CHECK_ONLY = 1<<13;
430    static final int SCAN_DONT_KILL_APP = 1<<14;
431    static final int SCAN_IGNORE_FROZEN = 1<<15;
432    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
433    static final int SCAN_AS_INSTANT_APP = 1<<17;
434    static final int SCAN_AS_FULL_APP = 1<<18;
435    /** Should not be with the scan flags */
436    static final int FLAGS_REMOVE_CHATTY = 1<<31;
437
438    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
439
440    private static final int[] EMPTY_INT_ARRAY = new int[0];
441
442    /**
443     * Timeout (in milliseconds) after which the watchdog should declare that
444     * our handler thread is wedged.  The usual default for such things is one
445     * minute but we sometimes do very lengthy I/O operations on this thread,
446     * such as installing multi-gigabyte applications, so ours needs to be longer.
447     */
448    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
449
450    /**
451     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
452     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
453     * settings entry if available, otherwise we use the hardcoded default.  If it's been
454     * more than this long since the last fstrim, we force one during the boot sequence.
455     *
456     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
457     * one gets run at the next available charging+idle time.  This final mandatory
458     * no-fstrim check kicks in only of the other scheduling criteria is never met.
459     */
460    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
461
462    /**
463     * Whether verification is enabled by default.
464     */
465    private static final boolean DEFAULT_VERIFY_ENABLE = true;
466
467    /**
468     * The default maximum time to wait for the verification agent to return in
469     * milliseconds.
470     */
471    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
472
473    /**
474     * The default response for package verification timeout.
475     *
476     * This can be either PackageManager.VERIFICATION_ALLOW or
477     * PackageManager.VERIFICATION_REJECT.
478     */
479    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
480
481    static final String PLATFORM_PACKAGE_NAME = "android";
482
483    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
484
485    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
486            DEFAULT_CONTAINER_PACKAGE,
487            "com.android.defcontainer.DefaultContainerService");
488
489    private static final String KILL_APP_REASON_GIDS_CHANGED =
490            "permission grant or revoke changed gids";
491
492    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
493            "permissions revoked";
494
495    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
496
497    private static final String PACKAGE_SCHEME = "package";
498
499    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
500
501    /** Permission grant: not grant the permission. */
502    private static final int GRANT_DENIED = 1;
503
504    /** Permission grant: grant the permission as an install permission. */
505    private static final int GRANT_INSTALL = 2;
506
507    /** Permission grant: grant the permission as a runtime one. */
508    private static final int GRANT_RUNTIME = 3;
509
510    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
511    private static final int GRANT_UPGRADE = 4;
512
513    /** Canonical intent used to identify what counts as a "web browser" app */
514    private static final Intent sBrowserIntent;
515    static {
516        sBrowserIntent = new Intent();
517        sBrowserIntent.setAction(Intent.ACTION_VIEW);
518        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
519        sBrowserIntent.setData(Uri.parse("http:"));
520    }
521
522    /**
523     * The set of all protected actions [i.e. those actions for which a high priority
524     * intent filter is disallowed].
525     */
526    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
527    static {
528        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
531        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
532    }
533
534    // Compilation reasons.
535    public static final int REASON_FIRST_BOOT = 0;
536    public static final int REASON_BOOT = 1;
537    public static final int REASON_INSTALL = 2;
538    public static final int REASON_BACKGROUND_DEXOPT = 3;
539    public static final int REASON_AB_OTA = 4;
540    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
541    public static final int REASON_SHARED_APK = 6;
542    public static final int REASON_FORCED_DEXOPT = 7;
543    public static final int REASON_CORE_APP = 8;
544
545    public static final int REASON_LAST = REASON_CORE_APP;
546
547    /** All dangerous permission names in the same order as the events in MetricsEvent */
548    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
549            Manifest.permission.READ_CALENDAR,
550            Manifest.permission.WRITE_CALENDAR,
551            Manifest.permission.CAMERA,
552            Manifest.permission.READ_CONTACTS,
553            Manifest.permission.WRITE_CONTACTS,
554            Manifest.permission.GET_ACCOUNTS,
555            Manifest.permission.ACCESS_FINE_LOCATION,
556            Manifest.permission.ACCESS_COARSE_LOCATION,
557            Manifest.permission.RECORD_AUDIO,
558            Manifest.permission.READ_PHONE_STATE,
559            Manifest.permission.CALL_PHONE,
560            Manifest.permission.READ_CALL_LOG,
561            Manifest.permission.WRITE_CALL_LOG,
562            Manifest.permission.ADD_VOICEMAIL,
563            Manifest.permission.USE_SIP,
564            Manifest.permission.PROCESS_OUTGOING_CALLS,
565            Manifest.permission.READ_CELL_BROADCASTS,
566            Manifest.permission.BODY_SENSORS,
567            Manifest.permission.SEND_SMS,
568            Manifest.permission.RECEIVE_SMS,
569            Manifest.permission.READ_SMS,
570            Manifest.permission.RECEIVE_WAP_PUSH,
571            Manifest.permission.RECEIVE_MMS,
572            Manifest.permission.READ_EXTERNAL_STORAGE,
573            Manifest.permission.WRITE_EXTERNAL_STORAGE,
574            Manifest.permission.READ_PHONE_NUMBER,
575            Manifest.permission.ANSWER_PHONE_CALLS);
576
577
578    /**
579     * Version number for the package parser cache. Increment this whenever the format or
580     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
581     */
582    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
583
584    /**
585     * Whether the package parser cache is enabled.
586     */
587    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
588
589    final ServiceThread mHandlerThread;
590
591    final PackageHandler mHandler;
592
593    private final ProcessLoggingHandler mProcessLoggingHandler;
594
595    /**
596     * Messages for {@link #mHandler} that need to wait for system ready before
597     * being dispatched.
598     */
599    private ArrayList<Message> mPostSystemReadyMessages;
600
601    final int mSdkVersion = Build.VERSION.SDK_INT;
602
603    final Context mContext;
604    final boolean mFactoryTest;
605    final boolean mOnlyCore;
606    final DisplayMetrics mMetrics;
607    final int mDefParseFlags;
608    final String[] mSeparateProcesses;
609    final boolean mIsUpgrade;
610    final boolean mIsPreNUpgrade;
611    final boolean mIsPreNMR1Upgrade;
612
613    @GuardedBy("mPackages")
614    private boolean mDexOptDialogShown;
615
616    /** The location for ASEC container files on internal storage. */
617    final String mAsecInternalPath;
618
619    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
620    // LOCK HELD.  Can be called with mInstallLock held.
621    @GuardedBy("mInstallLock")
622    final Installer mInstaller;
623
624    /** Directory where installed third-party apps stored */
625    final File mAppInstallDir;
626
627    /**
628     * Directory to which applications installed internally have their
629     * 32 bit native libraries copied.
630     */
631    private File mAppLib32InstallDir;
632
633    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
634    // apps.
635    final File mDrmAppPrivateInstallDir;
636
637    // ----------------------------------------------------------------
638
639    // Lock for state used when installing and doing other long running
640    // operations.  Methods that must be called with this lock held have
641    // the suffix "LI".
642    final Object mInstallLock = new Object();
643
644    // ----------------------------------------------------------------
645
646    // Keys are String (package name), values are Package.  This also serves
647    // as the lock for the global state.  Methods that must be called with
648    // this lock held have the prefix "LP".
649    @GuardedBy("mPackages")
650    final ArrayMap<String, PackageParser.Package> mPackages =
651            new ArrayMap<String, PackageParser.Package>();
652
653    final ArrayMap<String, Set<String>> mKnownCodebase =
654            new ArrayMap<String, Set<String>>();
655
656    // List of APK paths to load for each user and package. This data is never
657    // persisted by the package manager. Instead, the overlay manager will
658    // ensure the data is up-to-date in runtime.
659    @GuardedBy("mPackages")
660    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
661        new SparseArray<ArrayMap<String, ArrayList<String>>>();
662
663    /**
664     * Tracks new system packages [received in an OTA] that we expect to
665     * find updated user-installed versions. Keys are package name, values
666     * are package location.
667     */
668    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
669    /**
670     * Tracks high priority intent filters for protected actions. During boot, certain
671     * filter actions are protected and should never be allowed to have a high priority
672     * intent filter for them. However, there is one, and only one exception -- the
673     * setup wizard. It must be able to define a high priority intent filter for these
674     * actions to ensure there are no escapes from the wizard. We need to delay processing
675     * of these during boot as we need to look at all of the system packages in order
676     * to know which component is the setup wizard.
677     */
678    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
679    /**
680     * Whether or not processing protected filters should be deferred.
681     */
682    private boolean mDeferProtectedFilters = true;
683
684    /**
685     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
686     */
687    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
688    /**
689     * Whether or not system app permissions should be promoted from install to runtime.
690     */
691    boolean mPromoteSystemApps;
692
693    @GuardedBy("mPackages")
694    final Settings mSettings;
695
696    /**
697     * Set of package names that are currently "frozen", which means active
698     * surgery is being done on the code/data for that package. The platform
699     * will refuse to launch frozen packages to avoid race conditions.
700     *
701     * @see PackageFreezer
702     */
703    @GuardedBy("mPackages")
704    final ArraySet<String> mFrozenPackages = new ArraySet<>();
705
706    final ProtectedPackages mProtectedPackages;
707
708    boolean mFirstBoot;
709
710    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
711
712    // System configuration read by SystemConfig.
713    final int[] mGlobalGids;
714    final SparseArray<ArraySet<String>> mSystemPermissions;
715    @GuardedBy("mAvailableFeatures")
716    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
717
718    // If mac_permissions.xml was found for seinfo labeling.
719    boolean mFoundPolicyFile;
720
721    private final InstantAppRegistry mInstantAppRegistry;
722
723    @GuardedBy("mPackages")
724    int mChangedPackagesSequenceNumber;
725    /**
726     * List of changed [installed, removed or updated] packages.
727     * mapping from user id -> sequence number -> package name
728     */
729    @GuardedBy("mPackages")
730    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
731    /**
732     * The sequence number of the last change to a package.
733     * mapping from user id -> package name -> sequence number
734     */
735    @GuardedBy("mPackages")
736    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
737
738    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
739        @Override public boolean hasFeature(String feature) {
740            return PackageManagerService.this.hasSystemFeature(feature, 0);
741        }
742    };
743
744    public static final class SharedLibraryEntry {
745        public final String path;
746        public final String apk;
747        public final SharedLibraryInfo info;
748
749        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
750                String declaringPackageName, int declaringPackageVersionCode) {
751            path = _path;
752            apk = _apk;
753            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
754                    declaringPackageName, declaringPackageVersionCode), null);
755        }
756    }
757
758    // Currently known shared libraries.
759    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
760    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
761            new ArrayMap<>();
762
763    // All available activities, for your resolving pleasure.
764    final ActivityIntentResolver mActivities =
765            new ActivityIntentResolver();
766
767    // All available receivers, for your resolving pleasure.
768    final ActivityIntentResolver mReceivers =
769            new ActivityIntentResolver();
770
771    // All available services, for your resolving pleasure.
772    final ServiceIntentResolver mServices = new ServiceIntentResolver();
773
774    // All available providers, for your resolving pleasure.
775    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
776
777    // Mapping from provider base names (first directory in content URI codePath)
778    // to the provider information.
779    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
780            new ArrayMap<String, PackageParser.Provider>();
781
782    // Mapping from instrumentation class names to info about them.
783    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
784            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
785
786    // Mapping from permission names to info about them.
787    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
788            new ArrayMap<String, PackageParser.PermissionGroup>();
789
790    // Packages whose data we have transfered into another package, thus
791    // should no longer exist.
792    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
793
794    // Broadcast actions that are only available to the system.
795    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
796
797    /** List of packages waiting for verification. */
798    final SparseArray<PackageVerificationState> mPendingVerification
799            = new SparseArray<PackageVerificationState>();
800
801    /** Set of packages associated with each app op permission. */
802    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
803
804    final PackageInstallerService mInstallerService;
805
806    private final PackageDexOptimizer mPackageDexOptimizer;
807    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
808    // is used by other apps).
809    private final DexManager mDexManager;
810
811    private AtomicInteger mNextMoveId = new AtomicInteger();
812    private final MoveCallbacks mMoveCallbacks;
813
814    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
815
816    // Cache of users who need badging.
817    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
818
819    /** Token for keys in mPendingVerification. */
820    private int mPendingVerificationToken = 0;
821
822    volatile boolean mSystemReady;
823    volatile boolean mSafeMode;
824    volatile boolean mHasSystemUidErrors;
825
826    ApplicationInfo mAndroidApplication;
827    final ActivityInfo mResolveActivity = new ActivityInfo();
828    final ResolveInfo mResolveInfo = new ResolveInfo();
829    ComponentName mResolveComponentName;
830    PackageParser.Package mPlatformPackage;
831    ComponentName mCustomResolverComponentName;
832
833    boolean mResolverReplaced = false;
834
835    private final @Nullable ComponentName mIntentFilterVerifierComponent;
836    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
837
838    private int mIntentFilterVerificationToken = 0;
839
840    /** The service connection to the ephemeral resolver */
841    final EphemeralResolverConnection mInstantAppResolverConnection;
842
843    /** Component used to install ephemeral applications */
844    ComponentName mInstantAppInstallerComponent;
845    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
846    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
847
848    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
849            = new SparseArray<IntentFilterVerificationState>();
850
851    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
852
853    // List of packages names to keep cached, even if they are uninstalled for all users
854    private List<String> mKeepUninstalledPackages;
855
856    private UserManagerInternal mUserManagerInternal;
857
858    private DeviceIdleController.LocalService mDeviceIdleController;
859
860    private File mCacheDir;
861
862    private ArraySet<String> mPrivappPermissionsViolations;
863
864    private Future<?> mPrepareAppDataFuture;
865
866    private static class IFVerificationParams {
867        PackageParser.Package pkg;
868        boolean replacing;
869        int userId;
870        int verifierUid;
871
872        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
873                int _userId, int _verifierUid) {
874            pkg = _pkg;
875            replacing = _replacing;
876            userId = _userId;
877            replacing = _replacing;
878            verifierUid = _verifierUid;
879        }
880    }
881
882    private interface IntentFilterVerifier<T extends IntentFilter> {
883        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
884                                               T filter, String packageName);
885        void startVerifications(int userId);
886        void receiveVerificationResponse(int verificationId);
887    }
888
889    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
890        private Context mContext;
891        private ComponentName mIntentFilterVerifierComponent;
892        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
893
894        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
895            mContext = context;
896            mIntentFilterVerifierComponent = verifierComponent;
897        }
898
899        private String getDefaultScheme() {
900            return IntentFilter.SCHEME_HTTPS;
901        }
902
903        @Override
904        public void startVerifications(int userId) {
905            // Launch verifications requests
906            int count = mCurrentIntentFilterVerifications.size();
907            for (int n=0; n<count; n++) {
908                int verificationId = mCurrentIntentFilterVerifications.get(n);
909                final IntentFilterVerificationState ivs =
910                        mIntentFilterVerificationStates.get(verificationId);
911
912                String packageName = ivs.getPackageName();
913
914                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
915                final int filterCount = filters.size();
916                ArraySet<String> domainsSet = new ArraySet<>();
917                for (int m=0; m<filterCount; m++) {
918                    PackageParser.ActivityIntentInfo filter = filters.get(m);
919                    domainsSet.addAll(filter.getHostsList());
920                }
921                synchronized (mPackages) {
922                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
923                            packageName, domainsSet) != null) {
924                        scheduleWriteSettingsLocked();
925                    }
926                }
927                sendVerificationRequest(userId, verificationId, ivs);
928            }
929            mCurrentIntentFilterVerifications.clear();
930        }
931
932        private void sendVerificationRequest(int userId, int verificationId,
933                IntentFilterVerificationState ivs) {
934
935            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
936            verificationIntent.putExtra(
937                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
938                    verificationId);
939            verificationIntent.putExtra(
940                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
941                    getDefaultScheme());
942            verificationIntent.putExtra(
943                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
944                    ivs.getHostsString());
945            verificationIntent.putExtra(
946                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
947                    ivs.getPackageName());
948            verificationIntent.setComponent(mIntentFilterVerifierComponent);
949            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
950
951            UserHandle user = new UserHandle(userId);
952            mContext.sendBroadcastAsUser(verificationIntent, user);
953            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
954                    "Sending IntentFilter verification broadcast");
955        }
956
957        public void receiveVerificationResponse(int verificationId) {
958            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
959
960            final boolean verified = ivs.isVerified();
961
962            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
963            final int count = filters.size();
964            if (DEBUG_DOMAIN_VERIFICATION) {
965                Slog.i(TAG, "Received verification response " + verificationId
966                        + " for " + count + " filters, verified=" + verified);
967            }
968            for (int n=0; n<count; n++) {
969                PackageParser.ActivityIntentInfo filter = filters.get(n);
970                filter.setVerified(verified);
971
972                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
973                        + " verified with result:" + verified + " and hosts:"
974                        + ivs.getHostsString());
975            }
976
977            mIntentFilterVerificationStates.remove(verificationId);
978
979            final String packageName = ivs.getPackageName();
980            IntentFilterVerificationInfo ivi = null;
981
982            synchronized (mPackages) {
983                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
984            }
985            if (ivi == null) {
986                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
987                        + verificationId + " packageName:" + packageName);
988                return;
989            }
990            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
991                    "Updating IntentFilterVerificationInfo for package " + packageName
992                            +" verificationId:" + verificationId);
993
994            synchronized (mPackages) {
995                if (verified) {
996                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
997                } else {
998                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
999                }
1000                scheduleWriteSettingsLocked();
1001
1002                final int userId = ivs.getUserId();
1003                if (userId != UserHandle.USER_ALL) {
1004                    final int userStatus =
1005                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1006
1007                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1008                    boolean needUpdate = false;
1009
1010                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1011                    // already been set by the User thru the Disambiguation dialog
1012                    switch (userStatus) {
1013                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1014                            if (verified) {
1015                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1016                            } else {
1017                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1018                            }
1019                            needUpdate = true;
1020                            break;
1021
1022                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1023                            if (verified) {
1024                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1025                                needUpdate = true;
1026                            }
1027                            break;
1028
1029                        default:
1030                            // Nothing to do
1031                    }
1032
1033                    if (needUpdate) {
1034                        mSettings.updateIntentFilterVerificationStatusLPw(
1035                                packageName, updatedStatus, userId);
1036                        scheduleWritePackageRestrictionsLocked(userId);
1037                    }
1038                }
1039            }
1040        }
1041
1042        @Override
1043        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1044                    ActivityIntentInfo filter, String packageName) {
1045            if (!hasValidDomains(filter)) {
1046                return false;
1047            }
1048            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1049            if (ivs == null) {
1050                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1051                        packageName);
1052            }
1053            if (DEBUG_DOMAIN_VERIFICATION) {
1054                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1055            }
1056            ivs.addFilter(filter);
1057            return true;
1058        }
1059
1060        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1061                int userId, int verificationId, String packageName) {
1062            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1063                    verifierUid, userId, packageName);
1064            ivs.setPendingState();
1065            synchronized (mPackages) {
1066                mIntentFilterVerificationStates.append(verificationId, ivs);
1067                mCurrentIntentFilterVerifications.add(verificationId);
1068            }
1069            return ivs;
1070        }
1071    }
1072
1073    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1074        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1075                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1076                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1077    }
1078
1079    // Set of pending broadcasts for aggregating enable/disable of components.
1080    static class PendingPackageBroadcasts {
1081        // for each user id, a map of <package name -> components within that package>
1082        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1083
1084        public PendingPackageBroadcasts() {
1085            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1086        }
1087
1088        public ArrayList<String> get(int userId, String packageName) {
1089            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1090            return packages.get(packageName);
1091        }
1092
1093        public void put(int userId, String packageName, ArrayList<String> components) {
1094            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1095            packages.put(packageName, components);
1096        }
1097
1098        public void remove(int userId, String packageName) {
1099            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1100            if (packages != null) {
1101                packages.remove(packageName);
1102            }
1103        }
1104
1105        public void remove(int userId) {
1106            mUidMap.remove(userId);
1107        }
1108
1109        public int userIdCount() {
1110            return mUidMap.size();
1111        }
1112
1113        public int userIdAt(int n) {
1114            return mUidMap.keyAt(n);
1115        }
1116
1117        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1118            return mUidMap.get(userId);
1119        }
1120
1121        public int size() {
1122            // total number of pending broadcast entries across all userIds
1123            int num = 0;
1124            for (int i = 0; i< mUidMap.size(); i++) {
1125                num += mUidMap.valueAt(i).size();
1126            }
1127            return num;
1128        }
1129
1130        public void clear() {
1131            mUidMap.clear();
1132        }
1133
1134        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1135            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1136            if (map == null) {
1137                map = new ArrayMap<String, ArrayList<String>>();
1138                mUidMap.put(userId, map);
1139            }
1140            return map;
1141        }
1142    }
1143    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1144
1145    // Service Connection to remote media container service to copy
1146    // package uri's from external media onto secure containers
1147    // or internal storage.
1148    private IMediaContainerService mContainerService = null;
1149
1150    static final int SEND_PENDING_BROADCAST = 1;
1151    static final int MCS_BOUND = 3;
1152    static final int END_COPY = 4;
1153    static final int INIT_COPY = 5;
1154    static final int MCS_UNBIND = 6;
1155    static final int START_CLEANING_PACKAGE = 7;
1156    static final int FIND_INSTALL_LOC = 8;
1157    static final int POST_INSTALL = 9;
1158    static final int MCS_RECONNECT = 10;
1159    static final int MCS_GIVE_UP = 11;
1160    static final int UPDATED_MEDIA_STATUS = 12;
1161    static final int WRITE_SETTINGS = 13;
1162    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1163    static final int PACKAGE_VERIFIED = 15;
1164    static final int CHECK_PENDING_VERIFICATION = 16;
1165    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1166    static final int INTENT_FILTER_VERIFIED = 18;
1167    static final int WRITE_PACKAGE_LIST = 19;
1168    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1169
1170    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1171
1172    // Delay time in millisecs
1173    static final int BROADCAST_DELAY = 10 * 1000;
1174
1175    static UserManagerService sUserManager;
1176
1177    // Stores a list of users whose package restrictions file needs to be updated
1178    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1179
1180    final private DefaultContainerConnection mDefContainerConn =
1181            new DefaultContainerConnection();
1182    class DefaultContainerConnection implements ServiceConnection {
1183        public void onServiceConnected(ComponentName name, IBinder service) {
1184            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1185            final IMediaContainerService imcs = IMediaContainerService.Stub
1186                    .asInterface(Binder.allowBlocking(service));
1187            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1188        }
1189
1190        public void onServiceDisconnected(ComponentName name) {
1191            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1192        }
1193    }
1194
1195    // Recordkeeping of restore-after-install operations that are currently in flight
1196    // between the Package Manager and the Backup Manager
1197    static class PostInstallData {
1198        public InstallArgs args;
1199        public PackageInstalledInfo res;
1200
1201        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1202            args = _a;
1203            res = _r;
1204        }
1205    }
1206
1207    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1208    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1209
1210    // XML tags for backup/restore of various bits of state
1211    private static final String TAG_PREFERRED_BACKUP = "pa";
1212    private static final String TAG_DEFAULT_APPS = "da";
1213    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1214
1215    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1216    private static final String TAG_ALL_GRANTS = "rt-grants";
1217    private static final String TAG_GRANT = "grant";
1218    private static final String ATTR_PACKAGE_NAME = "pkg";
1219
1220    private static final String TAG_PERMISSION = "perm";
1221    private static final String ATTR_PERMISSION_NAME = "name";
1222    private static final String ATTR_IS_GRANTED = "g";
1223    private static final String ATTR_USER_SET = "set";
1224    private static final String ATTR_USER_FIXED = "fixed";
1225    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1226
1227    // System/policy permission grants are not backed up
1228    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1229            FLAG_PERMISSION_POLICY_FIXED
1230            | FLAG_PERMISSION_SYSTEM_FIXED
1231            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1232
1233    // And we back up these user-adjusted states
1234    private static final int USER_RUNTIME_GRANT_MASK =
1235            FLAG_PERMISSION_USER_SET
1236            | FLAG_PERMISSION_USER_FIXED
1237            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1238
1239    final @Nullable String mRequiredVerifierPackage;
1240    final @NonNull String mRequiredInstallerPackage;
1241    final @NonNull String mRequiredUninstallerPackage;
1242    final @Nullable String mSetupWizardPackage;
1243    final @Nullable String mStorageManagerPackage;
1244    final @NonNull String mServicesSystemSharedLibraryPackageName;
1245    final @NonNull String mSharedSystemSharedLibraryPackageName;
1246
1247    final boolean mPermissionReviewRequired;
1248
1249    private final PackageUsage mPackageUsage = new PackageUsage();
1250    private final CompilerStats mCompilerStats = new CompilerStats();
1251
1252    class PackageHandler extends Handler {
1253        private boolean mBound = false;
1254        final ArrayList<HandlerParams> mPendingInstalls =
1255            new ArrayList<HandlerParams>();
1256
1257        private boolean connectToService() {
1258            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1259                    " DefaultContainerService");
1260            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1261            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1263                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1264                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1265                mBound = true;
1266                return true;
1267            }
1268            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1269            return false;
1270        }
1271
1272        private void disconnectService() {
1273            mContainerService = null;
1274            mBound = false;
1275            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1276            mContext.unbindService(mDefContainerConn);
1277            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1278        }
1279
1280        PackageHandler(Looper looper) {
1281            super(looper);
1282        }
1283
1284        public void handleMessage(Message msg) {
1285            try {
1286                doHandleMessage(msg);
1287            } finally {
1288                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1289            }
1290        }
1291
1292        void doHandleMessage(Message msg) {
1293            switch (msg.what) {
1294                case INIT_COPY: {
1295                    HandlerParams params = (HandlerParams) msg.obj;
1296                    int idx = mPendingInstalls.size();
1297                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1298                    // If a bind was already initiated we dont really
1299                    // need to do anything. The pending install
1300                    // will be processed later on.
1301                    if (!mBound) {
1302                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1303                                System.identityHashCode(mHandler));
1304                        // If this is the only one pending we might
1305                        // have to bind to the service again.
1306                        if (!connectToService()) {
1307                            Slog.e(TAG, "Failed to bind to media container service");
1308                            params.serviceError();
1309                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1310                                    System.identityHashCode(mHandler));
1311                            if (params.traceMethod != null) {
1312                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1313                                        params.traceCookie);
1314                            }
1315                            return;
1316                        } else {
1317                            // Once we bind to the service, the first
1318                            // pending request will be processed.
1319                            mPendingInstalls.add(idx, params);
1320                        }
1321                    } else {
1322                        mPendingInstalls.add(idx, params);
1323                        // Already bound to the service. Just make
1324                        // sure we trigger off processing the first request.
1325                        if (idx == 0) {
1326                            mHandler.sendEmptyMessage(MCS_BOUND);
1327                        }
1328                    }
1329                    break;
1330                }
1331                case MCS_BOUND: {
1332                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1333                    if (msg.obj != null) {
1334                        mContainerService = (IMediaContainerService) msg.obj;
1335                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1336                                System.identityHashCode(mHandler));
1337                    }
1338                    if (mContainerService == null) {
1339                        if (!mBound) {
1340                            // Something seriously wrong since we are not bound and we are not
1341                            // waiting for connection. Bail out.
1342                            Slog.e(TAG, "Cannot bind to media container service");
1343                            for (HandlerParams params : mPendingInstalls) {
1344                                // Indicate service bind error
1345                                params.serviceError();
1346                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1347                                        System.identityHashCode(params));
1348                                if (params.traceMethod != null) {
1349                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1350                                            params.traceMethod, params.traceCookie);
1351                                }
1352                                return;
1353                            }
1354                            mPendingInstalls.clear();
1355                        } else {
1356                            Slog.w(TAG, "Waiting to connect to media container service");
1357                        }
1358                    } else if (mPendingInstalls.size() > 0) {
1359                        HandlerParams params = mPendingInstalls.get(0);
1360                        if (params != null) {
1361                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1362                                    System.identityHashCode(params));
1363                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1364                            if (params.startCopy()) {
1365                                // We are done...  look for more work or to
1366                                // go idle.
1367                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1368                                        "Checking for more work or unbind...");
1369                                // Delete pending install
1370                                if (mPendingInstalls.size() > 0) {
1371                                    mPendingInstalls.remove(0);
1372                                }
1373                                if (mPendingInstalls.size() == 0) {
1374                                    if (mBound) {
1375                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1376                                                "Posting delayed MCS_UNBIND");
1377                                        removeMessages(MCS_UNBIND);
1378                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1379                                        // Unbind after a little delay, to avoid
1380                                        // continual thrashing.
1381                                        sendMessageDelayed(ubmsg, 10000);
1382                                    }
1383                                } else {
1384                                    // There are more pending requests in queue.
1385                                    // Just post MCS_BOUND message to trigger processing
1386                                    // of next pending install.
1387                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1388                                            "Posting MCS_BOUND for next work");
1389                                    mHandler.sendEmptyMessage(MCS_BOUND);
1390                                }
1391                            }
1392                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1393                        }
1394                    } else {
1395                        // Should never happen ideally.
1396                        Slog.w(TAG, "Empty queue");
1397                    }
1398                    break;
1399                }
1400                case MCS_RECONNECT: {
1401                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1402                    if (mPendingInstalls.size() > 0) {
1403                        if (mBound) {
1404                            disconnectService();
1405                        }
1406                        if (!connectToService()) {
1407                            Slog.e(TAG, "Failed to bind to media container service");
1408                            for (HandlerParams params : mPendingInstalls) {
1409                                // Indicate service bind error
1410                                params.serviceError();
1411                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1412                                        System.identityHashCode(params));
1413                            }
1414                            mPendingInstalls.clear();
1415                        }
1416                    }
1417                    break;
1418                }
1419                case MCS_UNBIND: {
1420                    // If there is no actual work left, then time to unbind.
1421                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1422
1423                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1424                        if (mBound) {
1425                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1426
1427                            disconnectService();
1428                        }
1429                    } else if (mPendingInstalls.size() > 0) {
1430                        // There are more pending requests in queue.
1431                        // Just post MCS_BOUND message to trigger processing
1432                        // of next pending install.
1433                        mHandler.sendEmptyMessage(MCS_BOUND);
1434                    }
1435
1436                    break;
1437                }
1438                case MCS_GIVE_UP: {
1439                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1440                    HandlerParams params = mPendingInstalls.remove(0);
1441                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1442                            System.identityHashCode(params));
1443                    break;
1444                }
1445                case SEND_PENDING_BROADCAST: {
1446                    String packages[];
1447                    ArrayList<String> components[];
1448                    int size = 0;
1449                    int uids[];
1450                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1451                    synchronized (mPackages) {
1452                        if (mPendingBroadcasts == null) {
1453                            return;
1454                        }
1455                        size = mPendingBroadcasts.size();
1456                        if (size <= 0) {
1457                            // Nothing to be done. Just return
1458                            return;
1459                        }
1460                        packages = new String[size];
1461                        components = new ArrayList[size];
1462                        uids = new int[size];
1463                        int i = 0;  // filling out the above arrays
1464
1465                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1466                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1467                            Iterator<Map.Entry<String, ArrayList<String>>> it
1468                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1469                                            .entrySet().iterator();
1470                            while (it.hasNext() && i < size) {
1471                                Map.Entry<String, ArrayList<String>> ent = it.next();
1472                                packages[i] = ent.getKey();
1473                                components[i] = ent.getValue();
1474                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1475                                uids[i] = (ps != null)
1476                                        ? UserHandle.getUid(packageUserId, ps.appId)
1477                                        : -1;
1478                                i++;
1479                            }
1480                        }
1481                        size = i;
1482                        mPendingBroadcasts.clear();
1483                    }
1484                    // Send broadcasts
1485                    for (int i = 0; i < size; i++) {
1486                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                    break;
1490                }
1491                case START_CLEANING_PACKAGE: {
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1493                    final String packageName = (String)msg.obj;
1494                    final int userId = msg.arg1;
1495                    final boolean andCode = msg.arg2 != 0;
1496                    synchronized (mPackages) {
1497                        if (userId == UserHandle.USER_ALL) {
1498                            int[] users = sUserManager.getUserIds();
1499                            for (int user : users) {
1500                                mSettings.addPackageToCleanLPw(
1501                                        new PackageCleanItem(user, packageName, andCode));
1502                            }
1503                        } else {
1504                            mSettings.addPackageToCleanLPw(
1505                                    new PackageCleanItem(userId, packageName, andCode));
1506                        }
1507                    }
1508                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1509                    startCleaningPackages();
1510                } break;
1511                case POST_INSTALL: {
1512                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1513
1514                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1515                    final boolean didRestore = (msg.arg2 != 0);
1516                    mRunningInstalls.delete(msg.arg1);
1517
1518                    if (data != null) {
1519                        InstallArgs args = data.args;
1520                        PackageInstalledInfo parentRes = data.res;
1521
1522                        final boolean grantPermissions = (args.installFlags
1523                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1524                        final boolean killApp = (args.installFlags
1525                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1526                        final String[] grantedPermissions = args.installGrantPermissions;
1527
1528                        // Handle the parent package
1529                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1530                                grantedPermissions, didRestore, args.installerPackageName,
1531                                args.observer);
1532
1533                        // Handle the child packages
1534                        final int childCount = (parentRes.addedChildPackages != null)
1535                                ? parentRes.addedChildPackages.size() : 0;
1536                        for (int i = 0; i < childCount; i++) {
1537                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1538                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1539                                    grantedPermissions, false, args.installerPackageName,
1540                                    args.observer);
1541                        }
1542
1543                        // Log tracing if needed
1544                        if (args.traceMethod != null) {
1545                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1546                                    args.traceCookie);
1547                        }
1548                    } else {
1549                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1550                    }
1551
1552                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1553                } break;
1554                case UPDATED_MEDIA_STATUS: {
1555                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1556                    boolean reportStatus = msg.arg1 == 1;
1557                    boolean doGc = msg.arg2 == 1;
1558                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1559                    if (doGc) {
1560                        // Force a gc to clear up stale containers.
1561                        Runtime.getRuntime().gc();
1562                    }
1563                    if (msg.obj != null) {
1564                        @SuppressWarnings("unchecked")
1565                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1566                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1567                        // Unload containers
1568                        unloadAllContainers(args);
1569                    }
1570                    if (reportStatus) {
1571                        try {
1572                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1573                                    "Invoking StorageManagerService call back");
1574                            PackageHelper.getStorageManager().finishMediaUpdate();
1575                        } catch (RemoteException e) {
1576                            Log.e(TAG, "StorageManagerService not running?");
1577                        }
1578                    }
1579                } break;
1580                case WRITE_SETTINGS: {
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1582                    synchronized (mPackages) {
1583                        removeMessages(WRITE_SETTINGS);
1584                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1585                        mSettings.writeLPr();
1586                        mDirtyUsers.clear();
1587                    }
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1589                } break;
1590                case WRITE_PACKAGE_RESTRICTIONS: {
1591                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1592                    synchronized (mPackages) {
1593                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1594                        for (int userId : mDirtyUsers) {
1595                            mSettings.writePackageRestrictionsLPr(userId);
1596                        }
1597                        mDirtyUsers.clear();
1598                    }
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1600                } break;
1601                case WRITE_PACKAGE_LIST: {
1602                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603                    synchronized (mPackages) {
1604                        removeMessages(WRITE_PACKAGE_LIST);
1605                        mSettings.writePackageListLPr(msg.arg1);
1606                    }
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1608                } break;
1609                case CHECK_PENDING_VERIFICATION: {
1610                    final int verificationId = msg.arg1;
1611                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1612
1613                    if ((state != null) && !state.timeoutExtended()) {
1614                        final InstallArgs args = state.getInstallArgs();
1615                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1616
1617                        Slog.i(TAG, "Verification timed out for " + originUri);
1618                        mPendingVerification.remove(verificationId);
1619
1620                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1621
1622                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1623                            Slog.i(TAG, "Continuing with installation of " + originUri);
1624                            state.setVerifierResponse(Binder.getCallingUid(),
1625                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1626                            broadcastPackageVerified(verificationId, originUri,
1627                                    PackageManager.VERIFICATION_ALLOW,
1628                                    state.getInstallArgs().getUser());
1629                            try {
1630                                ret = args.copyApk(mContainerService, true);
1631                            } catch (RemoteException e) {
1632                                Slog.e(TAG, "Could not contact the ContainerService");
1633                            }
1634                        } else {
1635                            broadcastPackageVerified(verificationId, originUri,
1636                                    PackageManager.VERIFICATION_REJECT,
1637                                    state.getInstallArgs().getUser());
1638                        }
1639
1640                        Trace.asyncTraceEnd(
1641                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1642
1643                        processPendingInstall(args, ret);
1644                        mHandler.sendEmptyMessage(MCS_UNBIND);
1645                    }
1646                    break;
1647                }
1648                case PACKAGE_VERIFIED: {
1649                    final int verificationId = msg.arg1;
1650
1651                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1652                    if (state == null) {
1653                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1654                        break;
1655                    }
1656
1657                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1658
1659                    state.setVerifierResponse(response.callerUid, response.code);
1660
1661                    if (state.isVerificationComplete()) {
1662                        mPendingVerification.remove(verificationId);
1663
1664                        final InstallArgs args = state.getInstallArgs();
1665                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1666
1667                        int ret;
1668                        if (state.isInstallAllowed()) {
1669                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1670                            broadcastPackageVerified(verificationId, originUri,
1671                                    response.code, state.getInstallArgs().getUser());
1672                            try {
1673                                ret = args.copyApk(mContainerService, true);
1674                            } catch (RemoteException e) {
1675                                Slog.e(TAG, "Could not contact the ContainerService");
1676                            }
1677                        } else {
1678                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1679                        }
1680
1681                        Trace.asyncTraceEnd(
1682                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1683
1684                        processPendingInstall(args, ret);
1685                        mHandler.sendEmptyMessage(MCS_UNBIND);
1686                    }
1687
1688                    break;
1689                }
1690                case START_INTENT_FILTER_VERIFICATIONS: {
1691                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1692                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1693                            params.replacing, params.pkg);
1694                    break;
1695                }
1696                case INTENT_FILTER_VERIFIED: {
1697                    final int verificationId = msg.arg1;
1698
1699                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1700                            verificationId);
1701                    if (state == null) {
1702                        Slog.w(TAG, "Invalid IntentFilter verification token "
1703                                + verificationId + " received");
1704                        break;
1705                    }
1706
1707                    final int userId = state.getUserId();
1708
1709                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1710                            "Processing IntentFilter verification with token:"
1711                            + verificationId + " and userId:" + userId);
1712
1713                    final IntentFilterVerificationResponse response =
1714                            (IntentFilterVerificationResponse) msg.obj;
1715
1716                    state.setVerifierResponse(response.callerUid, response.code);
1717
1718                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1719                            "IntentFilter verification with token:" + verificationId
1720                            + " and userId:" + userId
1721                            + " is settings verifier response with response code:"
1722                            + response.code);
1723
1724                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1725                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1726                                + response.getFailedDomainsString());
1727                    }
1728
1729                    if (state.isVerificationComplete()) {
1730                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1731                    } else {
1732                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1733                                "IntentFilter verification with token:" + verificationId
1734                                + " was not said to be complete");
1735                    }
1736
1737                    break;
1738                }
1739                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1740                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1741                            mInstantAppResolverConnection,
1742                            (InstantAppRequest) msg.obj,
1743                            mInstantAppInstallerActivity,
1744                            mHandler);
1745                }
1746            }
1747        }
1748    }
1749
1750    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1751            boolean killApp, String[] grantedPermissions,
1752            boolean launchedForRestore, String installerPackage,
1753            IPackageInstallObserver2 installObserver) {
1754        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1755            // Send the removed broadcasts
1756            if (res.removedInfo != null) {
1757                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1758            }
1759
1760            // Now that we successfully installed the package, grant runtime
1761            // permissions if requested before broadcasting the install. Also
1762            // for legacy apps in permission review mode we clear the permission
1763            // review flag which is used to emulate runtime permissions for
1764            // legacy apps.
1765            if (grantPermissions) {
1766                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1767            }
1768
1769            final boolean update = res.removedInfo != null
1770                    && res.removedInfo.removedPackage != null;
1771
1772            // If this is the first time we have child packages for a disabled privileged
1773            // app that had no children, we grant requested runtime permissions to the new
1774            // children if the parent on the system image had them already granted.
1775            if (res.pkg.parentPackage != null) {
1776                synchronized (mPackages) {
1777                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1778                }
1779            }
1780
1781            synchronized (mPackages) {
1782                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1783            }
1784
1785            final String packageName = res.pkg.applicationInfo.packageName;
1786
1787            // Determine the set of users who are adding this package for
1788            // the first time vs. those who are seeing an update.
1789            int[] firstUsers = EMPTY_INT_ARRAY;
1790            int[] updateUsers = EMPTY_INT_ARRAY;
1791            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1792            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1793            for (int newUser : res.newUsers) {
1794                if (ps.getInstantApp(newUser)) {
1795                    continue;
1796                }
1797                if (allNewUsers) {
1798                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1799                    continue;
1800                }
1801                boolean isNew = true;
1802                for (int origUser : res.origUsers) {
1803                    if (origUser == newUser) {
1804                        isNew = false;
1805                        break;
1806                    }
1807                }
1808                if (isNew) {
1809                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1810                } else {
1811                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1812                }
1813            }
1814
1815            // Send installed broadcasts if the package is not a static shared lib.
1816            if (res.pkg.staticSharedLibName == null) {
1817                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1818
1819                // Send added for users that see the package for the first time
1820                // sendPackageAddedForNewUsers also deals with system apps
1821                int appId = UserHandle.getAppId(res.uid);
1822                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1823                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1824
1825                // Send added for users that don't see the package for the first time
1826                Bundle extras = new Bundle(1);
1827                extras.putInt(Intent.EXTRA_UID, res.uid);
1828                if (update) {
1829                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1830                }
1831                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1832                        extras, 0 /*flags*/, null /*targetPackage*/,
1833                        null /*finishedReceiver*/, updateUsers);
1834
1835                // Send replaced for users that don't see the package for the first time
1836                if (update) {
1837                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1838                            packageName, extras, 0 /*flags*/,
1839                            null /*targetPackage*/, null /*finishedReceiver*/,
1840                            updateUsers);
1841                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1842                            null /*package*/, null /*extras*/, 0 /*flags*/,
1843                            packageName /*targetPackage*/,
1844                            null /*finishedReceiver*/, updateUsers);
1845                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1846                    // First-install and we did a restore, so we're responsible for the
1847                    // first-launch broadcast.
1848                    if (DEBUG_BACKUP) {
1849                        Slog.i(TAG, "Post-restore of " + packageName
1850                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1851                    }
1852                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1853                }
1854
1855                // Send broadcast package appeared if forward locked/external for all users
1856                // treat asec-hosted packages like removable media on upgrade
1857                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1858                    if (DEBUG_INSTALL) {
1859                        Slog.i(TAG, "upgrading pkg " + res.pkg
1860                                + " is ASEC-hosted -> AVAILABLE");
1861                    }
1862                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1863                    ArrayList<String> pkgList = new ArrayList<>(1);
1864                    pkgList.add(packageName);
1865                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1866                }
1867            }
1868
1869            // Work that needs to happen on first install within each user
1870            if (firstUsers != null && firstUsers.length > 0) {
1871                synchronized (mPackages) {
1872                    for (int userId : firstUsers) {
1873                        // If this app is a browser and it's newly-installed for some
1874                        // users, clear any default-browser state in those users. The
1875                        // app's nature doesn't depend on the user, so we can just check
1876                        // its browser nature in any user and generalize.
1877                        if (packageIsBrowser(packageName, userId)) {
1878                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1879                        }
1880
1881                        // We may also need to apply pending (restored) runtime
1882                        // permission grants within these users.
1883                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1884                    }
1885                }
1886            }
1887
1888            // Log current value of "unknown sources" setting
1889            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1890                    getUnknownSourcesSettings());
1891
1892            // Force a gc to clear up things
1893            Runtime.getRuntime().gc();
1894
1895            // Remove the replaced package's older resources safely now
1896            // We delete after a gc for applications  on sdcard.
1897            if (res.removedInfo != null && res.removedInfo.args != null) {
1898                synchronized (mInstallLock) {
1899                    res.removedInfo.args.doPostDeleteLI(true);
1900                }
1901            }
1902
1903            // Notify DexManager that the package was installed for new users.
1904            // The updated users should already be indexed and the package code paths
1905            // should not change.
1906            // Don't notify the manager for ephemeral apps as they are not expected to
1907            // survive long enough to benefit of background optimizations.
1908            for (int userId : firstUsers) {
1909                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1910                mDexManager.notifyPackageInstalled(info, userId);
1911            }
1912        }
1913
1914        // If someone is watching installs - notify them
1915        if (installObserver != null) {
1916            try {
1917                Bundle extras = extrasForInstallResult(res);
1918                installObserver.onPackageInstalled(res.name, res.returnCode,
1919                        res.returnMsg, extras);
1920            } catch (RemoteException e) {
1921                Slog.i(TAG, "Observer no longer exists.");
1922            }
1923        }
1924    }
1925
1926    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1927            PackageParser.Package pkg) {
1928        if (pkg.parentPackage == null) {
1929            return;
1930        }
1931        if (pkg.requestedPermissions == null) {
1932            return;
1933        }
1934        final PackageSetting disabledSysParentPs = mSettings
1935                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1936        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1937                || !disabledSysParentPs.isPrivileged()
1938                || (disabledSysParentPs.childPackageNames != null
1939                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1940            return;
1941        }
1942        final int[] allUserIds = sUserManager.getUserIds();
1943        final int permCount = pkg.requestedPermissions.size();
1944        for (int i = 0; i < permCount; i++) {
1945            String permission = pkg.requestedPermissions.get(i);
1946            BasePermission bp = mSettings.mPermissions.get(permission);
1947            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1948                continue;
1949            }
1950            for (int userId : allUserIds) {
1951                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1952                        permission, userId)) {
1953                    grantRuntimePermission(pkg.packageName, permission, userId);
1954                }
1955            }
1956        }
1957    }
1958
1959    private StorageEventListener mStorageListener = new StorageEventListener() {
1960        @Override
1961        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1962            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1963                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1964                    final String volumeUuid = vol.getFsUuid();
1965
1966                    // Clean up any users or apps that were removed or recreated
1967                    // while this volume was missing
1968                    sUserManager.reconcileUsers(volumeUuid);
1969                    reconcileApps(volumeUuid);
1970
1971                    // Clean up any install sessions that expired or were
1972                    // cancelled while this volume was missing
1973                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1974
1975                    loadPrivatePackages(vol);
1976
1977                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1978                    unloadPrivatePackages(vol);
1979                }
1980            }
1981
1982            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1983                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1984                    updateExternalMediaStatus(true, false);
1985                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1986                    updateExternalMediaStatus(false, false);
1987                }
1988            }
1989        }
1990
1991        @Override
1992        public void onVolumeForgotten(String fsUuid) {
1993            if (TextUtils.isEmpty(fsUuid)) {
1994                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1995                return;
1996            }
1997
1998            // Remove any apps installed on the forgotten volume
1999            synchronized (mPackages) {
2000                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2001                for (PackageSetting ps : packages) {
2002                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2003                    deletePackageVersioned(new VersionedPackage(ps.name,
2004                            PackageManager.VERSION_CODE_HIGHEST),
2005                            new LegacyPackageDeleteObserver(null).getBinder(),
2006                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2007                    // Try very hard to release any references to this package
2008                    // so we don't risk the system server being killed due to
2009                    // open FDs
2010                    AttributeCache.instance().removePackage(ps.name);
2011                }
2012
2013                mSettings.onVolumeForgotten(fsUuid);
2014                mSettings.writeLPr();
2015            }
2016        }
2017    };
2018
2019    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2020            String[] grantedPermissions) {
2021        for (int userId : userIds) {
2022            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2023        }
2024    }
2025
2026    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2027            String[] grantedPermissions) {
2028        SettingBase sb = (SettingBase) pkg.mExtras;
2029        if (sb == null) {
2030            return;
2031        }
2032
2033        PermissionsState permissionsState = sb.getPermissionsState();
2034
2035        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2036                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2037
2038        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2039                >= Build.VERSION_CODES.M;
2040
2041        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2042
2043        for (String permission : pkg.requestedPermissions) {
2044            final BasePermission bp;
2045            synchronized (mPackages) {
2046                bp = mSettings.mPermissions.get(permission);
2047            }
2048            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2049                    && (!instantApp || bp.isInstant())
2050                    && (grantedPermissions == null
2051                           || ArrayUtils.contains(grantedPermissions, permission))) {
2052                final int flags = permissionsState.getPermissionFlags(permission, userId);
2053                if (supportsRuntimePermissions) {
2054                    // Installer cannot change immutable permissions.
2055                    if ((flags & immutableFlags) == 0) {
2056                        grantRuntimePermission(pkg.packageName, permission, userId);
2057                    }
2058                } else if (mPermissionReviewRequired) {
2059                    // In permission review mode we clear the review flag when we
2060                    // are asked to install the app with all permissions granted.
2061                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2062                        updatePermissionFlags(permission, pkg.packageName,
2063                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2064                    }
2065                }
2066            }
2067        }
2068    }
2069
2070    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2071        Bundle extras = null;
2072        switch (res.returnCode) {
2073            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2074                extras = new Bundle();
2075                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2076                        res.origPermission);
2077                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2078                        res.origPackage);
2079                break;
2080            }
2081            case PackageManager.INSTALL_SUCCEEDED: {
2082                extras = new Bundle();
2083                extras.putBoolean(Intent.EXTRA_REPLACING,
2084                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2085                break;
2086            }
2087        }
2088        return extras;
2089    }
2090
2091    void scheduleWriteSettingsLocked() {
2092        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2093            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2094        }
2095    }
2096
2097    void scheduleWritePackageListLocked(int userId) {
2098        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2099            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2100            msg.arg1 = userId;
2101            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2102        }
2103    }
2104
2105    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2106        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2107        scheduleWritePackageRestrictionsLocked(userId);
2108    }
2109
2110    void scheduleWritePackageRestrictionsLocked(int userId) {
2111        final int[] userIds = (userId == UserHandle.USER_ALL)
2112                ? sUserManager.getUserIds() : new int[]{userId};
2113        for (int nextUserId : userIds) {
2114            if (!sUserManager.exists(nextUserId)) return;
2115            mDirtyUsers.add(nextUserId);
2116            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2117                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2118            }
2119        }
2120    }
2121
2122    public static PackageManagerService main(Context context, Installer installer,
2123            boolean factoryTest, boolean onlyCore) {
2124        // Self-check for initial settings.
2125        PackageManagerServiceCompilerMapping.checkProperties();
2126
2127        PackageManagerService m = new PackageManagerService(context, installer,
2128                factoryTest, onlyCore);
2129        m.enableSystemUserPackages();
2130        ServiceManager.addService("package", m);
2131        return m;
2132    }
2133
2134    private void enableSystemUserPackages() {
2135        if (!UserManager.isSplitSystemUser()) {
2136            return;
2137        }
2138        // For system user, enable apps based on the following conditions:
2139        // - app is whitelisted or belong to one of these groups:
2140        //   -- system app which has no launcher icons
2141        //   -- system app which has INTERACT_ACROSS_USERS permission
2142        //   -- system IME app
2143        // - app is not in the blacklist
2144        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2145        Set<String> enableApps = new ArraySet<>();
2146        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2147                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2148                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2149        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2150        enableApps.addAll(wlApps);
2151        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2152                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2153        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2154        enableApps.removeAll(blApps);
2155        Log.i(TAG, "Applications installed for system user: " + enableApps);
2156        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2157                UserHandle.SYSTEM);
2158        final int allAppsSize = allAps.size();
2159        synchronized (mPackages) {
2160            for (int i = 0; i < allAppsSize; i++) {
2161                String pName = allAps.get(i);
2162                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2163                // Should not happen, but we shouldn't be failing if it does
2164                if (pkgSetting == null) {
2165                    continue;
2166                }
2167                boolean install = enableApps.contains(pName);
2168                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2169                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2170                            + " for system user");
2171                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2172                }
2173            }
2174            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2175        }
2176    }
2177
2178    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2179        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2180                Context.DISPLAY_SERVICE);
2181        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2182    }
2183
2184    /**
2185     * Requests that files preopted on a secondary system partition be copied to the data partition
2186     * if possible.  Note that the actual copying of the files is accomplished by init for security
2187     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2188     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2189     */
2190    private static void requestCopyPreoptedFiles() {
2191        final int WAIT_TIME_MS = 100;
2192        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2193        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2194            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2195            // We will wait for up to 100 seconds.
2196            final long timeStart = SystemClock.uptimeMillis();
2197            final long timeEnd = timeStart + 100 * 1000;
2198            long timeNow = timeStart;
2199            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2200                try {
2201                    Thread.sleep(WAIT_TIME_MS);
2202                } catch (InterruptedException e) {
2203                    // Do nothing
2204                }
2205                timeNow = SystemClock.uptimeMillis();
2206                if (timeNow > timeEnd) {
2207                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2208                    Slog.wtf(TAG, "cppreopt did not finish!");
2209                    break;
2210                }
2211            }
2212
2213            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2214        }
2215    }
2216
2217    public PackageManagerService(Context context, Installer installer,
2218            boolean factoryTest, boolean onlyCore) {
2219        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2220        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2221        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2222                SystemClock.uptimeMillis());
2223
2224        if (mSdkVersion <= 0) {
2225            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2226        }
2227
2228        mContext = context;
2229
2230        mPermissionReviewRequired = context.getResources().getBoolean(
2231                R.bool.config_permissionReviewRequired);
2232
2233        mFactoryTest = factoryTest;
2234        mOnlyCore = onlyCore;
2235        mMetrics = new DisplayMetrics();
2236        mSettings = new Settings(mPackages);
2237        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2240                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2241        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2242                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2243        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2248                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2249
2250        String separateProcesses = SystemProperties.get("debug.separate_processes");
2251        if (separateProcesses != null && separateProcesses.length() > 0) {
2252            if ("*".equals(separateProcesses)) {
2253                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2254                mSeparateProcesses = null;
2255                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2256            } else {
2257                mDefParseFlags = 0;
2258                mSeparateProcesses = separateProcesses.split(",");
2259                Slog.w(TAG, "Running with debug.separate_processes: "
2260                        + separateProcesses);
2261            }
2262        } else {
2263            mDefParseFlags = 0;
2264            mSeparateProcesses = null;
2265        }
2266
2267        mInstaller = installer;
2268        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2269                "*dexopt*");
2270        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2271        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2272
2273        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2274                FgThread.get().getLooper());
2275
2276        getDefaultDisplayMetrics(context, mMetrics);
2277
2278        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2279        SystemConfig systemConfig = SystemConfig.getInstance();
2280        mGlobalGids = systemConfig.getGlobalGids();
2281        mSystemPermissions = systemConfig.getSystemPermissions();
2282        mAvailableFeatures = systemConfig.getAvailableFeatures();
2283        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2284
2285        mProtectedPackages = new ProtectedPackages(mContext);
2286
2287        synchronized (mInstallLock) {
2288        // writer
2289        synchronized (mPackages) {
2290            mHandlerThread = new ServiceThread(TAG,
2291                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2292            mHandlerThread.start();
2293            mHandler = new PackageHandler(mHandlerThread.getLooper());
2294            mProcessLoggingHandler = new ProcessLoggingHandler();
2295            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2296
2297            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2298            mInstantAppRegistry = new InstantAppRegistry(this);
2299
2300            File dataDir = Environment.getDataDirectory();
2301            mAppInstallDir = new File(dataDir, "app");
2302            mAppLib32InstallDir = new File(dataDir, "app-lib");
2303            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2304            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2305            sUserManager = new UserManagerService(context, this,
2306                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2307
2308            // Propagate permission configuration in to package manager.
2309            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2310                    = systemConfig.getPermissions();
2311            for (int i=0; i<permConfig.size(); i++) {
2312                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2313                BasePermission bp = mSettings.mPermissions.get(perm.name);
2314                if (bp == null) {
2315                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2316                    mSettings.mPermissions.put(perm.name, bp);
2317                }
2318                if (perm.gids != null) {
2319                    bp.setGids(perm.gids, perm.perUser);
2320                }
2321            }
2322
2323            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2324            final int builtInLibCount = libConfig.size();
2325            for (int i = 0; i < builtInLibCount; i++) {
2326                String name = libConfig.keyAt(i);
2327                String path = libConfig.valueAt(i);
2328                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2329                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2330            }
2331
2332            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2333
2334            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2335            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2336            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2337
2338            // Clean up orphaned packages for which the code path doesn't exist
2339            // and they are an update to a system app - caused by bug/32321269
2340            final int packageSettingCount = mSettings.mPackages.size();
2341            for (int i = packageSettingCount - 1; i >= 0; i--) {
2342                PackageSetting ps = mSettings.mPackages.valueAt(i);
2343                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2344                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2345                    mSettings.mPackages.removeAt(i);
2346                    mSettings.enableSystemPackageLPw(ps.name);
2347                }
2348            }
2349
2350            if (mFirstBoot) {
2351                requestCopyPreoptedFiles();
2352            }
2353
2354            String customResolverActivity = Resources.getSystem().getString(
2355                    R.string.config_customResolverActivity);
2356            if (TextUtils.isEmpty(customResolverActivity)) {
2357                customResolverActivity = null;
2358            } else {
2359                mCustomResolverComponentName = ComponentName.unflattenFromString(
2360                        customResolverActivity);
2361            }
2362
2363            long startTime = SystemClock.uptimeMillis();
2364
2365            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2366                    startTime);
2367
2368            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2369            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2370
2371            if (bootClassPath == null) {
2372                Slog.w(TAG, "No BOOTCLASSPATH found!");
2373            }
2374
2375            if (systemServerClassPath == null) {
2376                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2377            }
2378
2379            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2380            final String[] dexCodeInstructionSets =
2381                    getDexCodeInstructionSets(
2382                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2383
2384            /**
2385             * Ensure all external libraries have had dexopt run on them.
2386             */
2387            if (mSharedLibraries.size() > 0) {
2388                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2389                // NOTE: For now, we're compiling these system "shared libraries"
2390                // (and framework jars) into all available architectures. It's possible
2391                // to compile them only when we come across an app that uses them (there's
2392                // already logic for that in scanPackageLI) but that adds some complexity.
2393                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2394                    final int libCount = mSharedLibraries.size();
2395                    for (int i = 0; i < libCount; i++) {
2396                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2397                        final int versionCount = versionedLib.size();
2398                        for (int j = 0; j < versionCount; j++) {
2399                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2400                            final String libPath = libEntry.path != null
2401                                    ? libEntry.path : libEntry.apk;
2402                            if (libPath == null) {
2403                                continue;
2404                            }
2405                            try {
2406                                // Shared libraries do not have profiles so we perform a full
2407                                // AOT compilation (if needed).
2408                                int dexoptNeeded = DexFile.getDexOptNeeded(
2409                                        libPath, dexCodeInstructionSet,
2410                                        getCompilerFilterForReason(REASON_SHARED_APK),
2411                                        false /* newProfile */);
2412                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2413                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2414                                            dexCodeInstructionSet, dexoptNeeded, null,
2415                                            DEXOPT_PUBLIC,
2416                                            getCompilerFilterForReason(REASON_SHARED_APK),
2417                                            StorageManager.UUID_PRIVATE_INTERNAL,
2418                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2419                                }
2420                            } catch (FileNotFoundException e) {
2421                                Slog.w(TAG, "Library not found: " + libPath);
2422                            } catch (IOException | InstallerException e) {
2423                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2424                                        + e.getMessage());
2425                            }
2426                        }
2427                    }
2428                }
2429                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2430            }
2431
2432            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2433
2434            final VersionInfo ver = mSettings.getInternalVersion();
2435            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2436
2437            // when upgrading from pre-M, promote system app permissions from install to runtime
2438            mPromoteSystemApps =
2439                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2440
2441            // When upgrading from pre-N, we need to handle package extraction like first boot,
2442            // as there is no profiling data available.
2443            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2444
2445            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2446
2447            // save off the names of pre-existing system packages prior to scanning; we don't
2448            // want to automatically grant runtime permissions for new system apps
2449            if (mPromoteSystemApps) {
2450                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2451                while (pkgSettingIter.hasNext()) {
2452                    PackageSetting ps = pkgSettingIter.next();
2453                    if (isSystemApp(ps)) {
2454                        mExistingSystemPackages.add(ps.name);
2455                    }
2456                }
2457            }
2458
2459            mCacheDir = preparePackageParserCache(mIsUpgrade);
2460
2461            // Set flag to monitor and not change apk file paths when
2462            // scanning install directories.
2463            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2464
2465            if (mIsUpgrade || mFirstBoot) {
2466                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2467            }
2468
2469            // Collect vendor overlay packages. (Do this before scanning any apps.)
2470            // For security and version matching reason, only consider
2471            // overlay packages if they reside in the right directory.
2472            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2473                    | PackageParser.PARSE_IS_SYSTEM
2474                    | PackageParser.PARSE_IS_SYSTEM_DIR
2475                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2476
2477            // Find base frameworks (resource packages without code).
2478            scanDirTracedLI(frameworkDir, mDefParseFlags
2479                    | PackageParser.PARSE_IS_SYSTEM
2480                    | PackageParser.PARSE_IS_SYSTEM_DIR
2481                    | PackageParser.PARSE_IS_PRIVILEGED,
2482                    scanFlags | SCAN_NO_DEX, 0);
2483
2484            // Collected privileged system packages.
2485            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2486            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR
2489                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2490
2491            // Collect ordinary system packages.
2492            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2493            scanDirTracedLI(systemAppDir, mDefParseFlags
2494                    | PackageParser.PARSE_IS_SYSTEM
2495                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2496
2497            // Collect all vendor packages.
2498            File vendorAppDir = new File("/vendor/app");
2499            try {
2500                vendorAppDir = vendorAppDir.getCanonicalFile();
2501            } catch (IOException e) {
2502                // failed to look up canonical path, continue with original one
2503            }
2504            scanDirTracedLI(vendorAppDir, mDefParseFlags
2505                    | PackageParser.PARSE_IS_SYSTEM
2506                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2507
2508            // Collect all OEM packages.
2509            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2510            scanDirTracedLI(oemAppDir, mDefParseFlags
2511                    | PackageParser.PARSE_IS_SYSTEM
2512                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2513
2514            // Prune any system packages that no longer exist.
2515            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2516            if (!mOnlyCore) {
2517                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2518                while (psit.hasNext()) {
2519                    PackageSetting ps = psit.next();
2520
2521                    /*
2522                     * If this is not a system app, it can't be a
2523                     * disable system app.
2524                     */
2525                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2526                        continue;
2527                    }
2528
2529                    /*
2530                     * If the package is scanned, it's not erased.
2531                     */
2532                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2533                    if (scannedPkg != null) {
2534                        /*
2535                         * If the system app is both scanned and in the
2536                         * disabled packages list, then it must have been
2537                         * added via OTA. Remove it from the currently
2538                         * scanned package so the previously user-installed
2539                         * application can be scanned.
2540                         */
2541                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2542                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2543                                    + ps.name + "; removing system app.  Last known codePath="
2544                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2545                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2546                                    + scannedPkg.mVersionCode);
2547                            removePackageLI(scannedPkg, true);
2548                            mExpectingBetter.put(ps.name, ps.codePath);
2549                        }
2550
2551                        continue;
2552                    }
2553
2554                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2555                        psit.remove();
2556                        logCriticalInfo(Log.WARN, "System package " + ps.name
2557                                + " no longer exists; it's data will be wiped");
2558                        // Actual deletion of code and data will be handled by later
2559                        // reconciliation step
2560                    } else {
2561                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2562                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2563                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2564                        }
2565                    }
2566                }
2567            }
2568
2569            //look for any incomplete package installations
2570            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2571            for (int i = 0; i < deletePkgsList.size(); i++) {
2572                // Actual deletion of code and data will be handled by later
2573                // reconciliation step
2574                final String packageName = deletePkgsList.get(i).name;
2575                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2576                synchronized (mPackages) {
2577                    mSettings.removePackageLPw(packageName);
2578                }
2579            }
2580
2581            //delete tmp files
2582            deleteTempPackageFiles();
2583
2584            // Remove any shared userIDs that have no associated packages
2585            mSettings.pruneSharedUsersLPw();
2586
2587            if (!mOnlyCore) {
2588                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2589                        SystemClock.uptimeMillis());
2590                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2591
2592                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2593                        | PackageParser.PARSE_FORWARD_LOCK,
2594                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2595
2596                /**
2597                 * Remove disable package settings for any updated system
2598                 * apps that were removed via an OTA. If they're not a
2599                 * previously-updated app, remove them completely.
2600                 * Otherwise, just revoke their system-level permissions.
2601                 */
2602                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2603                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2604                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2605
2606                    String msg;
2607                    if (deletedPkg == null) {
2608                        msg = "Updated system package " + deletedAppName
2609                                + " no longer exists; it's data will be wiped";
2610                        // Actual deletion of code and data will be handled by later
2611                        // reconciliation step
2612                    } else {
2613                        msg = "Updated system app + " + deletedAppName
2614                                + " no longer present; removing system privileges for "
2615                                + deletedAppName;
2616
2617                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2618
2619                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2620                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2621                    }
2622                    logCriticalInfo(Log.WARN, msg);
2623                }
2624
2625                /**
2626                 * Make sure all system apps that we expected to appear on
2627                 * the userdata partition actually showed up. If they never
2628                 * appeared, crawl back and revive the system version.
2629                 */
2630                for (int i = 0; i < mExpectingBetter.size(); i++) {
2631                    final String packageName = mExpectingBetter.keyAt(i);
2632                    if (!mPackages.containsKey(packageName)) {
2633                        final File scanFile = mExpectingBetter.valueAt(i);
2634
2635                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2636                                + " but never showed up; reverting to system");
2637
2638                        int reparseFlags = mDefParseFlags;
2639                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2640                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2641                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2642                                    | PackageParser.PARSE_IS_PRIVILEGED;
2643                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2644                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2645                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2646                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2650                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2651                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2652                        } else {
2653                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2654                            continue;
2655                        }
2656
2657                        mSettings.enableSystemPackageLPw(packageName);
2658
2659                        try {
2660                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2661                        } catch (PackageManagerException e) {
2662                            Slog.e(TAG, "Failed to parse original system package: "
2663                                    + e.getMessage());
2664                        }
2665                    }
2666                }
2667            }
2668            mExpectingBetter.clear();
2669
2670            // Resolve the storage manager.
2671            mStorageManagerPackage = getStorageManagerPackageName();
2672
2673            // Resolve protected action filters. Only the setup wizard is allowed to
2674            // have a high priority filter for these actions.
2675            mSetupWizardPackage = getSetupWizardPackageName();
2676            if (mProtectedFilters.size() > 0) {
2677                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2678                    Slog.i(TAG, "No setup wizard;"
2679                        + " All protected intents capped to priority 0");
2680                }
2681                for (ActivityIntentInfo filter : mProtectedFilters) {
2682                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2683                        if (DEBUG_FILTERS) {
2684                            Slog.i(TAG, "Found setup wizard;"
2685                                + " allow priority " + filter.getPriority() + ";"
2686                                + " package: " + filter.activity.info.packageName
2687                                + " activity: " + filter.activity.className
2688                                + " priority: " + filter.getPriority());
2689                        }
2690                        // skip setup wizard; allow it to keep the high priority filter
2691                        continue;
2692                    }
2693                    Slog.w(TAG, "Protected action; cap priority to 0;"
2694                            + " package: " + filter.activity.info.packageName
2695                            + " activity: " + filter.activity.className
2696                            + " origPrio: " + filter.getPriority());
2697                    filter.setPriority(0);
2698                }
2699            }
2700            mDeferProtectedFilters = false;
2701            mProtectedFilters.clear();
2702
2703            // Now that we know all of the shared libraries, update all clients to have
2704            // the correct library paths.
2705            updateAllSharedLibrariesLPw(null);
2706
2707            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2708                // NOTE: We ignore potential failures here during a system scan (like
2709                // the rest of the commands above) because there's precious little we
2710                // can do about it. A settings error is reported, though.
2711                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2712            }
2713
2714            // Now that we know all the packages we are keeping,
2715            // read and update their last usage times.
2716            mPackageUsage.read(mPackages);
2717            mCompilerStats.read();
2718
2719            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2720                    SystemClock.uptimeMillis());
2721            Slog.i(TAG, "Time to scan packages: "
2722                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2723                    + " seconds");
2724
2725            // If the platform SDK has changed since the last time we booted,
2726            // we need to re-grant app permission to catch any new ones that
2727            // appear.  This is really a hack, and means that apps can in some
2728            // cases get permissions that the user didn't initially explicitly
2729            // allow...  it would be nice to have some better way to handle
2730            // this situation.
2731            int updateFlags = UPDATE_PERMISSIONS_ALL;
2732            if (ver.sdkVersion != mSdkVersion) {
2733                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2734                        + mSdkVersion + "; regranting permissions for internal storage");
2735                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2736            }
2737            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2738            ver.sdkVersion = mSdkVersion;
2739
2740            // If this is the first boot or an update from pre-M, and it is a normal
2741            // boot, then we need to initialize the default preferred apps across
2742            // all defined users.
2743            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2744                for (UserInfo user : sUserManager.getUsers(true)) {
2745                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2746                    applyFactoryDefaultBrowserLPw(user.id);
2747                    primeDomainVerificationsLPw(user.id);
2748                }
2749            }
2750
2751            // Prepare storage for system user really early during boot,
2752            // since core system apps like SettingsProvider and SystemUI
2753            // can't wait for user to start
2754            final int storageFlags;
2755            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2756                storageFlags = StorageManager.FLAG_STORAGE_DE;
2757            } else {
2758                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2759            }
2760            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2761                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2762                    true /* onlyCoreApps */);
2763            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2764                if (deferPackages == null || deferPackages.isEmpty()) {
2765                    return;
2766                }
2767                int count = 0;
2768                for (String pkgName : deferPackages) {
2769                    PackageParser.Package pkg = null;
2770                    synchronized (mPackages) {
2771                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2772                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2773                            pkg = ps.pkg;
2774                        }
2775                    }
2776                    if (pkg != null) {
2777                        synchronized (mInstallLock) {
2778                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2779                                    true /* maybeMigrateAppData */);
2780                        }
2781                        count++;
2782                    }
2783                }
2784                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2785            }, "prepareAppData");
2786
2787            // If this is first boot after an OTA, and a normal boot, then
2788            // we need to clear code cache directories.
2789            // Note that we do *not* clear the application profiles. These remain valid
2790            // across OTAs and are used to drive profile verification (post OTA) and
2791            // profile compilation (without waiting to collect a fresh set of profiles).
2792            if (mIsUpgrade && !onlyCore) {
2793                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2794                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2795                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2796                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2797                        // No apps are running this early, so no need to freeze
2798                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2799                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2800                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2801                    }
2802                }
2803                ver.fingerprint = Build.FINGERPRINT;
2804            }
2805
2806            checkDefaultBrowser();
2807
2808            // clear only after permissions and other defaults have been updated
2809            mExistingSystemPackages.clear();
2810            mPromoteSystemApps = false;
2811
2812            // All the changes are done during package scanning.
2813            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2814
2815            // can downgrade to reader
2816            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2817            mSettings.writeLPr();
2818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2819
2820            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2821            // early on (before the package manager declares itself as early) because other
2822            // components in the system server might ask for package contexts for these apps.
2823            //
2824            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2825            // (i.e, that the data partition is unavailable).
2826            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2827                long start = System.nanoTime();
2828                List<PackageParser.Package> coreApps = new ArrayList<>();
2829                for (PackageParser.Package pkg : mPackages.values()) {
2830                    if (pkg.coreApp) {
2831                        coreApps.add(pkg);
2832                    }
2833                }
2834
2835                int[] stats = performDexOptUpgrade(coreApps, false,
2836                        getCompilerFilterForReason(REASON_CORE_APP));
2837
2838                final int elapsedTimeSeconds =
2839                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2840                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2841
2842                if (DEBUG_DEXOPT) {
2843                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2844                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2845                }
2846
2847
2848                // TODO: Should we log these stats to tron too ?
2849                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2850                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2851                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2852                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2853            }
2854
2855            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2856                    SystemClock.uptimeMillis());
2857
2858            if (!mOnlyCore) {
2859                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2860                mRequiredInstallerPackage = getRequiredInstallerLPr();
2861                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2862                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2863                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2864                        mIntentFilterVerifierComponent);
2865                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2866                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2867                        SharedLibraryInfo.VERSION_UNDEFINED);
2868                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2869                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2870                        SharedLibraryInfo.VERSION_UNDEFINED);
2871            } else {
2872                mRequiredVerifierPackage = null;
2873                mRequiredInstallerPackage = null;
2874                mRequiredUninstallerPackage = null;
2875                mIntentFilterVerifierComponent = null;
2876                mIntentFilterVerifier = null;
2877                mServicesSystemSharedLibraryPackageName = null;
2878                mSharedSystemSharedLibraryPackageName = null;
2879            }
2880
2881            mInstallerService = new PackageInstallerService(context, this);
2882
2883            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2884            if (ephemeralResolverComponent != null) {
2885                if (DEBUG_EPHEMERAL) {
2886                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2887                }
2888                mInstantAppResolverConnection =
2889                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2890            } else {
2891                mInstantAppResolverConnection = null;
2892            }
2893            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2894            if (mInstantAppInstallerComponent != null) {
2895                if (DEBUG_EPHEMERAL) {
2896                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2897                }
2898                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2899            }
2900
2901            // Read and update the usage of dex files.
2902            // Do this at the end of PM init so that all the packages have their
2903            // data directory reconciled.
2904            // At this point we know the code paths of the packages, so we can validate
2905            // the disk file and build the internal cache.
2906            // The usage file is expected to be small so loading and verifying it
2907            // should take a fairly small time compare to the other activities (e.g. package
2908            // scanning).
2909            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2910            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2911            for (int userId : currentUserIds) {
2912                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2913            }
2914            mDexManager.load(userPackages);
2915        } // synchronized (mPackages)
2916        } // synchronized (mInstallLock)
2917
2918        // Now after opening every single application zip, make sure they
2919        // are all flushed.  Not really needed, but keeps things nice and
2920        // tidy.
2921        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2922        Runtime.getRuntime().gc();
2923        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2924
2925        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2926        FallbackCategoryProvider.loadFallbacks();
2927        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2928
2929        // The initial scanning above does many calls into installd while
2930        // holding the mPackages lock, but we're mostly interested in yelling
2931        // once we have a booted system.
2932        mInstaller.setWarnIfHeld(mPackages);
2933
2934        // Expose private service for system components to use.
2935        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2936        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2937    }
2938
2939    private static File preparePackageParserCache(boolean isUpgrade) {
2940        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2941            return null;
2942        }
2943
2944        // Disable package parsing on eng builds to allow for faster incremental development.
2945        if ("eng".equals(Build.TYPE)) {
2946            return null;
2947        }
2948
2949        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2950            Slog.i(TAG, "Disabling package parser cache due to system property.");
2951            return null;
2952        }
2953
2954        // The base directory for the package parser cache lives under /data/system/.
2955        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2956                "package_cache");
2957        if (cacheBaseDir == null) {
2958            return null;
2959        }
2960
2961        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2962        // This also serves to "GC" unused entries when the package cache version changes (which
2963        // can only happen during upgrades).
2964        if (isUpgrade) {
2965            FileUtils.deleteContents(cacheBaseDir);
2966        }
2967
2968
2969        // Return the versioned package cache directory. This is something like
2970        // "/data/system/package_cache/1"
2971        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2972
2973        // The following is a workaround to aid development on non-numbered userdebug
2974        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2975        // the system partition is newer.
2976        //
2977        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2978        // that starts with "eng." to signify that this is an engineering build and not
2979        // destined for release.
2980        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2981            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2982
2983            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2984            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2985            // in general and should not be used for production changes. In this specific case,
2986            // we know that they will work.
2987            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2988            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2989                FileUtils.deleteContents(cacheBaseDir);
2990                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2991            }
2992        }
2993
2994        return cacheDir;
2995    }
2996
2997    @Override
2998    public boolean isFirstBoot() {
2999        return mFirstBoot;
3000    }
3001
3002    @Override
3003    public boolean isOnlyCoreApps() {
3004        return mOnlyCore;
3005    }
3006
3007    @Override
3008    public boolean isUpgrade() {
3009        return mIsUpgrade;
3010    }
3011
3012    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3013        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3014
3015        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3016                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3017                UserHandle.USER_SYSTEM);
3018        if (matches.size() == 1) {
3019            return matches.get(0).getComponentInfo().packageName;
3020        } else if (matches.size() == 0) {
3021            Log.e(TAG, "There should probably be a verifier, but, none were found");
3022            return null;
3023        }
3024        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3025    }
3026
3027    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3028        synchronized (mPackages) {
3029            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3030            if (libraryEntry == null) {
3031                throw new IllegalStateException("Missing required shared library:" + name);
3032            }
3033            return libraryEntry.apk;
3034        }
3035    }
3036
3037    private @NonNull String getRequiredInstallerLPr() {
3038        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3039        intent.addCategory(Intent.CATEGORY_DEFAULT);
3040        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3041
3042        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3043                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3044                UserHandle.USER_SYSTEM);
3045        if (matches.size() == 1) {
3046            ResolveInfo resolveInfo = matches.get(0);
3047            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3048                throw new RuntimeException("The installer must be a privileged app");
3049            }
3050            return matches.get(0).getComponentInfo().packageName;
3051        } else {
3052            throw new RuntimeException("There must be exactly one installer; found " + matches);
3053        }
3054    }
3055
3056    private @NonNull String getRequiredUninstallerLPr() {
3057        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3058        intent.addCategory(Intent.CATEGORY_DEFAULT);
3059        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3060
3061        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3062                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3063                UserHandle.USER_SYSTEM);
3064        if (resolveInfo == null ||
3065                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3066            throw new RuntimeException("There must be exactly one uninstaller; found "
3067                    + resolveInfo);
3068        }
3069        return resolveInfo.getComponentInfo().packageName;
3070    }
3071
3072    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3073        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3074
3075        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3076                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3077                UserHandle.USER_SYSTEM);
3078        ResolveInfo best = null;
3079        final int N = matches.size();
3080        for (int i = 0; i < N; i++) {
3081            final ResolveInfo cur = matches.get(i);
3082            final String packageName = cur.getComponentInfo().packageName;
3083            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3084                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3085                continue;
3086            }
3087
3088            if (best == null || cur.priority > best.priority) {
3089                best = cur;
3090            }
3091        }
3092
3093        if (best != null) {
3094            return best.getComponentInfo().getComponentName();
3095        } else {
3096            throw new RuntimeException("There must be at least one intent filter verifier");
3097        }
3098    }
3099
3100    private @Nullable ComponentName getEphemeralResolverLPr() {
3101        final String[] packageArray =
3102                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3103        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3104            if (DEBUG_EPHEMERAL) {
3105                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3106            }
3107            return null;
3108        }
3109
3110        final int resolveFlags =
3111                MATCH_DIRECT_BOOT_AWARE
3112                | MATCH_DIRECT_BOOT_UNAWARE
3113                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3114        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3115        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3116                resolveFlags, UserHandle.USER_SYSTEM);
3117
3118        final int N = resolvers.size();
3119        if (N == 0) {
3120            if (DEBUG_EPHEMERAL) {
3121                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3122            }
3123            return null;
3124        }
3125
3126        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3127        for (int i = 0; i < N; i++) {
3128            final ResolveInfo info = resolvers.get(i);
3129
3130            if (info.serviceInfo == null) {
3131                continue;
3132            }
3133
3134            final String packageName = info.serviceInfo.packageName;
3135            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3136                if (DEBUG_EPHEMERAL) {
3137                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3138                            + " pkg: " + packageName + ", info:" + info);
3139                }
3140                continue;
3141            }
3142
3143            if (DEBUG_EPHEMERAL) {
3144                Slog.v(TAG, "Ephemeral resolver found;"
3145                        + " pkg: " + packageName + ", info:" + info);
3146            }
3147            return new ComponentName(packageName, info.serviceInfo.name);
3148        }
3149        if (DEBUG_EPHEMERAL) {
3150            Slog.v(TAG, "Ephemeral resolver NOT found");
3151        }
3152        return null;
3153    }
3154
3155    private @Nullable ComponentName getEphemeralInstallerLPr() {
3156        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3157        intent.addCategory(Intent.CATEGORY_DEFAULT);
3158        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3159
3160        final int resolveFlags =
3161                MATCH_DIRECT_BOOT_AWARE
3162                | MATCH_DIRECT_BOOT_UNAWARE
3163                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3164        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3165                resolveFlags, UserHandle.USER_SYSTEM);
3166        Iterator<ResolveInfo> iter = matches.iterator();
3167        while (iter.hasNext()) {
3168            final ResolveInfo rInfo = iter.next();
3169            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3170            if (ps != null) {
3171                final PermissionsState permissionsState = ps.getPermissionsState();
3172                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3173                    continue;
3174                }
3175            }
3176            iter.remove();
3177        }
3178        if (matches.size() == 0) {
3179            return null;
3180        } else if (matches.size() == 1) {
3181            return matches.get(0).getComponentInfo().getComponentName();
3182        } else {
3183            throw new RuntimeException(
3184                    "There must be at most one ephemeral installer; found " + matches);
3185        }
3186    }
3187
3188    private void primeDomainVerificationsLPw(int userId) {
3189        if (DEBUG_DOMAIN_VERIFICATION) {
3190            Slog.d(TAG, "Priming domain verifications in user " + userId);
3191        }
3192
3193        SystemConfig systemConfig = SystemConfig.getInstance();
3194        ArraySet<String> packages = systemConfig.getLinkedApps();
3195
3196        for (String packageName : packages) {
3197            PackageParser.Package pkg = mPackages.get(packageName);
3198            if (pkg != null) {
3199                if (!pkg.isSystemApp()) {
3200                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3201                    continue;
3202                }
3203
3204                ArraySet<String> domains = null;
3205                for (PackageParser.Activity a : pkg.activities) {
3206                    for (ActivityIntentInfo filter : a.intents) {
3207                        if (hasValidDomains(filter)) {
3208                            if (domains == null) {
3209                                domains = new ArraySet<String>();
3210                            }
3211                            domains.addAll(filter.getHostsList());
3212                        }
3213                    }
3214                }
3215
3216                if (domains != null && domains.size() > 0) {
3217                    if (DEBUG_DOMAIN_VERIFICATION) {
3218                        Slog.v(TAG, "      + " + packageName);
3219                    }
3220                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3221                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3222                    // and then 'always' in the per-user state actually used for intent resolution.
3223                    final IntentFilterVerificationInfo ivi;
3224                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3225                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3226                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3227                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3228                } else {
3229                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3230                            + "' does not handle web links");
3231                }
3232            } else {
3233                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3234            }
3235        }
3236
3237        scheduleWritePackageRestrictionsLocked(userId);
3238        scheduleWriteSettingsLocked();
3239    }
3240
3241    private void applyFactoryDefaultBrowserLPw(int userId) {
3242        // The default browser app's package name is stored in a string resource,
3243        // with a product-specific overlay used for vendor customization.
3244        String browserPkg = mContext.getResources().getString(
3245                com.android.internal.R.string.default_browser);
3246        if (!TextUtils.isEmpty(browserPkg)) {
3247            // non-empty string => required to be a known package
3248            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3249            if (ps == null) {
3250                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3251                browserPkg = null;
3252            } else {
3253                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3254            }
3255        }
3256
3257        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3258        // default.  If there's more than one, just leave everything alone.
3259        if (browserPkg == null) {
3260            calculateDefaultBrowserLPw(userId);
3261        }
3262    }
3263
3264    private void calculateDefaultBrowserLPw(int userId) {
3265        List<String> allBrowsers = resolveAllBrowserApps(userId);
3266        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3267        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3268    }
3269
3270    private List<String> resolveAllBrowserApps(int userId) {
3271        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3272        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3273                PackageManager.MATCH_ALL, userId);
3274
3275        final int count = list.size();
3276        List<String> result = new ArrayList<String>(count);
3277        for (int i=0; i<count; i++) {
3278            ResolveInfo info = list.get(i);
3279            if (info.activityInfo == null
3280                    || !info.handleAllWebDataURI
3281                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3282                    || result.contains(info.activityInfo.packageName)) {
3283                continue;
3284            }
3285            result.add(info.activityInfo.packageName);
3286        }
3287
3288        return result;
3289    }
3290
3291    private boolean packageIsBrowser(String packageName, int userId) {
3292        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3293                PackageManager.MATCH_ALL, userId);
3294        final int N = list.size();
3295        for (int i = 0; i < N; i++) {
3296            ResolveInfo info = list.get(i);
3297            if (packageName.equals(info.activityInfo.packageName)) {
3298                return true;
3299            }
3300        }
3301        return false;
3302    }
3303
3304    private void checkDefaultBrowser() {
3305        final int myUserId = UserHandle.myUserId();
3306        final String packageName = getDefaultBrowserPackageName(myUserId);
3307        if (packageName != null) {
3308            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3309            if (info == null) {
3310                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3311                synchronized (mPackages) {
3312                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3313                }
3314            }
3315        }
3316    }
3317
3318    @Override
3319    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3320            throws RemoteException {
3321        try {
3322            return super.onTransact(code, data, reply, flags);
3323        } catch (RuntimeException e) {
3324            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3325                Slog.wtf(TAG, "Package Manager Crash", e);
3326            }
3327            throw e;
3328        }
3329    }
3330
3331    static int[] appendInts(int[] cur, int[] add) {
3332        if (add == null) return cur;
3333        if (cur == null) return add;
3334        final int N = add.length;
3335        for (int i=0; i<N; i++) {
3336            cur = appendInt(cur, add[i]);
3337        }
3338        return cur;
3339    }
3340
3341    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3342        if (!sUserManager.exists(userId)) return null;
3343        if (ps == null) {
3344            return null;
3345        }
3346        final PackageParser.Package p = ps.pkg;
3347        if (p == null) {
3348            return null;
3349        }
3350        // Filter out ephemeral app metadata:
3351        //   * The system/shell/root can see metadata for any app
3352        //   * An installed app can see metadata for 1) other installed apps
3353        //     and 2) ephemeral apps that have explicitly interacted with it
3354        //   * Ephemeral apps can only see their own metadata
3355        //   * Holding a signature permission allows seeing instant apps
3356        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3357        if (callingAppId != Process.SYSTEM_UID
3358                && callingAppId != Process.SHELL_UID
3359                && callingAppId != Process.ROOT_UID
3360                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3361                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3362            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3363            if (instantAppPackageName != null) {
3364                // ephemeral apps can only get information on themselves
3365                if (!instantAppPackageName.equals(p.packageName)) {
3366                    return null;
3367                }
3368            } else {
3369                if (ps.getInstantApp(userId)) {
3370                    // only get access to the ephemeral app if we've been granted access
3371                    if (!mInstantAppRegistry.isInstantAccessGranted(
3372                            userId, callingAppId, ps.appId)) {
3373                        return null;
3374                    }
3375                }
3376            }
3377        }
3378
3379        final PermissionsState permissionsState = ps.getPermissionsState();
3380
3381        // Compute GIDs only if requested
3382        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3383                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3384        // Compute granted permissions only if package has requested permissions
3385        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3386                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3387        final PackageUserState state = ps.readUserState(userId);
3388
3389        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3390                && ps.isSystem()) {
3391            flags |= MATCH_ANY_USER;
3392        }
3393
3394        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3395                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3396
3397        if (packageInfo == null) {
3398            return null;
3399        }
3400
3401        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3402
3403        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3404                resolveExternalPackageNameLPr(p);
3405
3406        return packageInfo;
3407    }
3408
3409    @Override
3410    public void checkPackageStartable(String packageName, int userId) {
3411        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3412
3413        synchronized (mPackages) {
3414            final PackageSetting ps = mSettings.mPackages.get(packageName);
3415            if (ps == null) {
3416                throw new SecurityException("Package " + packageName + " was not found!");
3417            }
3418
3419            if (!ps.getInstalled(userId)) {
3420                throw new SecurityException(
3421                        "Package " + packageName + " was not installed for user " + userId + "!");
3422            }
3423
3424            if (mSafeMode && !ps.isSystem()) {
3425                throw new SecurityException("Package " + packageName + " not a system app!");
3426            }
3427
3428            if (mFrozenPackages.contains(packageName)) {
3429                throw new SecurityException("Package " + packageName + " is currently frozen!");
3430            }
3431
3432            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3433                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3434                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3435            }
3436        }
3437    }
3438
3439    @Override
3440    public boolean isPackageAvailable(String packageName, int userId) {
3441        if (!sUserManager.exists(userId)) return false;
3442        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3443                false /* requireFullPermission */, false /* checkShell */, "is package available");
3444        synchronized (mPackages) {
3445            PackageParser.Package p = mPackages.get(packageName);
3446            if (p != null) {
3447                final PackageSetting ps = (PackageSetting) p.mExtras;
3448                if (ps != null) {
3449                    final PackageUserState state = ps.readUserState(userId);
3450                    if (state != null) {
3451                        return PackageParser.isAvailable(state);
3452                    }
3453                }
3454            }
3455        }
3456        return false;
3457    }
3458
3459    @Override
3460    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3461        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3462                flags, userId);
3463    }
3464
3465    @Override
3466    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3467            int flags, int userId) {
3468        return getPackageInfoInternal(versionedPackage.getPackageName(),
3469                // TODO: We will change version code to long, so in the new API it is long
3470                (int) versionedPackage.getVersionCode(), flags, userId);
3471    }
3472
3473    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3474            int flags, int userId) {
3475        if (!sUserManager.exists(userId)) return null;
3476        flags = updateFlagsForPackage(flags, userId, packageName);
3477        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3478                false /* requireFullPermission */, false /* checkShell */, "get package info");
3479
3480        // reader
3481        synchronized (mPackages) {
3482            // Normalize package name to handle renamed packages and static libs
3483            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3484
3485            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3486            if (matchFactoryOnly) {
3487                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3488                if (ps != null) {
3489                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3490                        return null;
3491                    }
3492                    return generatePackageInfo(ps, flags, userId);
3493                }
3494            }
3495
3496            PackageParser.Package p = mPackages.get(packageName);
3497            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3498                return null;
3499            }
3500            if (DEBUG_PACKAGE_INFO)
3501                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3502            if (p != null) {
3503                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3504                        Binder.getCallingUid(), userId)) {
3505                    return null;
3506                }
3507                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3508            }
3509            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3510                final PackageSetting ps = mSettings.mPackages.get(packageName);
3511                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3512                    return null;
3513                }
3514                return generatePackageInfo(ps, flags, userId);
3515            }
3516        }
3517        return null;
3518    }
3519
3520
3521    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3522        // System/shell/root get to see all static libs
3523        final int appId = UserHandle.getAppId(uid);
3524        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3525                || appId == Process.ROOT_UID) {
3526            return false;
3527        }
3528
3529        // No package means no static lib as it is always on internal storage
3530        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3531            return false;
3532        }
3533
3534        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3535                ps.pkg.staticSharedLibVersion);
3536        if (libEntry == null) {
3537            return false;
3538        }
3539
3540        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3541        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3542        if (uidPackageNames == null) {
3543            return true;
3544        }
3545
3546        for (String uidPackageName : uidPackageNames) {
3547            if (ps.name.equals(uidPackageName)) {
3548                return false;
3549            }
3550            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3551            if (uidPs != null) {
3552                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3553                        libEntry.info.getName());
3554                if (index < 0) {
3555                    continue;
3556                }
3557                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3558                    return false;
3559                }
3560            }
3561        }
3562        return true;
3563    }
3564
3565    @Override
3566    public String[] currentToCanonicalPackageNames(String[] names) {
3567        String[] out = new String[names.length];
3568        // reader
3569        synchronized (mPackages) {
3570            for (int i=names.length-1; i>=0; i--) {
3571                PackageSetting ps = mSettings.mPackages.get(names[i]);
3572                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3573            }
3574        }
3575        return out;
3576    }
3577
3578    @Override
3579    public String[] canonicalToCurrentPackageNames(String[] names) {
3580        String[] out = new String[names.length];
3581        // reader
3582        synchronized (mPackages) {
3583            for (int i=names.length-1; i>=0; i--) {
3584                String cur = mSettings.getRenamedPackageLPr(names[i]);
3585                out[i] = cur != null ? cur : names[i];
3586            }
3587        }
3588        return out;
3589    }
3590
3591    @Override
3592    public int getPackageUid(String packageName, int flags, int userId) {
3593        if (!sUserManager.exists(userId)) return -1;
3594        flags = updateFlagsForPackage(flags, userId, packageName);
3595        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3596                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3597
3598        // reader
3599        synchronized (mPackages) {
3600            final PackageParser.Package p = mPackages.get(packageName);
3601            if (p != null && p.isMatch(flags)) {
3602                return UserHandle.getUid(userId, p.applicationInfo.uid);
3603            }
3604            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3605                final PackageSetting ps = mSettings.mPackages.get(packageName);
3606                if (ps != null && ps.isMatch(flags)) {
3607                    return UserHandle.getUid(userId, ps.appId);
3608                }
3609            }
3610        }
3611
3612        return -1;
3613    }
3614
3615    @Override
3616    public int[] getPackageGids(String packageName, int flags, int userId) {
3617        if (!sUserManager.exists(userId)) return null;
3618        flags = updateFlagsForPackage(flags, userId, packageName);
3619        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3620                false /* requireFullPermission */, false /* checkShell */,
3621                "getPackageGids");
3622
3623        // reader
3624        synchronized (mPackages) {
3625            final PackageParser.Package p = mPackages.get(packageName);
3626            if (p != null && p.isMatch(flags)) {
3627                PackageSetting ps = (PackageSetting) p.mExtras;
3628                // TODO: Shouldn't this be checking for package installed state for userId and
3629                // return null?
3630                return ps.getPermissionsState().computeGids(userId);
3631            }
3632            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3633                final PackageSetting ps = mSettings.mPackages.get(packageName);
3634                if (ps != null && ps.isMatch(flags)) {
3635                    return ps.getPermissionsState().computeGids(userId);
3636                }
3637            }
3638        }
3639
3640        return null;
3641    }
3642
3643    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3644        if (bp.perm != null) {
3645            return PackageParser.generatePermissionInfo(bp.perm, flags);
3646        }
3647        PermissionInfo pi = new PermissionInfo();
3648        pi.name = bp.name;
3649        pi.packageName = bp.sourcePackage;
3650        pi.nonLocalizedLabel = bp.name;
3651        pi.protectionLevel = bp.protectionLevel;
3652        return pi;
3653    }
3654
3655    @Override
3656    public PermissionInfo getPermissionInfo(String name, int flags) {
3657        // reader
3658        synchronized (mPackages) {
3659            final BasePermission p = mSettings.mPermissions.get(name);
3660            if (p != null) {
3661                return generatePermissionInfo(p, flags);
3662            }
3663            return null;
3664        }
3665    }
3666
3667    @Override
3668    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3669            int flags) {
3670        // reader
3671        synchronized (mPackages) {
3672            if (group != null && !mPermissionGroups.containsKey(group)) {
3673                // This is thrown as NameNotFoundException
3674                return null;
3675            }
3676
3677            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3678            for (BasePermission p : mSettings.mPermissions.values()) {
3679                if (group == null) {
3680                    if (p.perm == null || p.perm.info.group == null) {
3681                        out.add(generatePermissionInfo(p, flags));
3682                    }
3683                } else {
3684                    if (p.perm != null && group.equals(p.perm.info.group)) {
3685                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3686                    }
3687                }
3688            }
3689            return new ParceledListSlice<>(out);
3690        }
3691    }
3692
3693    @Override
3694    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3695        // reader
3696        synchronized (mPackages) {
3697            return PackageParser.generatePermissionGroupInfo(
3698                    mPermissionGroups.get(name), flags);
3699        }
3700    }
3701
3702    @Override
3703    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3704        // reader
3705        synchronized (mPackages) {
3706            final int N = mPermissionGroups.size();
3707            ArrayList<PermissionGroupInfo> out
3708                    = new ArrayList<PermissionGroupInfo>(N);
3709            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3710                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3711            }
3712            return new ParceledListSlice<>(out);
3713        }
3714    }
3715
3716    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3717            int uid, int userId) {
3718        if (!sUserManager.exists(userId)) return null;
3719        PackageSetting ps = mSettings.mPackages.get(packageName);
3720        if (ps != null) {
3721            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3722                return null;
3723            }
3724            if (ps.pkg == null) {
3725                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3726                if (pInfo != null) {
3727                    return pInfo.applicationInfo;
3728                }
3729                return null;
3730            }
3731            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3732                    ps.readUserState(userId), userId);
3733            if (ai != null) {
3734                rebaseEnabledOverlays(ai, userId);
3735                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3736            }
3737            return ai;
3738        }
3739        return null;
3740    }
3741
3742    @Override
3743    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3744        if (!sUserManager.exists(userId)) return null;
3745        flags = updateFlagsForApplication(flags, userId, packageName);
3746        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3747                false /* requireFullPermission */, false /* checkShell */, "get application info");
3748
3749        // writer
3750        synchronized (mPackages) {
3751            // Normalize package name to handle renamed packages and static libs
3752            packageName = resolveInternalPackageNameLPr(packageName,
3753                    PackageManager.VERSION_CODE_HIGHEST);
3754
3755            PackageParser.Package p = mPackages.get(packageName);
3756            if (DEBUG_PACKAGE_INFO) Log.v(
3757                    TAG, "getApplicationInfo " + packageName
3758                    + ": " + p);
3759            if (p != null) {
3760                PackageSetting ps = mSettings.mPackages.get(packageName);
3761                if (ps == null) return null;
3762                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3763                    return null;
3764                }
3765                // Note: isEnabledLP() does not apply here - always return info
3766                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3767                        p, flags, ps.readUserState(userId), userId);
3768                if (ai != null) {
3769                    rebaseEnabledOverlays(ai, userId);
3770                    ai.packageName = resolveExternalPackageNameLPr(p);
3771                }
3772                return ai;
3773            }
3774            if ("android".equals(packageName)||"system".equals(packageName)) {
3775                return mAndroidApplication;
3776            }
3777            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3778                // Already generates the external package name
3779                return generateApplicationInfoFromSettingsLPw(packageName,
3780                        Binder.getCallingUid(), flags, userId);
3781            }
3782        }
3783        return null;
3784    }
3785
3786    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3787        List<String> paths = new ArrayList<>();
3788        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3789            mEnabledOverlayPaths.get(userId);
3790        if (userSpecificOverlays != null) {
3791            if (!"android".equals(ai.packageName)) {
3792                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3793                if (frameworkOverlays != null) {
3794                    paths.addAll(frameworkOverlays);
3795                }
3796            }
3797
3798            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3799            if (appOverlays != null) {
3800                paths.addAll(appOverlays);
3801            }
3802        }
3803        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3804    }
3805
3806    private String normalizePackageNameLPr(String packageName) {
3807        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3808        return normalizedPackageName != null ? normalizedPackageName : packageName;
3809    }
3810
3811    @Override
3812    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3813            final IPackageDataObserver observer) {
3814        mContext.enforceCallingOrSelfPermission(
3815                android.Manifest.permission.CLEAR_APP_CACHE, null);
3816        mHandler.post(() -> {
3817            boolean success = false;
3818            try {
3819                freeStorage(volumeUuid, freeStorageSize, 0);
3820                success = true;
3821            } catch (IOException e) {
3822                Slog.w(TAG, e);
3823            }
3824            if (observer != null) {
3825                try {
3826                    observer.onRemoveCompleted(null, success);
3827                } catch (RemoteException e) {
3828                    Slog.w(TAG, e);
3829                }
3830            }
3831        });
3832    }
3833
3834    @Override
3835    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3836            final IntentSender pi) {
3837        mContext.enforceCallingOrSelfPermission(
3838                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3839        mHandler.post(() -> {
3840            boolean success = false;
3841            try {
3842                freeStorage(volumeUuid, freeStorageSize, 0);
3843                success = true;
3844            } catch (IOException e) {
3845                Slog.w(TAG, e);
3846            }
3847            if (pi != null) {
3848                try {
3849                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3850                } catch (SendIntentException e) {
3851                    Slog.w(TAG, e);
3852                }
3853            }
3854        });
3855    }
3856
3857    /**
3858     * Blocking call to clear various types of cached data across the system
3859     * until the requested bytes are available.
3860     */
3861    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3862        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3863        final File file = storage.findPathForUuid(volumeUuid);
3864
3865        if (ENABLE_FREE_CACHE_V2) {
3866            final boolean aggressive = (storageFlags
3867                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3868
3869            // 1. Pre-flight to determine if we have any chance to succeed
3870            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3871
3872            // 3. Consider parsed APK data (aggressive only)
3873            if (aggressive) {
3874                FileUtils.deleteContents(mCacheDir);
3875            }
3876            if (file.getUsableSpace() >= bytes) return;
3877
3878            // 4. Consider cached app data (above quotas)
3879            try {
3880                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3881            } catch (InstallerException ignored) {
3882            }
3883            if (file.getUsableSpace() >= bytes) return;
3884
3885            // 5. Consider shared libraries with refcount=0 and age>2h
3886            // 6. Consider dexopt output (aggressive only)
3887            // 7. Consider ephemeral apps not used in last week
3888
3889            // 8. Consider cached app data (below quotas)
3890            try {
3891                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3892                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3893            } catch (InstallerException ignored) {
3894            }
3895            if (file.getUsableSpace() >= bytes) return;
3896
3897            // 9. Consider DropBox entries
3898            // 10. Consider ephemeral cookies
3899
3900        } else {
3901            try {
3902                mInstaller.freeCache(volumeUuid, bytes, 0);
3903            } catch (InstallerException ignored) {
3904            }
3905            if (file.getUsableSpace() >= bytes) return;
3906        }
3907
3908        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3909    }
3910
3911    /**
3912     * Update given flags based on encryption status of current user.
3913     */
3914    private int updateFlags(int flags, int userId) {
3915        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3916                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3917            // Caller expressed an explicit opinion about what encryption
3918            // aware/unaware components they want to see, so fall through and
3919            // give them what they want
3920        } else {
3921            // Caller expressed no opinion, so match based on user state
3922            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3923                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3924            } else {
3925                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3926            }
3927        }
3928        return flags;
3929    }
3930
3931    private UserManagerInternal getUserManagerInternal() {
3932        if (mUserManagerInternal == null) {
3933            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3934        }
3935        return mUserManagerInternal;
3936    }
3937
3938    private DeviceIdleController.LocalService getDeviceIdleController() {
3939        if (mDeviceIdleController == null) {
3940            mDeviceIdleController =
3941                    LocalServices.getService(DeviceIdleController.LocalService.class);
3942        }
3943        return mDeviceIdleController;
3944    }
3945
3946    /**
3947     * Update given flags when being used to request {@link PackageInfo}.
3948     */
3949    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3950        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3951        boolean triaged = true;
3952        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3953                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3954            // Caller is asking for component details, so they'd better be
3955            // asking for specific encryption matching behavior, or be triaged
3956            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3957                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3958                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3959                triaged = false;
3960            }
3961        }
3962        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3963                | PackageManager.MATCH_SYSTEM_ONLY
3964                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3965            triaged = false;
3966        }
3967        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3968            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3969                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3970                    + Debug.getCallers(5));
3971        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3972                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3973            // If the caller wants all packages and has a restricted profile associated with it,
3974            // then match all users. This is to make sure that launchers that need to access work
3975            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3976            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3977            flags |= PackageManager.MATCH_ANY_USER;
3978        }
3979        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3980            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3981                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3982        }
3983        return updateFlags(flags, userId);
3984    }
3985
3986    /**
3987     * Update given flags when being used to request {@link ApplicationInfo}.
3988     */
3989    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3990        return updateFlagsForPackage(flags, userId, cookie);
3991    }
3992
3993    /**
3994     * Update given flags when being used to request {@link ComponentInfo}.
3995     */
3996    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3997        if (cookie instanceof Intent) {
3998            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3999                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4000            }
4001        }
4002
4003        boolean triaged = true;
4004        // Caller is asking for component details, so they'd better be
4005        // asking for specific encryption matching behavior, or be triaged
4006        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4007                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4008                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4009            triaged = false;
4010        }
4011        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4012            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4013                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4014        }
4015
4016        return updateFlags(flags, userId);
4017    }
4018
4019    /**
4020     * Update given intent when being used to request {@link ResolveInfo}.
4021     */
4022    private Intent updateIntentForResolve(Intent intent) {
4023        if (intent.getSelector() != null) {
4024            intent = intent.getSelector();
4025        }
4026        if (DEBUG_PREFERRED) {
4027            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4028        }
4029        return intent;
4030    }
4031
4032    /**
4033     * Update given flags when being used to request {@link ResolveInfo}.
4034     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4035     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4036     * flag set. However, this flag is only honoured in three circumstances:
4037     * <ul>
4038     * <li>when called from a system process</li>
4039     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4040     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4041     * action and a {@code android.intent.category.BROWSABLE} category</li>
4042     * </ul>
4043     */
4044    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4045        // Safe mode means we shouldn't match any third-party components
4046        if (mSafeMode) {
4047            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4048        }
4049        final int callingUid = Binder.getCallingUid();
4050        if (getInstantAppPackageName(callingUid) != null) {
4051            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4052            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4053            flags |= PackageManager.MATCH_INSTANT;
4054        } else {
4055            // Otherwise, prevent leaking ephemeral components
4056            final boolean isSpecialProcess =
4057                    callingUid == Process.SYSTEM_UID
4058                    || callingUid == Process.SHELL_UID
4059                    || callingUid == 0;
4060            final boolean allowMatchInstant =
4061                    (includeInstantApp
4062                            && Intent.ACTION_VIEW.equals(intent.getAction())
4063                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4064                            && hasWebURI(intent))
4065                    || isSpecialProcess
4066                    || mContext.checkCallingOrSelfPermission(
4067                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4068            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4069            if (!allowMatchInstant) {
4070                flags &= ~PackageManager.MATCH_INSTANT;
4071            }
4072        }
4073        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4074    }
4075
4076    @Override
4077    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4078        if (!sUserManager.exists(userId)) return null;
4079        flags = updateFlagsForComponent(flags, userId, component);
4080        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4081                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4082        synchronized (mPackages) {
4083            PackageParser.Activity a = mActivities.mActivities.get(component);
4084
4085            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4086            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4087                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4088                if (ps == null) return null;
4089                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4090                        userId);
4091            }
4092            if (mResolveComponentName.equals(component)) {
4093                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4094                        new PackageUserState(), userId);
4095            }
4096        }
4097        return null;
4098    }
4099
4100    @Override
4101    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4102            String resolvedType) {
4103        synchronized (mPackages) {
4104            if (component.equals(mResolveComponentName)) {
4105                // The resolver supports EVERYTHING!
4106                return true;
4107            }
4108            PackageParser.Activity a = mActivities.mActivities.get(component);
4109            if (a == null) {
4110                return false;
4111            }
4112            for (int i=0; i<a.intents.size(); i++) {
4113                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4114                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4115                    return true;
4116                }
4117            }
4118            return false;
4119        }
4120    }
4121
4122    @Override
4123    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4124        if (!sUserManager.exists(userId)) return null;
4125        flags = updateFlagsForComponent(flags, userId, component);
4126        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4127                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4128        synchronized (mPackages) {
4129            PackageParser.Activity a = mReceivers.mActivities.get(component);
4130            if (DEBUG_PACKAGE_INFO) Log.v(
4131                TAG, "getReceiverInfo " + component + ": " + a);
4132            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4133                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4134                if (ps == null) return null;
4135                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4136                        ps.readUserState(userId), userId);
4137                if (ri != null) {
4138                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4139                }
4140                return ri;
4141            }
4142        }
4143        return null;
4144    }
4145
4146    @Override
4147    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4148        if (!sUserManager.exists(userId)) return null;
4149        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4150
4151        flags = updateFlagsForPackage(flags, userId, null);
4152
4153        final boolean canSeeStaticLibraries =
4154                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4155                        == PERMISSION_GRANTED
4156                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4157                        == PERMISSION_GRANTED
4158                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4159                        == PERMISSION_GRANTED
4160                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4161                        == PERMISSION_GRANTED;
4162
4163        synchronized (mPackages) {
4164            List<SharedLibraryInfo> result = null;
4165
4166            final int libCount = mSharedLibraries.size();
4167            for (int i = 0; i < libCount; i++) {
4168                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4169                if (versionedLib == null) {
4170                    continue;
4171                }
4172
4173                final int versionCount = versionedLib.size();
4174                for (int j = 0; j < versionCount; j++) {
4175                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4176                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4177                        break;
4178                    }
4179                    final long identity = Binder.clearCallingIdentity();
4180                    try {
4181                        // TODO: We will change version code to long, so in the new API it is long
4182                        PackageInfo packageInfo = getPackageInfoVersioned(
4183                                libInfo.getDeclaringPackage(), flags, userId);
4184                        if (packageInfo == null) {
4185                            continue;
4186                        }
4187                    } finally {
4188                        Binder.restoreCallingIdentity(identity);
4189                    }
4190
4191                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4192                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4193                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4194
4195                    if (result == null) {
4196                        result = new ArrayList<>();
4197                    }
4198                    result.add(resLibInfo);
4199                }
4200            }
4201
4202            return result != null ? new ParceledListSlice<>(result) : null;
4203        }
4204    }
4205
4206    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4207            SharedLibraryInfo libInfo, int flags, int userId) {
4208        List<VersionedPackage> versionedPackages = null;
4209        final int packageCount = mSettings.mPackages.size();
4210        for (int i = 0; i < packageCount; i++) {
4211            PackageSetting ps = mSettings.mPackages.valueAt(i);
4212
4213            if (ps == null) {
4214                continue;
4215            }
4216
4217            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4218                continue;
4219            }
4220
4221            final String libName = libInfo.getName();
4222            if (libInfo.isStatic()) {
4223                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4224                if (libIdx < 0) {
4225                    continue;
4226                }
4227                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4228                    continue;
4229                }
4230                if (versionedPackages == null) {
4231                    versionedPackages = new ArrayList<>();
4232                }
4233                // If the dependent is a static shared lib, use the public package name
4234                String dependentPackageName = ps.name;
4235                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4236                    dependentPackageName = ps.pkg.manifestPackageName;
4237                }
4238                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4239            } else if (ps.pkg != null) {
4240                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4241                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4242                    if (versionedPackages == null) {
4243                        versionedPackages = new ArrayList<>();
4244                    }
4245                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4246                }
4247            }
4248        }
4249
4250        return versionedPackages;
4251    }
4252
4253    @Override
4254    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4255        if (!sUserManager.exists(userId)) return null;
4256        flags = updateFlagsForComponent(flags, userId, component);
4257        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4258                false /* requireFullPermission */, false /* checkShell */, "get service info");
4259        synchronized (mPackages) {
4260            PackageParser.Service s = mServices.mServices.get(component);
4261            if (DEBUG_PACKAGE_INFO) Log.v(
4262                TAG, "getServiceInfo " + component + ": " + s);
4263            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4264                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4265                if (ps == null) return null;
4266                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4267                        ps.readUserState(userId), userId);
4268                if (si != null) {
4269                    rebaseEnabledOverlays(si.applicationInfo, userId);
4270                }
4271                return si;
4272            }
4273        }
4274        return null;
4275    }
4276
4277    @Override
4278    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4279        if (!sUserManager.exists(userId)) return null;
4280        flags = updateFlagsForComponent(flags, userId, component);
4281        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4282                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4283        synchronized (mPackages) {
4284            PackageParser.Provider p = mProviders.mProviders.get(component);
4285            if (DEBUG_PACKAGE_INFO) Log.v(
4286                TAG, "getProviderInfo " + component + ": " + p);
4287            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4288                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4289                if (ps == null) return null;
4290                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4291                        ps.readUserState(userId), userId);
4292                if (pi != null) {
4293                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4294                }
4295                return pi;
4296            }
4297        }
4298        return null;
4299    }
4300
4301    @Override
4302    public String[] getSystemSharedLibraryNames() {
4303        synchronized (mPackages) {
4304            Set<String> libs = null;
4305            final int libCount = mSharedLibraries.size();
4306            for (int i = 0; i < libCount; i++) {
4307                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4308                if (versionedLib == null) {
4309                    continue;
4310                }
4311                final int versionCount = versionedLib.size();
4312                for (int j = 0; j < versionCount; j++) {
4313                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4314                    if (!libEntry.info.isStatic()) {
4315                        if (libs == null) {
4316                            libs = new ArraySet<>();
4317                        }
4318                        libs.add(libEntry.info.getName());
4319                        break;
4320                    }
4321                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4322                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4323                            UserHandle.getUserId(Binder.getCallingUid()))) {
4324                        if (libs == null) {
4325                            libs = new ArraySet<>();
4326                        }
4327                        libs.add(libEntry.info.getName());
4328                        break;
4329                    }
4330                }
4331            }
4332
4333            if (libs != null) {
4334                String[] libsArray = new String[libs.size()];
4335                libs.toArray(libsArray);
4336                return libsArray;
4337            }
4338
4339            return null;
4340        }
4341    }
4342
4343    @Override
4344    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4345        synchronized (mPackages) {
4346            return mServicesSystemSharedLibraryPackageName;
4347        }
4348    }
4349
4350    @Override
4351    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4352        synchronized (mPackages) {
4353            return mSharedSystemSharedLibraryPackageName;
4354        }
4355    }
4356
4357    private void updateSequenceNumberLP(String packageName, int[] userList) {
4358        for (int i = userList.length - 1; i >= 0; --i) {
4359            final int userId = userList[i];
4360            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4361            if (changedPackages == null) {
4362                changedPackages = new SparseArray<>();
4363                mChangedPackages.put(userId, changedPackages);
4364            }
4365            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4366            if (sequenceNumbers == null) {
4367                sequenceNumbers = new HashMap<>();
4368                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4369            }
4370            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4371            if (sequenceNumber != null) {
4372                changedPackages.remove(sequenceNumber);
4373            }
4374            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4375            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4376        }
4377        mChangedPackagesSequenceNumber++;
4378    }
4379
4380    @Override
4381    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4382        synchronized (mPackages) {
4383            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4384                return null;
4385            }
4386            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4387            if (changedPackages == null) {
4388                return null;
4389            }
4390            final List<String> packageNames =
4391                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4392            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4393                final String packageName = changedPackages.get(i);
4394                if (packageName != null) {
4395                    packageNames.add(packageName);
4396                }
4397            }
4398            return packageNames.isEmpty()
4399                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4400        }
4401    }
4402
4403    @Override
4404    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4405        ArrayList<FeatureInfo> res;
4406        synchronized (mAvailableFeatures) {
4407            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4408            res.addAll(mAvailableFeatures.values());
4409        }
4410        final FeatureInfo fi = new FeatureInfo();
4411        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4412                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4413        res.add(fi);
4414
4415        return new ParceledListSlice<>(res);
4416    }
4417
4418    @Override
4419    public boolean hasSystemFeature(String name, int version) {
4420        synchronized (mAvailableFeatures) {
4421            final FeatureInfo feat = mAvailableFeatures.get(name);
4422            if (feat == null) {
4423                return false;
4424            } else {
4425                return feat.version >= version;
4426            }
4427        }
4428    }
4429
4430    @Override
4431    public int checkPermission(String permName, String pkgName, int userId) {
4432        if (!sUserManager.exists(userId)) {
4433            return PackageManager.PERMISSION_DENIED;
4434        }
4435
4436        synchronized (mPackages) {
4437            final PackageParser.Package p = mPackages.get(pkgName);
4438            if (p != null && p.mExtras != null) {
4439                final PackageSetting ps = (PackageSetting) p.mExtras;
4440                final PermissionsState permissionsState = ps.getPermissionsState();
4441                if (permissionsState.hasPermission(permName, userId)) {
4442                    return PackageManager.PERMISSION_GRANTED;
4443                }
4444                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4445                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4446                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4447                    return PackageManager.PERMISSION_GRANTED;
4448                }
4449            }
4450        }
4451
4452        return PackageManager.PERMISSION_DENIED;
4453    }
4454
4455    @Override
4456    public int checkUidPermission(String permName, int uid) {
4457        final int userId = UserHandle.getUserId(uid);
4458
4459        if (!sUserManager.exists(userId)) {
4460            return PackageManager.PERMISSION_DENIED;
4461        }
4462
4463        synchronized (mPackages) {
4464            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4465            if (obj != null) {
4466                final SettingBase ps = (SettingBase) obj;
4467                final PermissionsState permissionsState = ps.getPermissionsState();
4468                if (permissionsState.hasPermission(permName, userId)) {
4469                    return PackageManager.PERMISSION_GRANTED;
4470                }
4471                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4472                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4473                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4474                    return PackageManager.PERMISSION_GRANTED;
4475                }
4476            } else {
4477                ArraySet<String> perms = mSystemPermissions.get(uid);
4478                if (perms != null) {
4479                    if (perms.contains(permName)) {
4480                        return PackageManager.PERMISSION_GRANTED;
4481                    }
4482                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4483                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4484                        return PackageManager.PERMISSION_GRANTED;
4485                    }
4486                }
4487            }
4488        }
4489
4490        return PackageManager.PERMISSION_DENIED;
4491    }
4492
4493    @Override
4494    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4495        if (UserHandle.getCallingUserId() != userId) {
4496            mContext.enforceCallingPermission(
4497                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4498                    "isPermissionRevokedByPolicy for user " + userId);
4499        }
4500
4501        if (checkPermission(permission, packageName, userId)
4502                == PackageManager.PERMISSION_GRANTED) {
4503            return false;
4504        }
4505
4506        final long identity = Binder.clearCallingIdentity();
4507        try {
4508            final int flags = getPermissionFlags(permission, packageName, userId);
4509            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4510        } finally {
4511            Binder.restoreCallingIdentity(identity);
4512        }
4513    }
4514
4515    @Override
4516    public String getPermissionControllerPackageName() {
4517        synchronized (mPackages) {
4518            return mRequiredInstallerPackage;
4519        }
4520    }
4521
4522    /**
4523     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4524     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4525     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4526     * @param message the message to log on security exception
4527     */
4528    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4529            boolean checkShell, String message) {
4530        if (userId < 0) {
4531            throw new IllegalArgumentException("Invalid userId " + userId);
4532        }
4533        if (checkShell) {
4534            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4535        }
4536        if (userId == UserHandle.getUserId(callingUid)) return;
4537        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4538            if (requireFullPermission) {
4539                mContext.enforceCallingOrSelfPermission(
4540                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4541            } else {
4542                try {
4543                    mContext.enforceCallingOrSelfPermission(
4544                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4545                } catch (SecurityException se) {
4546                    mContext.enforceCallingOrSelfPermission(
4547                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4548                }
4549            }
4550        }
4551    }
4552
4553    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4554        if (callingUid == Process.SHELL_UID) {
4555            if (userHandle >= 0
4556                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4557                throw new SecurityException("Shell does not have permission to access user "
4558                        + userHandle);
4559            } else if (userHandle < 0) {
4560                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4561                        + Debug.getCallers(3));
4562            }
4563        }
4564    }
4565
4566    private BasePermission findPermissionTreeLP(String permName) {
4567        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4568            if (permName.startsWith(bp.name) &&
4569                    permName.length() > bp.name.length() &&
4570                    permName.charAt(bp.name.length()) == '.') {
4571                return bp;
4572            }
4573        }
4574        return null;
4575    }
4576
4577    private BasePermission checkPermissionTreeLP(String permName) {
4578        if (permName != null) {
4579            BasePermission bp = findPermissionTreeLP(permName);
4580            if (bp != null) {
4581                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4582                    return bp;
4583                }
4584                throw new SecurityException("Calling uid "
4585                        + Binder.getCallingUid()
4586                        + " is not allowed to add to permission tree "
4587                        + bp.name + " owned by uid " + bp.uid);
4588            }
4589        }
4590        throw new SecurityException("No permission tree found for " + permName);
4591    }
4592
4593    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4594        if (s1 == null) {
4595            return s2 == null;
4596        }
4597        if (s2 == null) {
4598            return false;
4599        }
4600        if (s1.getClass() != s2.getClass()) {
4601            return false;
4602        }
4603        return s1.equals(s2);
4604    }
4605
4606    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4607        if (pi1.icon != pi2.icon) return false;
4608        if (pi1.logo != pi2.logo) return false;
4609        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4610        if (!compareStrings(pi1.name, pi2.name)) return false;
4611        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4612        // We'll take care of setting this one.
4613        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4614        // These are not currently stored in settings.
4615        //if (!compareStrings(pi1.group, pi2.group)) return false;
4616        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4617        //if (pi1.labelRes != pi2.labelRes) return false;
4618        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4619        return true;
4620    }
4621
4622    int permissionInfoFootprint(PermissionInfo info) {
4623        int size = info.name.length();
4624        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4625        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4626        return size;
4627    }
4628
4629    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4630        int size = 0;
4631        for (BasePermission perm : mSettings.mPermissions.values()) {
4632            if (perm.uid == tree.uid) {
4633                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4634            }
4635        }
4636        return size;
4637    }
4638
4639    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4640        // We calculate the max size of permissions defined by this uid and throw
4641        // if that plus the size of 'info' would exceed our stated maximum.
4642        if (tree.uid != Process.SYSTEM_UID) {
4643            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4644            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4645                throw new SecurityException("Permission tree size cap exceeded");
4646            }
4647        }
4648    }
4649
4650    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4651        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4652            throw new SecurityException("Label must be specified in permission");
4653        }
4654        BasePermission tree = checkPermissionTreeLP(info.name);
4655        BasePermission bp = mSettings.mPermissions.get(info.name);
4656        boolean added = bp == null;
4657        boolean changed = true;
4658        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4659        if (added) {
4660            enforcePermissionCapLocked(info, tree);
4661            bp = new BasePermission(info.name, tree.sourcePackage,
4662                    BasePermission.TYPE_DYNAMIC);
4663        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4664            throw new SecurityException(
4665                    "Not allowed to modify non-dynamic permission "
4666                    + info.name);
4667        } else {
4668            if (bp.protectionLevel == fixedLevel
4669                    && bp.perm.owner.equals(tree.perm.owner)
4670                    && bp.uid == tree.uid
4671                    && comparePermissionInfos(bp.perm.info, info)) {
4672                changed = false;
4673            }
4674        }
4675        bp.protectionLevel = fixedLevel;
4676        info = new PermissionInfo(info);
4677        info.protectionLevel = fixedLevel;
4678        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4679        bp.perm.info.packageName = tree.perm.info.packageName;
4680        bp.uid = tree.uid;
4681        if (added) {
4682            mSettings.mPermissions.put(info.name, bp);
4683        }
4684        if (changed) {
4685            if (!async) {
4686                mSettings.writeLPr();
4687            } else {
4688                scheduleWriteSettingsLocked();
4689            }
4690        }
4691        return added;
4692    }
4693
4694    @Override
4695    public boolean addPermission(PermissionInfo info) {
4696        synchronized (mPackages) {
4697            return addPermissionLocked(info, false);
4698        }
4699    }
4700
4701    @Override
4702    public boolean addPermissionAsync(PermissionInfo info) {
4703        synchronized (mPackages) {
4704            return addPermissionLocked(info, true);
4705        }
4706    }
4707
4708    @Override
4709    public void removePermission(String name) {
4710        synchronized (mPackages) {
4711            checkPermissionTreeLP(name);
4712            BasePermission bp = mSettings.mPermissions.get(name);
4713            if (bp != null) {
4714                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4715                    throw new SecurityException(
4716                            "Not allowed to modify non-dynamic permission "
4717                            + name);
4718                }
4719                mSettings.mPermissions.remove(name);
4720                mSettings.writeLPr();
4721            }
4722        }
4723    }
4724
4725    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4726            BasePermission bp) {
4727        int index = pkg.requestedPermissions.indexOf(bp.name);
4728        if (index == -1) {
4729            throw new SecurityException("Package " + pkg.packageName
4730                    + " has not requested permission " + bp.name);
4731        }
4732        if (!bp.isRuntime() && !bp.isDevelopment()) {
4733            throw new SecurityException("Permission " + bp.name
4734                    + " is not a changeable permission type");
4735        }
4736    }
4737
4738    @Override
4739    public void grantRuntimePermission(String packageName, String name, final int userId) {
4740        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4741    }
4742
4743    private void grantRuntimePermission(String packageName, String name, final int userId,
4744            boolean overridePolicy) {
4745        if (!sUserManager.exists(userId)) {
4746            Log.e(TAG, "No such user:" + userId);
4747            return;
4748        }
4749
4750        mContext.enforceCallingOrSelfPermission(
4751                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4752                "grantRuntimePermission");
4753
4754        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4755                true /* requireFullPermission */, true /* checkShell */,
4756                "grantRuntimePermission");
4757
4758        final int uid;
4759        final SettingBase sb;
4760
4761        synchronized (mPackages) {
4762            final PackageParser.Package pkg = mPackages.get(packageName);
4763            if (pkg == null) {
4764                throw new IllegalArgumentException("Unknown package: " + packageName);
4765            }
4766
4767            final BasePermission bp = mSettings.mPermissions.get(name);
4768            if (bp == null) {
4769                throw new IllegalArgumentException("Unknown permission: " + name);
4770            }
4771
4772            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4773
4774            // If a permission review is required for legacy apps we represent
4775            // their permissions as always granted runtime ones since we need
4776            // to keep the review required permission flag per user while an
4777            // install permission's state is shared across all users.
4778            if (mPermissionReviewRequired
4779                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4780                    && bp.isRuntime()) {
4781                return;
4782            }
4783
4784            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4785            sb = (SettingBase) pkg.mExtras;
4786            if (sb == null) {
4787                throw new IllegalArgumentException("Unknown package: " + packageName);
4788            }
4789
4790            final PermissionsState permissionsState = sb.getPermissionsState();
4791
4792            final int flags = permissionsState.getPermissionFlags(name, userId);
4793            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4794                throw new SecurityException("Cannot grant system fixed permission "
4795                        + name + " for package " + packageName);
4796            }
4797            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4798                throw new SecurityException("Cannot grant policy fixed permission "
4799                        + name + " for package " + packageName);
4800            }
4801
4802            if (bp.isDevelopment()) {
4803                // Development permissions must be handled specially, since they are not
4804                // normal runtime permissions.  For now they apply to all users.
4805                if (permissionsState.grantInstallPermission(bp) !=
4806                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4807                    scheduleWriteSettingsLocked();
4808                }
4809                return;
4810            }
4811
4812            final PackageSetting ps = mSettings.mPackages.get(packageName);
4813            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4814                throw new SecurityException("Cannot grant non-ephemeral permission"
4815                        + name + " for package " + packageName);
4816            }
4817
4818            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4819                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4820                return;
4821            }
4822
4823            final int result = permissionsState.grantRuntimePermission(bp, userId);
4824            switch (result) {
4825                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4826                    return;
4827                }
4828
4829                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4830                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4831                    mHandler.post(new Runnable() {
4832                        @Override
4833                        public void run() {
4834                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4835                        }
4836                    });
4837                }
4838                break;
4839            }
4840
4841            if (bp.isRuntime()) {
4842                logPermissionGranted(mContext, name, packageName);
4843            }
4844
4845            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4846
4847            // Not critical if that is lost - app has to request again.
4848            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4849        }
4850
4851        // Only need to do this if user is initialized. Otherwise it's a new user
4852        // and there are no processes running as the user yet and there's no need
4853        // to make an expensive call to remount processes for the changed permissions.
4854        if (READ_EXTERNAL_STORAGE.equals(name)
4855                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4856            final long token = Binder.clearCallingIdentity();
4857            try {
4858                if (sUserManager.isInitialized(userId)) {
4859                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4860                            StorageManagerInternal.class);
4861                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4862                }
4863            } finally {
4864                Binder.restoreCallingIdentity(token);
4865            }
4866        }
4867    }
4868
4869    @Override
4870    public void revokeRuntimePermission(String packageName, String name, int userId) {
4871        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4872    }
4873
4874    private void revokeRuntimePermission(String packageName, String name, int userId,
4875            boolean overridePolicy) {
4876        if (!sUserManager.exists(userId)) {
4877            Log.e(TAG, "No such user:" + userId);
4878            return;
4879        }
4880
4881        mContext.enforceCallingOrSelfPermission(
4882                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4883                "revokeRuntimePermission");
4884
4885        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4886                true /* requireFullPermission */, true /* checkShell */,
4887                "revokeRuntimePermission");
4888
4889        final int appId;
4890
4891        synchronized (mPackages) {
4892            final PackageParser.Package pkg = mPackages.get(packageName);
4893            if (pkg == null) {
4894                throw new IllegalArgumentException("Unknown package: " + packageName);
4895            }
4896
4897            final BasePermission bp = mSettings.mPermissions.get(name);
4898            if (bp == null) {
4899                throw new IllegalArgumentException("Unknown permission: " + name);
4900            }
4901
4902            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4903
4904            // If a permission review is required for legacy apps we represent
4905            // their permissions as always granted runtime ones since we need
4906            // to keep the review required permission flag per user while an
4907            // install permission's state is shared across all users.
4908            if (mPermissionReviewRequired
4909                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4910                    && bp.isRuntime()) {
4911                return;
4912            }
4913
4914            SettingBase sb = (SettingBase) pkg.mExtras;
4915            if (sb == null) {
4916                throw new IllegalArgumentException("Unknown package: " + packageName);
4917            }
4918
4919            final PermissionsState permissionsState = sb.getPermissionsState();
4920
4921            final int flags = permissionsState.getPermissionFlags(name, userId);
4922            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4923                throw new SecurityException("Cannot revoke system fixed permission "
4924                        + name + " for package " + packageName);
4925            }
4926            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4927                throw new SecurityException("Cannot revoke policy fixed permission "
4928                        + name + " for package " + packageName);
4929            }
4930
4931            if (bp.isDevelopment()) {
4932                // Development permissions must be handled specially, since they are not
4933                // normal runtime permissions.  For now they apply to all users.
4934                if (permissionsState.revokeInstallPermission(bp) !=
4935                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4936                    scheduleWriteSettingsLocked();
4937                }
4938                return;
4939            }
4940
4941            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4942                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4943                return;
4944            }
4945
4946            if (bp.isRuntime()) {
4947                logPermissionRevoked(mContext, name, packageName);
4948            }
4949
4950            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4951
4952            // Critical, after this call app should never have the permission.
4953            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4954
4955            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4956        }
4957
4958        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4959    }
4960
4961    /**
4962     * Get the first event id for the permission.
4963     *
4964     * <p>There are four events for each permission: <ul>
4965     *     <li>Request permission: first id + 0</li>
4966     *     <li>Grant permission: first id + 1</li>
4967     *     <li>Request for permission denied: first id + 2</li>
4968     *     <li>Revoke permission: first id + 3</li>
4969     * </ul></p>
4970     *
4971     * @param name name of the permission
4972     *
4973     * @return The first event id for the permission
4974     */
4975    private static int getBaseEventId(@NonNull String name) {
4976        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4977
4978        if (eventIdIndex == -1) {
4979            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4980                    || "user".equals(Build.TYPE)) {
4981                Log.i(TAG, "Unknown permission " + name);
4982
4983                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4984            } else {
4985                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4986                //
4987                // Also update
4988                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4989                // - metrics_constants.proto
4990                throw new IllegalStateException("Unknown permission " + name);
4991            }
4992        }
4993
4994        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4995    }
4996
4997    /**
4998     * Log that a permission was revoked.
4999     *
5000     * @param context Context of the caller
5001     * @param name name of the permission
5002     * @param packageName package permission if for
5003     */
5004    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5005            @NonNull String packageName) {
5006        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5007    }
5008
5009    /**
5010     * Log that a permission request was granted.
5011     *
5012     * @param context Context of the caller
5013     * @param name name of the permission
5014     * @param packageName package permission if for
5015     */
5016    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5017            @NonNull String packageName) {
5018        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5019    }
5020
5021    @Override
5022    public void resetRuntimePermissions() {
5023        mContext.enforceCallingOrSelfPermission(
5024                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5025                "revokeRuntimePermission");
5026
5027        int callingUid = Binder.getCallingUid();
5028        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5029            mContext.enforceCallingOrSelfPermission(
5030                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5031                    "resetRuntimePermissions");
5032        }
5033
5034        synchronized (mPackages) {
5035            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5036            for (int userId : UserManagerService.getInstance().getUserIds()) {
5037                final int packageCount = mPackages.size();
5038                for (int i = 0; i < packageCount; i++) {
5039                    PackageParser.Package pkg = mPackages.valueAt(i);
5040                    if (!(pkg.mExtras instanceof PackageSetting)) {
5041                        continue;
5042                    }
5043                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5044                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5045                }
5046            }
5047        }
5048    }
5049
5050    @Override
5051    public int getPermissionFlags(String name, String packageName, int userId) {
5052        if (!sUserManager.exists(userId)) {
5053            return 0;
5054        }
5055
5056        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5057
5058        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5059                true /* requireFullPermission */, false /* checkShell */,
5060                "getPermissionFlags");
5061
5062        synchronized (mPackages) {
5063            final PackageParser.Package pkg = mPackages.get(packageName);
5064            if (pkg == null) {
5065                return 0;
5066            }
5067
5068            final BasePermission bp = mSettings.mPermissions.get(name);
5069            if (bp == null) {
5070                return 0;
5071            }
5072
5073            SettingBase sb = (SettingBase) pkg.mExtras;
5074            if (sb == null) {
5075                return 0;
5076            }
5077
5078            PermissionsState permissionsState = sb.getPermissionsState();
5079            return permissionsState.getPermissionFlags(name, userId);
5080        }
5081    }
5082
5083    @Override
5084    public void updatePermissionFlags(String name, String packageName, int flagMask,
5085            int flagValues, int userId) {
5086        if (!sUserManager.exists(userId)) {
5087            return;
5088        }
5089
5090        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5091
5092        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5093                true /* requireFullPermission */, true /* checkShell */,
5094                "updatePermissionFlags");
5095
5096        // Only the system can change these flags and nothing else.
5097        if (getCallingUid() != Process.SYSTEM_UID) {
5098            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5099            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5100            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5101            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5102            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5103        }
5104
5105        synchronized (mPackages) {
5106            final PackageParser.Package pkg = mPackages.get(packageName);
5107            if (pkg == null) {
5108                throw new IllegalArgumentException("Unknown package: " + packageName);
5109            }
5110
5111            final BasePermission bp = mSettings.mPermissions.get(name);
5112            if (bp == null) {
5113                throw new IllegalArgumentException("Unknown permission: " + name);
5114            }
5115
5116            SettingBase sb = (SettingBase) pkg.mExtras;
5117            if (sb == null) {
5118                throw new IllegalArgumentException("Unknown package: " + packageName);
5119            }
5120
5121            PermissionsState permissionsState = sb.getPermissionsState();
5122
5123            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5124
5125            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5126                // Install and runtime permissions are stored in different places,
5127                // so figure out what permission changed and persist the change.
5128                if (permissionsState.getInstallPermissionState(name) != null) {
5129                    scheduleWriteSettingsLocked();
5130                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5131                        || hadState) {
5132                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5133                }
5134            }
5135        }
5136    }
5137
5138    /**
5139     * Update the permission flags for all packages and runtime permissions of a user in order
5140     * to allow device or profile owner to remove POLICY_FIXED.
5141     */
5142    @Override
5143    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5144        if (!sUserManager.exists(userId)) {
5145            return;
5146        }
5147
5148        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5149
5150        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5151                true /* requireFullPermission */, true /* checkShell */,
5152                "updatePermissionFlagsForAllApps");
5153
5154        // Only the system can change system fixed flags.
5155        if (getCallingUid() != Process.SYSTEM_UID) {
5156            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5157            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5158        }
5159
5160        synchronized (mPackages) {
5161            boolean changed = false;
5162            final int packageCount = mPackages.size();
5163            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5164                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5165                SettingBase sb = (SettingBase) pkg.mExtras;
5166                if (sb == null) {
5167                    continue;
5168                }
5169                PermissionsState permissionsState = sb.getPermissionsState();
5170                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5171                        userId, flagMask, flagValues);
5172            }
5173            if (changed) {
5174                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5175            }
5176        }
5177    }
5178
5179    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5180        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5181                != PackageManager.PERMISSION_GRANTED
5182            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5183                != PackageManager.PERMISSION_GRANTED) {
5184            throw new SecurityException(message + " requires "
5185                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5186                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5187        }
5188    }
5189
5190    @Override
5191    public boolean shouldShowRequestPermissionRationale(String permissionName,
5192            String packageName, int userId) {
5193        if (UserHandle.getCallingUserId() != userId) {
5194            mContext.enforceCallingPermission(
5195                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5196                    "canShowRequestPermissionRationale for user " + userId);
5197        }
5198
5199        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5200        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5201            return false;
5202        }
5203
5204        if (checkPermission(permissionName, packageName, userId)
5205                == PackageManager.PERMISSION_GRANTED) {
5206            return false;
5207        }
5208
5209        final int flags;
5210
5211        final long identity = Binder.clearCallingIdentity();
5212        try {
5213            flags = getPermissionFlags(permissionName,
5214                    packageName, userId);
5215        } finally {
5216            Binder.restoreCallingIdentity(identity);
5217        }
5218
5219        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5220                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5221                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5222
5223        if ((flags & fixedFlags) != 0) {
5224            return false;
5225        }
5226
5227        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5228    }
5229
5230    @Override
5231    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5232        mContext.enforceCallingOrSelfPermission(
5233                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5234                "addOnPermissionsChangeListener");
5235
5236        synchronized (mPackages) {
5237            mOnPermissionChangeListeners.addListenerLocked(listener);
5238        }
5239    }
5240
5241    @Override
5242    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5243        synchronized (mPackages) {
5244            mOnPermissionChangeListeners.removeListenerLocked(listener);
5245        }
5246    }
5247
5248    @Override
5249    public boolean isProtectedBroadcast(String actionName) {
5250        synchronized (mPackages) {
5251            if (mProtectedBroadcasts.contains(actionName)) {
5252                return true;
5253            } else if (actionName != null) {
5254                // TODO: remove these terrible hacks
5255                if (actionName.startsWith("android.net.netmon.lingerExpired")
5256                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5257                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5258                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5259                    return true;
5260                }
5261            }
5262        }
5263        return false;
5264    }
5265
5266    @Override
5267    public int checkSignatures(String pkg1, String pkg2) {
5268        synchronized (mPackages) {
5269            final PackageParser.Package p1 = mPackages.get(pkg1);
5270            final PackageParser.Package p2 = mPackages.get(pkg2);
5271            if (p1 == null || p1.mExtras == null
5272                    || p2 == null || p2.mExtras == null) {
5273                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5274            }
5275            return compareSignatures(p1.mSignatures, p2.mSignatures);
5276        }
5277    }
5278
5279    @Override
5280    public int checkUidSignatures(int uid1, int uid2) {
5281        // Map to base uids.
5282        uid1 = UserHandle.getAppId(uid1);
5283        uid2 = UserHandle.getAppId(uid2);
5284        // reader
5285        synchronized (mPackages) {
5286            Signature[] s1;
5287            Signature[] s2;
5288            Object obj = mSettings.getUserIdLPr(uid1);
5289            if (obj != null) {
5290                if (obj instanceof SharedUserSetting) {
5291                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5292                } else if (obj instanceof PackageSetting) {
5293                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5294                } else {
5295                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5296                }
5297            } else {
5298                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5299            }
5300            obj = mSettings.getUserIdLPr(uid2);
5301            if (obj != null) {
5302                if (obj instanceof SharedUserSetting) {
5303                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5304                } else if (obj instanceof PackageSetting) {
5305                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5306                } else {
5307                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5308                }
5309            } else {
5310                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5311            }
5312            return compareSignatures(s1, s2);
5313        }
5314    }
5315
5316    /**
5317     * This method should typically only be used when granting or revoking
5318     * permissions, since the app may immediately restart after this call.
5319     * <p>
5320     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5321     * guard your work against the app being relaunched.
5322     */
5323    private void killUid(int appId, int userId, String reason) {
5324        final long identity = Binder.clearCallingIdentity();
5325        try {
5326            IActivityManager am = ActivityManager.getService();
5327            if (am != null) {
5328                try {
5329                    am.killUid(appId, userId, reason);
5330                } catch (RemoteException e) {
5331                    /* ignore - same process */
5332                }
5333            }
5334        } finally {
5335            Binder.restoreCallingIdentity(identity);
5336        }
5337    }
5338
5339    /**
5340     * Compares two sets of signatures. Returns:
5341     * <br />
5342     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5343     * <br />
5344     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5345     * <br />
5346     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5347     * <br />
5348     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5349     * <br />
5350     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5351     */
5352    static int compareSignatures(Signature[] s1, Signature[] s2) {
5353        if (s1 == null) {
5354            return s2 == null
5355                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5356                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5357        }
5358
5359        if (s2 == null) {
5360            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5361        }
5362
5363        if (s1.length != s2.length) {
5364            return PackageManager.SIGNATURE_NO_MATCH;
5365        }
5366
5367        // Since both signature sets are of size 1, we can compare without HashSets.
5368        if (s1.length == 1) {
5369            return s1[0].equals(s2[0]) ?
5370                    PackageManager.SIGNATURE_MATCH :
5371                    PackageManager.SIGNATURE_NO_MATCH;
5372        }
5373
5374        ArraySet<Signature> set1 = new ArraySet<Signature>();
5375        for (Signature sig : s1) {
5376            set1.add(sig);
5377        }
5378        ArraySet<Signature> set2 = new ArraySet<Signature>();
5379        for (Signature sig : s2) {
5380            set2.add(sig);
5381        }
5382        // Make sure s2 contains all signatures in s1.
5383        if (set1.equals(set2)) {
5384            return PackageManager.SIGNATURE_MATCH;
5385        }
5386        return PackageManager.SIGNATURE_NO_MATCH;
5387    }
5388
5389    /**
5390     * If the database version for this type of package (internal storage or
5391     * external storage) is less than the version where package signatures
5392     * were updated, return true.
5393     */
5394    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5395        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5396        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5397    }
5398
5399    /**
5400     * Used for backward compatibility to make sure any packages with
5401     * certificate chains get upgraded to the new style. {@code existingSigs}
5402     * will be in the old format (since they were stored on disk from before the
5403     * system upgrade) and {@code scannedSigs} will be in the newer format.
5404     */
5405    private int compareSignaturesCompat(PackageSignatures existingSigs,
5406            PackageParser.Package scannedPkg) {
5407        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5408            return PackageManager.SIGNATURE_NO_MATCH;
5409        }
5410
5411        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5412        for (Signature sig : existingSigs.mSignatures) {
5413            existingSet.add(sig);
5414        }
5415        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5416        for (Signature sig : scannedPkg.mSignatures) {
5417            try {
5418                Signature[] chainSignatures = sig.getChainSignatures();
5419                for (Signature chainSig : chainSignatures) {
5420                    scannedCompatSet.add(chainSig);
5421                }
5422            } catch (CertificateEncodingException e) {
5423                scannedCompatSet.add(sig);
5424            }
5425        }
5426        /*
5427         * Make sure the expanded scanned set contains all signatures in the
5428         * existing one.
5429         */
5430        if (scannedCompatSet.equals(existingSet)) {
5431            // Migrate the old signatures to the new scheme.
5432            existingSigs.assignSignatures(scannedPkg.mSignatures);
5433            // The new KeySets will be re-added later in the scanning process.
5434            synchronized (mPackages) {
5435                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5436            }
5437            return PackageManager.SIGNATURE_MATCH;
5438        }
5439        return PackageManager.SIGNATURE_NO_MATCH;
5440    }
5441
5442    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5443        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5444        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5445    }
5446
5447    private int compareSignaturesRecover(PackageSignatures existingSigs,
5448            PackageParser.Package scannedPkg) {
5449        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5450            return PackageManager.SIGNATURE_NO_MATCH;
5451        }
5452
5453        String msg = null;
5454        try {
5455            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5456                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5457                        + scannedPkg.packageName);
5458                return PackageManager.SIGNATURE_MATCH;
5459            }
5460        } catch (CertificateException e) {
5461            msg = e.getMessage();
5462        }
5463
5464        logCriticalInfo(Log.INFO,
5465                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5466        return PackageManager.SIGNATURE_NO_MATCH;
5467    }
5468
5469    @Override
5470    public List<String> getAllPackages() {
5471        synchronized (mPackages) {
5472            return new ArrayList<String>(mPackages.keySet());
5473        }
5474    }
5475
5476    @Override
5477    public String[] getPackagesForUid(int uid) {
5478        final int userId = UserHandle.getUserId(uid);
5479        uid = UserHandle.getAppId(uid);
5480        // reader
5481        synchronized (mPackages) {
5482            Object obj = mSettings.getUserIdLPr(uid);
5483            if (obj instanceof SharedUserSetting) {
5484                final SharedUserSetting sus = (SharedUserSetting) obj;
5485                final int N = sus.packages.size();
5486                String[] res = new String[N];
5487                final Iterator<PackageSetting> it = sus.packages.iterator();
5488                int i = 0;
5489                while (it.hasNext()) {
5490                    PackageSetting ps = it.next();
5491                    if (ps.getInstalled(userId)) {
5492                        res[i++] = ps.name;
5493                    } else {
5494                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5495                    }
5496                }
5497                return res;
5498            } else if (obj instanceof PackageSetting) {
5499                final PackageSetting ps = (PackageSetting) obj;
5500                if (ps.getInstalled(userId)) {
5501                    return new String[]{ps.name};
5502                }
5503            }
5504        }
5505        return null;
5506    }
5507
5508    @Override
5509    public String getNameForUid(int uid) {
5510        // reader
5511        synchronized (mPackages) {
5512            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5513            if (obj instanceof SharedUserSetting) {
5514                final SharedUserSetting sus = (SharedUserSetting) obj;
5515                return sus.name + ":" + sus.userId;
5516            } else if (obj instanceof PackageSetting) {
5517                final PackageSetting ps = (PackageSetting) obj;
5518                return ps.name;
5519            }
5520        }
5521        return null;
5522    }
5523
5524    @Override
5525    public int getUidForSharedUser(String sharedUserName) {
5526        if(sharedUserName == null) {
5527            return -1;
5528        }
5529        // reader
5530        synchronized (mPackages) {
5531            SharedUserSetting suid;
5532            try {
5533                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5534                if (suid != null) {
5535                    return suid.userId;
5536                }
5537            } catch (PackageManagerException ignore) {
5538                // can't happen, but, still need to catch it
5539            }
5540            return -1;
5541        }
5542    }
5543
5544    @Override
5545    public int getFlagsForUid(int uid) {
5546        synchronized (mPackages) {
5547            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5548            if (obj instanceof SharedUserSetting) {
5549                final SharedUserSetting sus = (SharedUserSetting) obj;
5550                return sus.pkgFlags;
5551            } else if (obj instanceof PackageSetting) {
5552                final PackageSetting ps = (PackageSetting) obj;
5553                return ps.pkgFlags;
5554            }
5555        }
5556        return 0;
5557    }
5558
5559    @Override
5560    public int getPrivateFlagsForUid(int uid) {
5561        synchronized (mPackages) {
5562            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5563            if (obj instanceof SharedUserSetting) {
5564                final SharedUserSetting sus = (SharedUserSetting) obj;
5565                return sus.pkgPrivateFlags;
5566            } else if (obj instanceof PackageSetting) {
5567                final PackageSetting ps = (PackageSetting) obj;
5568                return ps.pkgPrivateFlags;
5569            }
5570        }
5571        return 0;
5572    }
5573
5574    @Override
5575    public boolean isUidPrivileged(int uid) {
5576        uid = UserHandle.getAppId(uid);
5577        // reader
5578        synchronized (mPackages) {
5579            Object obj = mSettings.getUserIdLPr(uid);
5580            if (obj instanceof SharedUserSetting) {
5581                final SharedUserSetting sus = (SharedUserSetting) obj;
5582                final Iterator<PackageSetting> it = sus.packages.iterator();
5583                while (it.hasNext()) {
5584                    if (it.next().isPrivileged()) {
5585                        return true;
5586                    }
5587                }
5588            } else if (obj instanceof PackageSetting) {
5589                final PackageSetting ps = (PackageSetting) obj;
5590                return ps.isPrivileged();
5591            }
5592        }
5593        return false;
5594    }
5595
5596    @Override
5597    public String[] getAppOpPermissionPackages(String permissionName) {
5598        synchronized (mPackages) {
5599            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5600            if (pkgs == null) {
5601                return null;
5602            }
5603            return pkgs.toArray(new String[pkgs.size()]);
5604        }
5605    }
5606
5607    @Override
5608    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5609            int flags, int userId) {
5610        return resolveIntentInternal(
5611                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5612    }
5613
5614    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5615            int flags, int userId, boolean includeInstantApp) {
5616        try {
5617            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5618
5619            if (!sUserManager.exists(userId)) return null;
5620            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5621            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5622                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5623
5624            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5625            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5626                    flags, userId, includeInstantApp);
5627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5628
5629            final ResolveInfo bestChoice =
5630                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5631            return bestChoice;
5632        } finally {
5633            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5634        }
5635    }
5636
5637    @Override
5638    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5639        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5640            throw new SecurityException(
5641                    "findPersistentPreferredActivity can only be run by the system");
5642        }
5643        if (!sUserManager.exists(userId)) {
5644            return null;
5645        }
5646        intent = updateIntentForResolve(intent);
5647        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5648        final int flags = updateFlagsForResolve(0, userId, intent, false);
5649        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5650                userId);
5651        synchronized (mPackages) {
5652            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5653                    userId);
5654        }
5655    }
5656
5657    @Override
5658    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5659            IntentFilter filter, int match, ComponentName activity) {
5660        final int userId = UserHandle.getCallingUserId();
5661        if (DEBUG_PREFERRED) {
5662            Log.v(TAG, "setLastChosenActivity intent=" + intent
5663                + " resolvedType=" + resolvedType
5664                + " flags=" + flags
5665                + " filter=" + filter
5666                + " match=" + match
5667                + " activity=" + activity);
5668            filter.dump(new PrintStreamPrinter(System.out), "    ");
5669        }
5670        intent.setComponent(null);
5671        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5672                userId);
5673        // Find any earlier preferred or last chosen entries and nuke them
5674        findPreferredActivity(intent, resolvedType,
5675                flags, query, 0, false, true, false, userId);
5676        // Add the new activity as the last chosen for this filter
5677        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5678                "Setting last chosen");
5679    }
5680
5681    @Override
5682    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5683        final int userId = UserHandle.getCallingUserId();
5684        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5685        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5686                userId);
5687        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5688                false, false, false, userId);
5689    }
5690
5691    /**
5692     * Returns whether or not instant apps have been disabled remotely.
5693     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5694     * held. Otherwise we run the risk of deadlock.
5695     */
5696    private boolean isEphemeralDisabled() {
5697        // ephemeral apps have been disabled across the board
5698        if (DISABLE_EPHEMERAL_APPS) {
5699            return true;
5700        }
5701        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5702        if (!mSystemReady) {
5703            return true;
5704        }
5705        // we can't get a content resolver until the system is ready; these checks must happen last
5706        final ContentResolver resolver = mContext.getContentResolver();
5707        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5708            return true;
5709        }
5710        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5711    }
5712
5713    private boolean isEphemeralAllowed(
5714            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5715            boolean skipPackageCheck) {
5716        final int callingUser = UserHandle.getCallingUserId();
5717        if (callingUser != UserHandle.USER_SYSTEM) {
5718            return false;
5719        }
5720        if (mInstantAppResolverConnection == null) {
5721            return false;
5722        }
5723        if (mInstantAppInstallerComponent == null) {
5724            return false;
5725        }
5726        if (intent.getComponent() != null) {
5727            return false;
5728        }
5729        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5730            return false;
5731        }
5732        if (!skipPackageCheck && intent.getPackage() != null) {
5733            return false;
5734        }
5735        final boolean isWebUri = hasWebURI(intent);
5736        if (!isWebUri || intent.getData().getHost() == null) {
5737            return false;
5738        }
5739        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5740        // Or if there's already an ephemeral app installed that handles the action
5741        synchronized (mPackages) {
5742            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5743            for (int n = 0; n < count; n++) {
5744                ResolveInfo info = resolvedActivities.get(n);
5745                String packageName = info.activityInfo.packageName;
5746                PackageSetting ps = mSettings.mPackages.get(packageName);
5747                if (ps != null) {
5748                    // Try to get the status from User settings first
5749                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5750                    int status = (int) (packedStatus >> 32);
5751                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5752                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5753                        if (DEBUG_EPHEMERAL) {
5754                            Slog.v(TAG, "DENY ephemeral apps;"
5755                                + " pkg: " + packageName + ", status: " + status);
5756                        }
5757                        return false;
5758                    }
5759                    if (ps.getInstantApp(userId)) {
5760                        return false;
5761                    }
5762                }
5763            }
5764        }
5765        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5766        return true;
5767    }
5768
5769    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5770            Intent origIntent, String resolvedType, String callingPackage,
5771            int userId) {
5772        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5773                new InstantAppRequest(responseObj, origIntent, resolvedType,
5774                        callingPackage, userId));
5775        mHandler.sendMessage(msg);
5776    }
5777
5778    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5779            int flags, List<ResolveInfo> query, int userId) {
5780        if (query != null) {
5781            final int N = query.size();
5782            if (N == 1) {
5783                return query.get(0);
5784            } else if (N > 1) {
5785                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5786                // If there is more than one activity with the same priority,
5787                // then let the user decide between them.
5788                ResolveInfo r0 = query.get(0);
5789                ResolveInfo r1 = query.get(1);
5790                if (DEBUG_INTENT_MATCHING || debug) {
5791                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5792                            + r1.activityInfo.name + "=" + r1.priority);
5793                }
5794                // If the first activity has a higher priority, or a different
5795                // default, then it is always desirable to pick it.
5796                if (r0.priority != r1.priority
5797                        || r0.preferredOrder != r1.preferredOrder
5798                        || r0.isDefault != r1.isDefault) {
5799                    return query.get(0);
5800                }
5801                // If we have saved a preference for a preferred activity for
5802                // this Intent, use that.
5803                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5804                        flags, query, r0.priority, true, false, debug, userId);
5805                if (ri != null) {
5806                    return ri;
5807                }
5808                // If we have an ephemeral app, use it
5809                for (int i = 0; i < N; i++) {
5810                    ri = query.get(i);
5811                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5812                        return ri;
5813                    }
5814                }
5815                ri = new ResolveInfo(mResolveInfo);
5816                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5817                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5818                // If all of the options come from the same package, show the application's
5819                // label and icon instead of the generic resolver's.
5820                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5821                // and then throw away the ResolveInfo itself, meaning that the caller loses
5822                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5823                // a fallback for this case; we only set the target package's resources on
5824                // the ResolveInfo, not the ActivityInfo.
5825                final String intentPackage = intent.getPackage();
5826                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5827                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5828                    ri.resolvePackageName = intentPackage;
5829                    if (userNeedsBadging(userId)) {
5830                        ri.noResourceId = true;
5831                    } else {
5832                        ri.icon = appi.icon;
5833                    }
5834                    ri.iconResourceId = appi.icon;
5835                    ri.labelRes = appi.labelRes;
5836                }
5837                ri.activityInfo.applicationInfo = new ApplicationInfo(
5838                        ri.activityInfo.applicationInfo);
5839                if (userId != 0) {
5840                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5841                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5842                }
5843                // Make sure that the resolver is displayable in car mode
5844                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5845                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5846                return ri;
5847            }
5848        }
5849        return null;
5850    }
5851
5852    /**
5853     * Return true if the given list is not empty and all of its contents have
5854     * an activityInfo with the given package name.
5855     */
5856    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5857        if (ArrayUtils.isEmpty(list)) {
5858            return false;
5859        }
5860        for (int i = 0, N = list.size(); i < N; i++) {
5861            final ResolveInfo ri = list.get(i);
5862            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5863            if (ai == null || !packageName.equals(ai.packageName)) {
5864                return false;
5865            }
5866        }
5867        return true;
5868    }
5869
5870    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5871            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5872        final int N = query.size();
5873        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5874                .get(userId);
5875        // Get the list of persistent preferred activities that handle the intent
5876        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5877        List<PersistentPreferredActivity> pprefs = ppir != null
5878                ? ppir.queryIntent(intent, resolvedType,
5879                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5880                        userId)
5881                : null;
5882        if (pprefs != null && pprefs.size() > 0) {
5883            final int M = pprefs.size();
5884            for (int i=0; i<M; i++) {
5885                final PersistentPreferredActivity ppa = pprefs.get(i);
5886                if (DEBUG_PREFERRED || debug) {
5887                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5888                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5889                            + "\n  component=" + ppa.mComponent);
5890                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5891                }
5892                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5893                        flags | MATCH_DISABLED_COMPONENTS, userId);
5894                if (DEBUG_PREFERRED || debug) {
5895                    Slog.v(TAG, "Found persistent preferred activity:");
5896                    if (ai != null) {
5897                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5898                    } else {
5899                        Slog.v(TAG, "  null");
5900                    }
5901                }
5902                if (ai == null) {
5903                    // This previously registered persistent preferred activity
5904                    // component is no longer known. Ignore it and do NOT remove it.
5905                    continue;
5906                }
5907                for (int j=0; j<N; j++) {
5908                    final ResolveInfo ri = query.get(j);
5909                    if (!ri.activityInfo.applicationInfo.packageName
5910                            .equals(ai.applicationInfo.packageName)) {
5911                        continue;
5912                    }
5913                    if (!ri.activityInfo.name.equals(ai.name)) {
5914                        continue;
5915                    }
5916                    //  Found a persistent preference that can handle the intent.
5917                    if (DEBUG_PREFERRED || debug) {
5918                        Slog.v(TAG, "Returning persistent preferred activity: " +
5919                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5920                    }
5921                    return ri;
5922                }
5923            }
5924        }
5925        return null;
5926    }
5927
5928    // TODO: handle preferred activities missing while user has amnesia
5929    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5930            List<ResolveInfo> query, int priority, boolean always,
5931            boolean removeMatches, boolean debug, int userId) {
5932        if (!sUserManager.exists(userId)) return null;
5933        flags = updateFlagsForResolve(flags, userId, intent, false);
5934        intent = updateIntentForResolve(intent);
5935        // writer
5936        synchronized (mPackages) {
5937            // Try to find a matching persistent preferred activity.
5938            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5939                    debug, userId);
5940
5941            // If a persistent preferred activity matched, use it.
5942            if (pri != null) {
5943                return pri;
5944            }
5945
5946            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5947            // Get the list of preferred activities that handle the intent
5948            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5949            List<PreferredActivity> prefs = pir != null
5950                    ? pir.queryIntent(intent, resolvedType,
5951                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5952                            userId)
5953                    : null;
5954            if (prefs != null && prefs.size() > 0) {
5955                boolean changed = false;
5956                try {
5957                    // First figure out how good the original match set is.
5958                    // We will only allow preferred activities that came
5959                    // from the same match quality.
5960                    int match = 0;
5961
5962                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5963
5964                    final int N = query.size();
5965                    for (int j=0; j<N; j++) {
5966                        final ResolveInfo ri = query.get(j);
5967                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5968                                + ": 0x" + Integer.toHexString(match));
5969                        if (ri.match > match) {
5970                            match = ri.match;
5971                        }
5972                    }
5973
5974                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5975                            + Integer.toHexString(match));
5976
5977                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5978                    final int M = prefs.size();
5979                    for (int i=0; i<M; i++) {
5980                        final PreferredActivity pa = prefs.get(i);
5981                        if (DEBUG_PREFERRED || debug) {
5982                            Slog.v(TAG, "Checking PreferredActivity ds="
5983                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5984                                    + "\n  component=" + pa.mPref.mComponent);
5985                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5986                        }
5987                        if (pa.mPref.mMatch != match) {
5988                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5989                                    + Integer.toHexString(pa.mPref.mMatch));
5990                            continue;
5991                        }
5992                        // If it's not an "always" type preferred activity and that's what we're
5993                        // looking for, skip it.
5994                        if (always && !pa.mPref.mAlways) {
5995                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5996                            continue;
5997                        }
5998                        final ActivityInfo ai = getActivityInfo(
5999                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6000                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6001                                userId);
6002                        if (DEBUG_PREFERRED || debug) {
6003                            Slog.v(TAG, "Found preferred activity:");
6004                            if (ai != null) {
6005                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6006                            } else {
6007                                Slog.v(TAG, "  null");
6008                            }
6009                        }
6010                        if (ai == null) {
6011                            // This previously registered preferred activity
6012                            // component is no longer known.  Most likely an update
6013                            // to the app was installed and in the new version this
6014                            // component no longer exists.  Clean it up by removing
6015                            // it from the preferred activities list, and skip it.
6016                            Slog.w(TAG, "Removing dangling preferred activity: "
6017                                    + pa.mPref.mComponent);
6018                            pir.removeFilter(pa);
6019                            changed = true;
6020                            continue;
6021                        }
6022                        for (int j=0; j<N; j++) {
6023                            final ResolveInfo ri = query.get(j);
6024                            if (!ri.activityInfo.applicationInfo.packageName
6025                                    .equals(ai.applicationInfo.packageName)) {
6026                                continue;
6027                            }
6028                            if (!ri.activityInfo.name.equals(ai.name)) {
6029                                continue;
6030                            }
6031
6032                            if (removeMatches) {
6033                                pir.removeFilter(pa);
6034                                changed = true;
6035                                if (DEBUG_PREFERRED) {
6036                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6037                                }
6038                                break;
6039                            }
6040
6041                            // Okay we found a previously set preferred or last chosen app.
6042                            // If the result set is different from when this
6043                            // was created, we need to clear it and re-ask the
6044                            // user their preference, if we're looking for an "always" type entry.
6045                            if (always && !pa.mPref.sameSet(query)) {
6046                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6047                                        + intent + " type " + resolvedType);
6048                                if (DEBUG_PREFERRED) {
6049                                    Slog.v(TAG, "Removing preferred activity since set changed "
6050                                            + pa.mPref.mComponent);
6051                                }
6052                                pir.removeFilter(pa);
6053                                // Re-add the filter as a "last chosen" entry (!always)
6054                                PreferredActivity lastChosen = new PreferredActivity(
6055                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6056                                pir.addFilter(lastChosen);
6057                                changed = true;
6058                                return null;
6059                            }
6060
6061                            // Yay! Either the set matched or we're looking for the last chosen
6062                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6063                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6064                            return ri;
6065                        }
6066                    }
6067                } finally {
6068                    if (changed) {
6069                        if (DEBUG_PREFERRED) {
6070                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6071                        }
6072                        scheduleWritePackageRestrictionsLocked(userId);
6073                    }
6074                }
6075            }
6076        }
6077        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6078        return null;
6079    }
6080
6081    /*
6082     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6083     */
6084    @Override
6085    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6086            int targetUserId) {
6087        mContext.enforceCallingOrSelfPermission(
6088                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6089        List<CrossProfileIntentFilter> matches =
6090                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6091        if (matches != null) {
6092            int size = matches.size();
6093            for (int i = 0; i < size; i++) {
6094                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6095            }
6096        }
6097        if (hasWebURI(intent)) {
6098            // cross-profile app linking works only towards the parent.
6099            final UserInfo parent = getProfileParent(sourceUserId);
6100            synchronized(mPackages) {
6101                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6102                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6103                        intent, resolvedType, flags, sourceUserId, parent.id);
6104                return xpDomainInfo != null;
6105            }
6106        }
6107        return false;
6108    }
6109
6110    private UserInfo getProfileParent(int userId) {
6111        final long identity = Binder.clearCallingIdentity();
6112        try {
6113            return sUserManager.getProfileParent(userId);
6114        } finally {
6115            Binder.restoreCallingIdentity(identity);
6116        }
6117    }
6118
6119    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6120            String resolvedType, int userId) {
6121        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6122        if (resolver != null) {
6123            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6124        }
6125        return null;
6126    }
6127
6128    @Override
6129    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6130            String resolvedType, int flags, int userId) {
6131        try {
6132            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6133
6134            return new ParceledListSlice<>(
6135                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6136        } finally {
6137            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6138        }
6139    }
6140
6141    /**
6142     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6143     * instant, returns {@code null}.
6144     */
6145    private String getInstantAppPackageName(int callingUid) {
6146        final int appId = UserHandle.getAppId(callingUid);
6147        synchronized (mPackages) {
6148            final Object obj = mSettings.getUserIdLPr(appId);
6149            if (obj instanceof PackageSetting) {
6150                final PackageSetting ps = (PackageSetting) obj;
6151                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6152                return isInstantApp ? ps.pkg.packageName : null;
6153            }
6154        }
6155        return null;
6156    }
6157
6158    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6159            String resolvedType, int flags, int userId) {
6160        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6161    }
6162
6163    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6164            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6165        if (!sUserManager.exists(userId)) return Collections.emptyList();
6166        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6167        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6169                false /* requireFullPermission */, false /* checkShell */,
6170                "query intent activities");
6171        ComponentName comp = intent.getComponent();
6172        if (comp == null) {
6173            if (intent.getSelector() != null) {
6174                intent = intent.getSelector();
6175                comp = intent.getComponent();
6176            }
6177        }
6178
6179        if (comp != null) {
6180            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6181            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6182            if (ai != null) {
6183                // When specifying an explicit component, we prevent the activity from being
6184                // used when either 1) the calling package is normal and the activity is within
6185                // an ephemeral application or 2) the calling package is ephemeral and the
6186                // activity is not visible to ephemeral applications.
6187                final boolean matchInstantApp =
6188                        (flags & PackageManager.MATCH_INSTANT) != 0;
6189                final boolean matchVisibleToInstantAppOnly =
6190                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6191                final boolean isCallerInstantApp =
6192                        instantAppPkgName != null;
6193                final boolean isTargetSameInstantApp =
6194                        comp.getPackageName().equals(instantAppPkgName);
6195                final boolean isTargetInstantApp =
6196                        (ai.applicationInfo.privateFlags
6197                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6198                final boolean isTargetHiddenFromInstantApp =
6199                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6200                final boolean blockResolution =
6201                        !isTargetSameInstantApp
6202                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6203                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6204                                        && isTargetHiddenFromInstantApp));
6205                if (!blockResolution) {
6206                    final ResolveInfo ri = new ResolveInfo();
6207                    ri.activityInfo = ai;
6208                    list.add(ri);
6209                }
6210            }
6211            return applyPostResolutionFilter(list, instantAppPkgName);
6212        }
6213
6214        // reader
6215        boolean sortResult = false;
6216        boolean addEphemeral = false;
6217        List<ResolveInfo> result;
6218        final String pkgName = intent.getPackage();
6219        final boolean ephemeralDisabled = isEphemeralDisabled();
6220        synchronized (mPackages) {
6221            if (pkgName == null) {
6222                List<CrossProfileIntentFilter> matchingFilters =
6223                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6224                // Check for results that need to skip the current profile.
6225                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6226                        resolvedType, flags, userId);
6227                if (xpResolveInfo != null) {
6228                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6229                    xpResult.add(xpResolveInfo);
6230                    return applyPostResolutionFilter(
6231                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6232                }
6233
6234                // Check for results in the current profile.
6235                result = filterIfNotSystemUser(mActivities.queryIntent(
6236                        intent, resolvedType, flags, userId), userId);
6237                addEphemeral = !ephemeralDisabled
6238                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6239
6240                // Check for cross profile results.
6241                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6242                xpResolveInfo = queryCrossProfileIntents(
6243                        matchingFilters, intent, resolvedType, flags, userId,
6244                        hasNonNegativePriorityResult);
6245                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6246                    boolean isVisibleToUser = filterIfNotSystemUser(
6247                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6248                    if (isVisibleToUser) {
6249                        result.add(xpResolveInfo);
6250                        sortResult = true;
6251                    }
6252                }
6253                if (hasWebURI(intent)) {
6254                    CrossProfileDomainInfo xpDomainInfo = null;
6255                    final UserInfo parent = getProfileParent(userId);
6256                    if (parent != null) {
6257                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6258                                flags, userId, parent.id);
6259                    }
6260                    if (xpDomainInfo != null) {
6261                        if (xpResolveInfo != null) {
6262                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6263                            // in the result.
6264                            result.remove(xpResolveInfo);
6265                        }
6266                        if (result.size() == 0 && !addEphemeral) {
6267                            // No result in current profile, but found candidate in parent user.
6268                            // And we are not going to add emphemeral app, so we can return the
6269                            // result straight away.
6270                            result.add(xpDomainInfo.resolveInfo);
6271                            return applyPostResolutionFilter(result, instantAppPkgName);
6272                        }
6273                    } else if (result.size() <= 1 && !addEphemeral) {
6274                        // No result in parent user and <= 1 result in current profile, and we
6275                        // are not going to add emphemeral app, so we can return the result without
6276                        // further processing.
6277                        return applyPostResolutionFilter(result, instantAppPkgName);
6278                    }
6279                    // We have more than one candidate (combining results from current and parent
6280                    // profile), so we need filtering and sorting.
6281                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6282                            intent, flags, result, xpDomainInfo, userId);
6283                    sortResult = true;
6284                }
6285            } else {
6286                final PackageParser.Package pkg = mPackages.get(pkgName);
6287                if (pkg != null) {
6288                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6289                            mActivities.queryIntentForPackage(
6290                                    intent, resolvedType, flags, pkg.activities, userId),
6291                            userId), instantAppPkgName);
6292                } else {
6293                    // the caller wants to resolve for a particular package; however, there
6294                    // were no installed results, so, try to find an ephemeral result
6295                    addEphemeral =  !ephemeralDisabled
6296                            && isEphemeralAllowed(
6297                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6298                    result = new ArrayList<ResolveInfo>();
6299                }
6300            }
6301        }
6302        if (addEphemeral) {
6303            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6304            final InstantAppRequest requestObject = new InstantAppRequest(
6305                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6306                    null /*callingPackage*/, userId);
6307            final AuxiliaryResolveInfo auxiliaryResponse =
6308                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6309                            mContext, mInstantAppResolverConnection, requestObject);
6310            if (auxiliaryResponse != null) {
6311                if (DEBUG_EPHEMERAL) {
6312                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6313                }
6314                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6315                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6316                // make sure this resolver is the default
6317                ephemeralInstaller.isDefault = true;
6318                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6319                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6320                // add a non-generic filter
6321                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6322                ephemeralInstaller.filter.addDataPath(
6323                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6324                ephemeralInstaller.instantAppAvailable = true;
6325                result.add(ephemeralInstaller);
6326            }
6327            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6328        }
6329        if (sortResult) {
6330            Collections.sort(result, mResolvePrioritySorter);
6331        }
6332        return applyPostResolutionFilter(result, instantAppPkgName);
6333    }
6334
6335    private static class CrossProfileDomainInfo {
6336        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6337        ResolveInfo resolveInfo;
6338        /* Best domain verification status of the activities found in the other profile */
6339        int bestDomainVerificationStatus;
6340    }
6341
6342    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6343            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6344        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6345                sourceUserId)) {
6346            return null;
6347        }
6348        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6349                resolvedType, flags, parentUserId);
6350
6351        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6352            return null;
6353        }
6354        CrossProfileDomainInfo result = null;
6355        int size = resultTargetUser.size();
6356        for (int i = 0; i < size; i++) {
6357            ResolveInfo riTargetUser = resultTargetUser.get(i);
6358            // Intent filter verification is only for filters that specify a host. So don't return
6359            // those that handle all web uris.
6360            if (riTargetUser.handleAllWebDataURI) {
6361                continue;
6362            }
6363            String packageName = riTargetUser.activityInfo.packageName;
6364            PackageSetting ps = mSettings.mPackages.get(packageName);
6365            if (ps == null) {
6366                continue;
6367            }
6368            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6369            int status = (int)(verificationState >> 32);
6370            if (result == null) {
6371                result = new CrossProfileDomainInfo();
6372                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6373                        sourceUserId, parentUserId);
6374                result.bestDomainVerificationStatus = status;
6375            } else {
6376                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6377                        result.bestDomainVerificationStatus);
6378            }
6379        }
6380        // Don't consider matches with status NEVER across profiles.
6381        if (result != null && result.bestDomainVerificationStatus
6382                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6383            return null;
6384        }
6385        return result;
6386    }
6387
6388    /**
6389     * Verification statuses are ordered from the worse to the best, except for
6390     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6391     */
6392    private int bestDomainVerificationStatus(int status1, int status2) {
6393        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6394            return status2;
6395        }
6396        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6397            return status1;
6398        }
6399        return (int) MathUtils.max(status1, status2);
6400    }
6401
6402    private boolean isUserEnabled(int userId) {
6403        long callingId = Binder.clearCallingIdentity();
6404        try {
6405            UserInfo userInfo = sUserManager.getUserInfo(userId);
6406            return userInfo != null && userInfo.isEnabled();
6407        } finally {
6408            Binder.restoreCallingIdentity(callingId);
6409        }
6410    }
6411
6412    /**
6413     * Filter out activities with systemUserOnly flag set, when current user is not System.
6414     *
6415     * @return filtered list
6416     */
6417    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6418        if (userId == UserHandle.USER_SYSTEM) {
6419            return resolveInfos;
6420        }
6421        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6422            ResolveInfo info = resolveInfos.get(i);
6423            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6424                resolveInfos.remove(i);
6425            }
6426        }
6427        return resolveInfos;
6428    }
6429
6430    /**
6431     * Filters out ephemeral activities.
6432     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6433     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6434     *
6435     * @param resolveInfos The pre-filtered list of resolved activities
6436     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6437     *          is performed.
6438     * @return A filtered list of resolved activities.
6439     */
6440    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6441            String ephemeralPkgName) {
6442        // TODO: When adding on-demand split support for non-instant apps, remove this check
6443        // and always apply post filtering
6444        if (ephemeralPkgName == null) {
6445            return resolveInfos;
6446        }
6447        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6448            final ResolveInfo info = resolveInfos.get(i);
6449            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6450            // allow activities that are defined in the provided package
6451            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6452                if (info.activityInfo.splitName != null
6453                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6454                                info.activityInfo.splitName)) {
6455                    // requested activity is defined in a split that hasn't been installed yet.
6456                    // add the installer to the resolve list
6457                    if (DEBUG_EPHEMERAL) {
6458                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6459                    }
6460                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6461                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6462                            info.activityInfo.packageName, info.activityInfo.splitName,
6463                            info.activityInfo.applicationInfo.versionCode);
6464                    // make sure this resolver is the default
6465                    installerInfo.isDefault = true;
6466                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6467                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6468                    // add a non-generic filter
6469                    installerInfo.filter = new IntentFilter();
6470                    // load resources from the correct package
6471                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6472                    resolveInfos.set(i, installerInfo);
6473                }
6474                continue;
6475            }
6476            // allow activities that have been explicitly exposed to ephemeral apps
6477            if (!isEphemeralApp
6478                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6479                continue;
6480            }
6481            resolveInfos.remove(i);
6482        }
6483        return resolveInfos;
6484    }
6485
6486    /**
6487     * @param resolveInfos list of resolve infos in descending priority order
6488     * @return if the list contains a resolve info with non-negative priority
6489     */
6490    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6491        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6492    }
6493
6494    private static boolean hasWebURI(Intent intent) {
6495        if (intent.getData() == null) {
6496            return false;
6497        }
6498        final String scheme = intent.getScheme();
6499        if (TextUtils.isEmpty(scheme)) {
6500            return false;
6501        }
6502        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6503    }
6504
6505    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6506            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6507            int userId) {
6508        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6509
6510        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6511            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6512                    candidates.size());
6513        }
6514
6515        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6516        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6517        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6518        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6519        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6520        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6521
6522        synchronized (mPackages) {
6523            final int count = candidates.size();
6524            // First, try to use linked apps. Partition the candidates into four lists:
6525            // one for the final results, one for the "do not use ever", one for "undefined status"
6526            // and finally one for "browser app type".
6527            for (int n=0; n<count; n++) {
6528                ResolveInfo info = candidates.get(n);
6529                String packageName = info.activityInfo.packageName;
6530                PackageSetting ps = mSettings.mPackages.get(packageName);
6531                if (ps != null) {
6532                    // Add to the special match all list (Browser use case)
6533                    if (info.handleAllWebDataURI) {
6534                        matchAllList.add(info);
6535                        continue;
6536                    }
6537                    // Try to get the status from User settings first
6538                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6539                    int status = (int)(packedStatus >> 32);
6540                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6541                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6542                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6543                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6544                                    + " : linkgen=" + linkGeneration);
6545                        }
6546                        // Use link-enabled generation as preferredOrder, i.e.
6547                        // prefer newly-enabled over earlier-enabled.
6548                        info.preferredOrder = linkGeneration;
6549                        alwaysList.add(info);
6550                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6551                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6552                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6553                        }
6554                        neverList.add(info);
6555                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6556                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6557                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6558                        }
6559                        alwaysAskList.add(info);
6560                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6561                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6562                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6563                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6564                        }
6565                        undefinedList.add(info);
6566                    }
6567                }
6568            }
6569
6570            // We'll want to include browser possibilities in a few cases
6571            boolean includeBrowser = false;
6572
6573            // First try to add the "always" resolution(s) for the current user, if any
6574            if (alwaysList.size() > 0) {
6575                result.addAll(alwaysList);
6576            } else {
6577                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6578                result.addAll(undefinedList);
6579                // Maybe add one for the other profile.
6580                if (xpDomainInfo != null && (
6581                        xpDomainInfo.bestDomainVerificationStatus
6582                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6583                    result.add(xpDomainInfo.resolveInfo);
6584                }
6585                includeBrowser = true;
6586            }
6587
6588            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6589            // If there were 'always' entries their preferred order has been set, so we also
6590            // back that off to make the alternatives equivalent
6591            if (alwaysAskList.size() > 0) {
6592                for (ResolveInfo i : result) {
6593                    i.preferredOrder = 0;
6594                }
6595                result.addAll(alwaysAskList);
6596                includeBrowser = true;
6597            }
6598
6599            if (includeBrowser) {
6600                // Also add browsers (all of them or only the default one)
6601                if (DEBUG_DOMAIN_VERIFICATION) {
6602                    Slog.v(TAG, "   ...including browsers in candidate set");
6603                }
6604                if ((matchFlags & MATCH_ALL) != 0) {
6605                    result.addAll(matchAllList);
6606                } else {
6607                    // Browser/generic handling case.  If there's a default browser, go straight
6608                    // to that (but only if there is no other higher-priority match).
6609                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6610                    int maxMatchPrio = 0;
6611                    ResolveInfo defaultBrowserMatch = null;
6612                    final int numCandidates = matchAllList.size();
6613                    for (int n = 0; n < numCandidates; n++) {
6614                        ResolveInfo info = matchAllList.get(n);
6615                        // track the highest overall match priority...
6616                        if (info.priority > maxMatchPrio) {
6617                            maxMatchPrio = info.priority;
6618                        }
6619                        // ...and the highest-priority default browser match
6620                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6621                            if (defaultBrowserMatch == null
6622                                    || (defaultBrowserMatch.priority < info.priority)) {
6623                                if (debug) {
6624                                    Slog.v(TAG, "Considering default browser match " + info);
6625                                }
6626                                defaultBrowserMatch = info;
6627                            }
6628                        }
6629                    }
6630                    if (defaultBrowserMatch != null
6631                            && defaultBrowserMatch.priority >= maxMatchPrio
6632                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6633                    {
6634                        if (debug) {
6635                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6636                        }
6637                        result.add(defaultBrowserMatch);
6638                    } else {
6639                        result.addAll(matchAllList);
6640                    }
6641                }
6642
6643                // If there is nothing selected, add all candidates and remove the ones that the user
6644                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6645                if (result.size() == 0) {
6646                    result.addAll(candidates);
6647                    result.removeAll(neverList);
6648                }
6649            }
6650        }
6651        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6652            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6653                    result.size());
6654            for (ResolveInfo info : result) {
6655                Slog.v(TAG, "  + " + info.activityInfo);
6656            }
6657        }
6658        return result;
6659    }
6660
6661    // Returns a packed value as a long:
6662    //
6663    // high 'int'-sized word: link status: undefined/ask/never/always.
6664    // low 'int'-sized word: relative priority among 'always' results.
6665    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6666        long result = ps.getDomainVerificationStatusForUser(userId);
6667        // if none available, get the master status
6668        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6669            if (ps.getIntentFilterVerificationInfo() != null) {
6670                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6671            }
6672        }
6673        return result;
6674    }
6675
6676    private ResolveInfo querySkipCurrentProfileIntents(
6677            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6678            int flags, int sourceUserId) {
6679        if (matchingFilters != null) {
6680            int size = matchingFilters.size();
6681            for (int i = 0; i < size; i ++) {
6682                CrossProfileIntentFilter filter = matchingFilters.get(i);
6683                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6684                    // Checking if there are activities in the target user that can handle the
6685                    // intent.
6686                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6687                            resolvedType, flags, sourceUserId);
6688                    if (resolveInfo != null) {
6689                        return resolveInfo;
6690                    }
6691                }
6692            }
6693        }
6694        return null;
6695    }
6696
6697    // Return matching ResolveInfo in target user if any.
6698    private ResolveInfo queryCrossProfileIntents(
6699            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6700            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6701        if (matchingFilters != null) {
6702            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6703            // match the same intent. For performance reasons, it is better not to
6704            // run queryIntent twice for the same userId
6705            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6706            int size = matchingFilters.size();
6707            for (int i = 0; i < size; i++) {
6708                CrossProfileIntentFilter filter = matchingFilters.get(i);
6709                int targetUserId = filter.getTargetUserId();
6710                boolean skipCurrentProfile =
6711                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6712                boolean skipCurrentProfileIfNoMatchFound =
6713                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6714                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6715                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6716                    // Checking if there are activities in the target user that can handle the
6717                    // intent.
6718                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6719                            resolvedType, flags, sourceUserId);
6720                    if (resolveInfo != null) return resolveInfo;
6721                    alreadyTriedUserIds.put(targetUserId, true);
6722                }
6723            }
6724        }
6725        return null;
6726    }
6727
6728    /**
6729     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6730     * will forward the intent to the filter's target user.
6731     * Otherwise, returns null.
6732     */
6733    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6734            String resolvedType, int flags, int sourceUserId) {
6735        int targetUserId = filter.getTargetUserId();
6736        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6737                resolvedType, flags, targetUserId);
6738        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6739            // If all the matches in the target profile are suspended, return null.
6740            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6741                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6742                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6743                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6744                            targetUserId);
6745                }
6746            }
6747        }
6748        return null;
6749    }
6750
6751    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6752            int sourceUserId, int targetUserId) {
6753        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6754        long ident = Binder.clearCallingIdentity();
6755        boolean targetIsProfile;
6756        try {
6757            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6758        } finally {
6759            Binder.restoreCallingIdentity(ident);
6760        }
6761        String className;
6762        if (targetIsProfile) {
6763            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6764        } else {
6765            className = FORWARD_INTENT_TO_PARENT;
6766        }
6767        ComponentName forwardingActivityComponentName = new ComponentName(
6768                mAndroidApplication.packageName, className);
6769        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6770                sourceUserId);
6771        if (!targetIsProfile) {
6772            forwardingActivityInfo.showUserIcon = targetUserId;
6773            forwardingResolveInfo.noResourceId = true;
6774        }
6775        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6776        forwardingResolveInfo.priority = 0;
6777        forwardingResolveInfo.preferredOrder = 0;
6778        forwardingResolveInfo.match = 0;
6779        forwardingResolveInfo.isDefault = true;
6780        forwardingResolveInfo.filter = filter;
6781        forwardingResolveInfo.targetUserId = targetUserId;
6782        return forwardingResolveInfo;
6783    }
6784
6785    @Override
6786    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6787            Intent[] specifics, String[] specificTypes, Intent intent,
6788            String resolvedType, int flags, int userId) {
6789        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6790                specificTypes, intent, resolvedType, flags, userId));
6791    }
6792
6793    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6794            Intent[] specifics, String[] specificTypes, Intent intent,
6795            String resolvedType, int flags, int userId) {
6796        if (!sUserManager.exists(userId)) return Collections.emptyList();
6797        flags = updateFlagsForResolve(flags, userId, intent, false);
6798        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6799                false /* requireFullPermission */, false /* checkShell */,
6800                "query intent activity options");
6801        final String resultsAction = intent.getAction();
6802
6803        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6804                | PackageManager.GET_RESOLVED_FILTER, userId);
6805
6806        if (DEBUG_INTENT_MATCHING) {
6807            Log.v(TAG, "Query " + intent + ": " + results);
6808        }
6809
6810        int specificsPos = 0;
6811        int N;
6812
6813        // todo: note that the algorithm used here is O(N^2).  This
6814        // isn't a problem in our current environment, but if we start running
6815        // into situations where we have more than 5 or 10 matches then this
6816        // should probably be changed to something smarter...
6817
6818        // First we go through and resolve each of the specific items
6819        // that were supplied, taking care of removing any corresponding
6820        // duplicate items in the generic resolve list.
6821        if (specifics != null) {
6822            for (int i=0; i<specifics.length; i++) {
6823                final Intent sintent = specifics[i];
6824                if (sintent == null) {
6825                    continue;
6826                }
6827
6828                if (DEBUG_INTENT_MATCHING) {
6829                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6830                }
6831
6832                String action = sintent.getAction();
6833                if (resultsAction != null && resultsAction.equals(action)) {
6834                    // If this action was explicitly requested, then don't
6835                    // remove things that have it.
6836                    action = null;
6837                }
6838
6839                ResolveInfo ri = null;
6840                ActivityInfo ai = null;
6841
6842                ComponentName comp = sintent.getComponent();
6843                if (comp == null) {
6844                    ri = resolveIntent(
6845                        sintent,
6846                        specificTypes != null ? specificTypes[i] : null,
6847                            flags, userId);
6848                    if (ri == null) {
6849                        continue;
6850                    }
6851                    if (ri == mResolveInfo) {
6852                        // ACK!  Must do something better with this.
6853                    }
6854                    ai = ri.activityInfo;
6855                    comp = new ComponentName(ai.applicationInfo.packageName,
6856                            ai.name);
6857                } else {
6858                    ai = getActivityInfo(comp, flags, userId);
6859                    if (ai == null) {
6860                        continue;
6861                    }
6862                }
6863
6864                // Look for any generic query activities that are duplicates
6865                // of this specific one, and remove them from the results.
6866                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6867                N = results.size();
6868                int j;
6869                for (j=specificsPos; j<N; j++) {
6870                    ResolveInfo sri = results.get(j);
6871                    if ((sri.activityInfo.name.equals(comp.getClassName())
6872                            && sri.activityInfo.applicationInfo.packageName.equals(
6873                                    comp.getPackageName()))
6874                        || (action != null && sri.filter.matchAction(action))) {
6875                        results.remove(j);
6876                        if (DEBUG_INTENT_MATCHING) Log.v(
6877                            TAG, "Removing duplicate item from " + j
6878                            + " due to specific " + specificsPos);
6879                        if (ri == null) {
6880                            ri = sri;
6881                        }
6882                        j--;
6883                        N--;
6884                    }
6885                }
6886
6887                // Add this specific item to its proper place.
6888                if (ri == null) {
6889                    ri = new ResolveInfo();
6890                    ri.activityInfo = ai;
6891                }
6892                results.add(specificsPos, ri);
6893                ri.specificIndex = i;
6894                specificsPos++;
6895            }
6896        }
6897
6898        // Now we go through the remaining generic results and remove any
6899        // duplicate actions that are found here.
6900        N = results.size();
6901        for (int i=specificsPos; i<N-1; i++) {
6902            final ResolveInfo rii = results.get(i);
6903            if (rii.filter == null) {
6904                continue;
6905            }
6906
6907            // Iterate over all of the actions of this result's intent
6908            // filter...  typically this should be just one.
6909            final Iterator<String> it = rii.filter.actionsIterator();
6910            if (it == null) {
6911                continue;
6912            }
6913            while (it.hasNext()) {
6914                final String action = it.next();
6915                if (resultsAction != null && resultsAction.equals(action)) {
6916                    // If this action was explicitly requested, then don't
6917                    // remove things that have it.
6918                    continue;
6919                }
6920                for (int j=i+1; j<N; j++) {
6921                    final ResolveInfo rij = results.get(j);
6922                    if (rij.filter != null && rij.filter.hasAction(action)) {
6923                        results.remove(j);
6924                        if (DEBUG_INTENT_MATCHING) Log.v(
6925                            TAG, "Removing duplicate item from " + j
6926                            + " due to action " + action + " at " + i);
6927                        j--;
6928                        N--;
6929                    }
6930                }
6931            }
6932
6933            // If the caller didn't request filter information, drop it now
6934            // so we don't have to marshall/unmarshall it.
6935            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6936                rii.filter = null;
6937            }
6938        }
6939
6940        // Filter out the caller activity if so requested.
6941        if (caller != null) {
6942            N = results.size();
6943            for (int i=0; i<N; i++) {
6944                ActivityInfo ainfo = results.get(i).activityInfo;
6945                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6946                        && caller.getClassName().equals(ainfo.name)) {
6947                    results.remove(i);
6948                    break;
6949                }
6950            }
6951        }
6952
6953        // If the caller didn't request filter information,
6954        // drop them now so we don't have to
6955        // marshall/unmarshall it.
6956        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6957            N = results.size();
6958            for (int i=0; i<N; i++) {
6959                results.get(i).filter = null;
6960            }
6961        }
6962
6963        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6964        return results;
6965    }
6966
6967    @Override
6968    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6969            String resolvedType, int flags, int userId) {
6970        return new ParceledListSlice<>(
6971                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6972    }
6973
6974    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6975            String resolvedType, int flags, int userId) {
6976        if (!sUserManager.exists(userId)) return Collections.emptyList();
6977        flags = updateFlagsForResolve(flags, userId, intent, false);
6978        ComponentName comp = intent.getComponent();
6979        if (comp == null) {
6980            if (intent.getSelector() != null) {
6981                intent = intent.getSelector();
6982                comp = intent.getComponent();
6983            }
6984        }
6985        if (comp != null) {
6986            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6987            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6988            if (ai != null) {
6989                ResolveInfo ri = new ResolveInfo();
6990                ri.activityInfo = ai;
6991                list.add(ri);
6992            }
6993            return list;
6994        }
6995
6996        // reader
6997        synchronized (mPackages) {
6998            String pkgName = intent.getPackage();
6999            if (pkgName == null) {
7000                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7001            }
7002            final PackageParser.Package pkg = mPackages.get(pkgName);
7003            if (pkg != null) {
7004                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7005                        userId);
7006            }
7007            return Collections.emptyList();
7008        }
7009    }
7010
7011    @Override
7012    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7013        if (!sUserManager.exists(userId)) return null;
7014        flags = updateFlagsForResolve(flags, userId, intent, false);
7015        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7016        if (query != null) {
7017            if (query.size() >= 1) {
7018                // If there is more than one service with the same priority,
7019                // just arbitrarily pick the first one.
7020                return query.get(0);
7021            }
7022        }
7023        return null;
7024    }
7025
7026    @Override
7027    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7028            String resolvedType, int flags, int userId) {
7029        return new ParceledListSlice<>(
7030                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7031    }
7032
7033    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7034            String resolvedType, int flags, int userId) {
7035        if (!sUserManager.exists(userId)) return Collections.emptyList();
7036        flags = updateFlagsForResolve(flags, userId, intent, false);
7037        ComponentName comp = intent.getComponent();
7038        if (comp == null) {
7039            if (intent.getSelector() != null) {
7040                intent = intent.getSelector();
7041                comp = intent.getComponent();
7042            }
7043        }
7044        if (comp != null) {
7045            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7046            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7047            if (si != null) {
7048                final ResolveInfo ri = new ResolveInfo();
7049                ri.serviceInfo = si;
7050                list.add(ri);
7051            }
7052            return list;
7053        }
7054
7055        // reader
7056        synchronized (mPackages) {
7057            String pkgName = intent.getPackage();
7058            if (pkgName == null) {
7059                return mServices.queryIntent(intent, resolvedType, flags, userId);
7060            }
7061            final PackageParser.Package pkg = mPackages.get(pkgName);
7062            if (pkg != null) {
7063                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7064                        userId);
7065            }
7066            return Collections.emptyList();
7067        }
7068    }
7069
7070    @Override
7071    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7072            String resolvedType, int flags, int userId) {
7073        return new ParceledListSlice<>(
7074                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7075    }
7076
7077    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7078            Intent intent, String resolvedType, int flags, int userId) {
7079        if (!sUserManager.exists(userId)) return Collections.emptyList();
7080        flags = updateFlagsForResolve(flags, userId, intent, false);
7081        ComponentName comp = intent.getComponent();
7082        if (comp == null) {
7083            if (intent.getSelector() != null) {
7084                intent = intent.getSelector();
7085                comp = intent.getComponent();
7086            }
7087        }
7088        if (comp != null) {
7089            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7090            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7091            if (pi != null) {
7092                final ResolveInfo ri = new ResolveInfo();
7093                ri.providerInfo = pi;
7094                list.add(ri);
7095            }
7096            return list;
7097        }
7098
7099        // reader
7100        synchronized (mPackages) {
7101            String pkgName = intent.getPackage();
7102            if (pkgName == null) {
7103                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7104            }
7105            final PackageParser.Package pkg = mPackages.get(pkgName);
7106            if (pkg != null) {
7107                return mProviders.queryIntentForPackage(
7108                        intent, resolvedType, flags, pkg.providers, userId);
7109            }
7110            return Collections.emptyList();
7111        }
7112    }
7113
7114    @Override
7115    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7116        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7117        flags = updateFlagsForPackage(flags, userId, null);
7118        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7119        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7120                true /* requireFullPermission */, false /* checkShell */,
7121                "get installed packages");
7122
7123        // writer
7124        synchronized (mPackages) {
7125            ArrayList<PackageInfo> list;
7126            if (listUninstalled) {
7127                list = new ArrayList<>(mSettings.mPackages.size());
7128                for (PackageSetting ps : mSettings.mPackages.values()) {
7129                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7130                        continue;
7131                    }
7132                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7133                    if (pi != null) {
7134                        list.add(pi);
7135                    }
7136                }
7137            } else {
7138                list = new ArrayList<>(mPackages.size());
7139                for (PackageParser.Package p : mPackages.values()) {
7140                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7141                            Binder.getCallingUid(), userId)) {
7142                        continue;
7143                    }
7144                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7145                            p.mExtras, flags, userId);
7146                    if (pi != null) {
7147                        list.add(pi);
7148                    }
7149                }
7150            }
7151
7152            return new ParceledListSlice<>(list);
7153        }
7154    }
7155
7156    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7157            String[] permissions, boolean[] tmp, int flags, int userId) {
7158        int numMatch = 0;
7159        final PermissionsState permissionsState = ps.getPermissionsState();
7160        for (int i=0; i<permissions.length; i++) {
7161            final String permission = permissions[i];
7162            if (permissionsState.hasPermission(permission, userId)) {
7163                tmp[i] = true;
7164                numMatch++;
7165            } else {
7166                tmp[i] = false;
7167            }
7168        }
7169        if (numMatch == 0) {
7170            return;
7171        }
7172        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7173
7174        // The above might return null in cases of uninstalled apps or install-state
7175        // skew across users/profiles.
7176        if (pi != null) {
7177            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7178                if (numMatch == permissions.length) {
7179                    pi.requestedPermissions = permissions;
7180                } else {
7181                    pi.requestedPermissions = new String[numMatch];
7182                    numMatch = 0;
7183                    for (int i=0; i<permissions.length; i++) {
7184                        if (tmp[i]) {
7185                            pi.requestedPermissions[numMatch] = permissions[i];
7186                            numMatch++;
7187                        }
7188                    }
7189                }
7190            }
7191            list.add(pi);
7192        }
7193    }
7194
7195    @Override
7196    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7197            String[] permissions, int flags, int userId) {
7198        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7199        flags = updateFlagsForPackage(flags, userId, permissions);
7200        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7201                true /* requireFullPermission */, false /* checkShell */,
7202                "get packages holding permissions");
7203        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7204
7205        // writer
7206        synchronized (mPackages) {
7207            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7208            boolean[] tmpBools = new boolean[permissions.length];
7209            if (listUninstalled) {
7210                for (PackageSetting ps : mSettings.mPackages.values()) {
7211                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7212                            userId);
7213                }
7214            } else {
7215                for (PackageParser.Package pkg : mPackages.values()) {
7216                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7217                    if (ps != null) {
7218                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7219                                userId);
7220                    }
7221                }
7222            }
7223
7224            return new ParceledListSlice<PackageInfo>(list);
7225        }
7226    }
7227
7228    @Override
7229    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7230        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7231        flags = updateFlagsForApplication(flags, userId, null);
7232        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7233
7234        // writer
7235        synchronized (mPackages) {
7236            ArrayList<ApplicationInfo> list;
7237            if (listUninstalled) {
7238                list = new ArrayList<>(mSettings.mPackages.size());
7239                for (PackageSetting ps : mSettings.mPackages.values()) {
7240                    ApplicationInfo ai;
7241                    int effectiveFlags = flags;
7242                    if (ps.isSystem()) {
7243                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7244                    }
7245                    if (ps.pkg != null) {
7246                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7247                            continue;
7248                        }
7249                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7250                                ps.readUserState(userId), userId);
7251                        if (ai != null) {
7252                            rebaseEnabledOverlays(ai, userId);
7253                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7254                        }
7255                    } else {
7256                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7257                        // and already converts to externally visible package name
7258                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7259                                Binder.getCallingUid(), effectiveFlags, userId);
7260                    }
7261                    if (ai != null) {
7262                        list.add(ai);
7263                    }
7264                }
7265            } else {
7266                list = new ArrayList<>(mPackages.size());
7267                for (PackageParser.Package p : mPackages.values()) {
7268                    if (p.mExtras != null) {
7269                        PackageSetting ps = (PackageSetting) p.mExtras;
7270                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7271                            continue;
7272                        }
7273                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7274                                ps.readUserState(userId), userId);
7275                        if (ai != null) {
7276                            rebaseEnabledOverlays(ai, userId);
7277                            ai.packageName = resolveExternalPackageNameLPr(p);
7278                            list.add(ai);
7279                        }
7280                    }
7281                }
7282            }
7283
7284            return new ParceledListSlice<>(list);
7285        }
7286    }
7287
7288    @Override
7289    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7290        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7291            return null;
7292        }
7293
7294        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7295                "getEphemeralApplications");
7296        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7297                true /* requireFullPermission */, false /* checkShell */,
7298                "getEphemeralApplications");
7299        synchronized (mPackages) {
7300            List<InstantAppInfo> instantApps = mInstantAppRegistry
7301                    .getInstantAppsLPr(userId);
7302            if (instantApps != null) {
7303                return new ParceledListSlice<>(instantApps);
7304            }
7305        }
7306        return null;
7307    }
7308
7309    @Override
7310    public boolean isInstantApp(String packageName, int userId) {
7311        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7312                true /* requireFullPermission */, false /* checkShell */,
7313                "isInstantApp");
7314        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7315            return false;
7316        }
7317
7318        synchronized (mPackages) {
7319            final PackageSetting ps = mSettings.mPackages.get(packageName);
7320            final boolean returnAllowed =
7321                    ps != null
7322                    && (isCallerSameApp(packageName)
7323                            || mContext.checkCallingOrSelfPermission(
7324                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7325                                            == PERMISSION_GRANTED
7326                            || mInstantAppRegistry.isInstantAccessGranted(
7327                                    userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId));
7328            if (returnAllowed) {
7329                return ps.getInstantApp(userId);
7330            }
7331        }
7332        return false;
7333    }
7334
7335    @Override
7336    public byte[] getInstantAppCookie(String packageName, int userId) {
7337        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7338            return null;
7339        }
7340
7341        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7342                true /* requireFullPermission */, false /* checkShell */,
7343                "getInstantAppCookie");
7344        if (!isCallerSameApp(packageName)) {
7345            return null;
7346        }
7347        synchronized (mPackages) {
7348            return mInstantAppRegistry.getInstantAppCookieLPw(
7349                    packageName, userId);
7350        }
7351    }
7352
7353    @Override
7354    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7355        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7356            return true;
7357        }
7358
7359        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7360                true /* requireFullPermission */, true /* checkShell */,
7361                "setInstantAppCookie");
7362        if (!isCallerSameApp(packageName)) {
7363            return false;
7364        }
7365        synchronized (mPackages) {
7366            return mInstantAppRegistry.setInstantAppCookieLPw(
7367                    packageName, cookie, userId);
7368        }
7369    }
7370
7371    @Override
7372    public Bitmap getInstantAppIcon(String packageName, int userId) {
7373        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7374            return null;
7375        }
7376
7377        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7378                "getInstantAppIcon");
7379
7380        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7381                true /* requireFullPermission */, false /* checkShell */,
7382                "getInstantAppIcon");
7383
7384        synchronized (mPackages) {
7385            return mInstantAppRegistry.getInstantAppIconLPw(
7386                    packageName, userId);
7387        }
7388    }
7389
7390    private boolean isCallerSameApp(String packageName) {
7391        PackageParser.Package pkg = mPackages.get(packageName);
7392        return pkg != null
7393                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7394    }
7395
7396    @Override
7397    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7398        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7399    }
7400
7401    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7402        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7403
7404        // reader
7405        synchronized (mPackages) {
7406            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7407            final int userId = UserHandle.getCallingUserId();
7408            while (i.hasNext()) {
7409                final PackageParser.Package p = i.next();
7410                if (p.applicationInfo == null) continue;
7411
7412                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7413                        && !p.applicationInfo.isDirectBootAware();
7414                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7415                        && p.applicationInfo.isDirectBootAware();
7416
7417                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7418                        && (!mSafeMode || isSystemApp(p))
7419                        && (matchesUnaware || matchesAware)) {
7420                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7421                    if (ps != null) {
7422                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7423                                ps.readUserState(userId), userId);
7424                        if (ai != null) {
7425                            rebaseEnabledOverlays(ai, userId);
7426                            finalList.add(ai);
7427                        }
7428                    }
7429                }
7430            }
7431        }
7432
7433        return finalList;
7434    }
7435
7436    @Override
7437    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7438        if (!sUserManager.exists(userId)) return null;
7439        flags = updateFlagsForComponent(flags, userId, name);
7440        // reader
7441        synchronized (mPackages) {
7442            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7443            PackageSetting ps = provider != null
7444                    ? mSettings.mPackages.get(provider.owner.packageName)
7445                    : null;
7446            return ps != null
7447                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7448                    ? PackageParser.generateProviderInfo(provider, flags,
7449                            ps.readUserState(userId), userId)
7450                    : null;
7451        }
7452    }
7453
7454    /**
7455     * @deprecated
7456     */
7457    @Deprecated
7458    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7459        // reader
7460        synchronized (mPackages) {
7461            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7462                    .entrySet().iterator();
7463            final int userId = UserHandle.getCallingUserId();
7464            while (i.hasNext()) {
7465                Map.Entry<String, PackageParser.Provider> entry = i.next();
7466                PackageParser.Provider p = entry.getValue();
7467                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7468
7469                if (ps != null && p.syncable
7470                        && (!mSafeMode || (p.info.applicationInfo.flags
7471                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7472                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7473                            ps.readUserState(userId), userId);
7474                    if (info != null) {
7475                        outNames.add(entry.getKey());
7476                        outInfo.add(info);
7477                    }
7478                }
7479            }
7480        }
7481    }
7482
7483    @Override
7484    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7485            int uid, int flags, String metaDataKey) {
7486        final int userId = processName != null ? UserHandle.getUserId(uid)
7487                : UserHandle.getCallingUserId();
7488        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7489        flags = updateFlagsForComponent(flags, userId, processName);
7490
7491        ArrayList<ProviderInfo> finalList = null;
7492        // reader
7493        synchronized (mPackages) {
7494            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7495            while (i.hasNext()) {
7496                final PackageParser.Provider p = i.next();
7497                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7498                if (ps != null && p.info.authority != null
7499                        && (processName == null
7500                                || (p.info.processName.equals(processName)
7501                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7502                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7503
7504                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7505                    // parameter.
7506                    if (metaDataKey != null
7507                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7508                        continue;
7509                    }
7510
7511                    if (finalList == null) {
7512                        finalList = new ArrayList<ProviderInfo>(3);
7513                    }
7514                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7515                            ps.readUserState(userId), userId);
7516                    if (info != null) {
7517                        finalList.add(info);
7518                    }
7519                }
7520            }
7521        }
7522
7523        if (finalList != null) {
7524            Collections.sort(finalList, mProviderInitOrderSorter);
7525            return new ParceledListSlice<ProviderInfo>(finalList);
7526        }
7527
7528        return ParceledListSlice.emptyList();
7529    }
7530
7531    @Override
7532    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7533        // reader
7534        synchronized (mPackages) {
7535            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7536            return PackageParser.generateInstrumentationInfo(i, flags);
7537        }
7538    }
7539
7540    @Override
7541    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7542            String targetPackage, int flags) {
7543        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7544    }
7545
7546    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7547            int flags) {
7548        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7549
7550        // reader
7551        synchronized (mPackages) {
7552            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7553            while (i.hasNext()) {
7554                final PackageParser.Instrumentation p = i.next();
7555                if (targetPackage == null
7556                        || targetPackage.equals(p.info.targetPackage)) {
7557                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7558                            flags);
7559                    if (ii != null) {
7560                        finalList.add(ii);
7561                    }
7562                }
7563            }
7564        }
7565
7566        return finalList;
7567    }
7568
7569    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7570        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7571        try {
7572            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7573        } finally {
7574            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7575        }
7576    }
7577
7578    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7579        final File[] files = dir.listFiles();
7580        if (ArrayUtils.isEmpty(files)) {
7581            Log.d(TAG, "No files in app dir " + dir);
7582            return;
7583        }
7584
7585        if (DEBUG_PACKAGE_SCANNING) {
7586            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7587                    + " flags=0x" + Integer.toHexString(parseFlags));
7588        }
7589        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7590                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7591
7592        // Submit files for parsing in parallel
7593        int fileCount = 0;
7594        for (File file : files) {
7595            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7596                    && !PackageInstallerService.isStageName(file.getName());
7597            if (!isPackage) {
7598                // Ignore entries which are not packages
7599                continue;
7600            }
7601            parallelPackageParser.submit(file, parseFlags);
7602            fileCount++;
7603        }
7604
7605        // Process results one by one
7606        for (; fileCount > 0; fileCount--) {
7607            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7608            Throwable throwable = parseResult.throwable;
7609            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7610
7611            if (throwable == null) {
7612                // Static shared libraries have synthetic package names
7613                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7614                    renameStaticSharedLibraryPackage(parseResult.pkg);
7615                }
7616                try {
7617                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7618                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7619                                currentTime, null);
7620                    }
7621                } catch (PackageManagerException e) {
7622                    errorCode = e.error;
7623                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7624                }
7625            } else if (throwable instanceof PackageParser.PackageParserException) {
7626                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7627                        throwable;
7628                errorCode = e.error;
7629                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7630            } else {
7631                throw new IllegalStateException("Unexpected exception occurred while parsing "
7632                        + parseResult.scanFile, throwable);
7633            }
7634
7635            // Delete invalid userdata apps
7636            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7637                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7638                logCriticalInfo(Log.WARN,
7639                        "Deleting invalid package at " + parseResult.scanFile);
7640                removeCodePathLI(parseResult.scanFile);
7641            }
7642        }
7643        parallelPackageParser.close();
7644    }
7645
7646    private static File getSettingsProblemFile() {
7647        File dataDir = Environment.getDataDirectory();
7648        File systemDir = new File(dataDir, "system");
7649        File fname = new File(systemDir, "uiderrors.txt");
7650        return fname;
7651    }
7652
7653    static void reportSettingsProblem(int priority, String msg) {
7654        logCriticalInfo(priority, msg);
7655    }
7656
7657    public static void logCriticalInfo(int priority, String msg) {
7658        Slog.println(priority, TAG, msg);
7659        EventLogTags.writePmCriticalInfo(msg);
7660        try {
7661            File fname = getSettingsProblemFile();
7662            FileOutputStream out = new FileOutputStream(fname, true);
7663            PrintWriter pw = new FastPrintWriter(out);
7664            SimpleDateFormat formatter = new SimpleDateFormat();
7665            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7666            pw.println(dateString + ": " + msg);
7667            pw.close();
7668            FileUtils.setPermissions(
7669                    fname.toString(),
7670                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7671                    -1, -1);
7672        } catch (java.io.IOException e) {
7673        }
7674    }
7675
7676    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7677        if (srcFile.isDirectory()) {
7678            final File baseFile = new File(pkg.baseCodePath);
7679            long maxModifiedTime = baseFile.lastModified();
7680            if (pkg.splitCodePaths != null) {
7681                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7682                    final File splitFile = new File(pkg.splitCodePaths[i]);
7683                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7684                }
7685            }
7686            return maxModifiedTime;
7687        }
7688        return srcFile.lastModified();
7689    }
7690
7691    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7692            final int policyFlags) throws PackageManagerException {
7693        // When upgrading from pre-N MR1, verify the package time stamp using the package
7694        // directory and not the APK file.
7695        final long lastModifiedTime = mIsPreNMR1Upgrade
7696                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7697        if (ps != null
7698                && ps.codePath.equals(srcFile)
7699                && ps.timeStamp == lastModifiedTime
7700                && !isCompatSignatureUpdateNeeded(pkg)
7701                && !isRecoverSignatureUpdateNeeded(pkg)) {
7702            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7703            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7704            ArraySet<PublicKey> signingKs;
7705            synchronized (mPackages) {
7706                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7707            }
7708            if (ps.signatures.mSignatures != null
7709                    && ps.signatures.mSignatures.length != 0
7710                    && signingKs != null) {
7711                // Optimization: reuse the existing cached certificates
7712                // if the package appears to be unchanged.
7713                pkg.mSignatures = ps.signatures.mSignatures;
7714                pkg.mSigningKeys = signingKs;
7715                return;
7716            }
7717
7718            Slog.w(TAG, "PackageSetting for " + ps.name
7719                    + " is missing signatures.  Collecting certs again to recover them.");
7720        } else {
7721            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7722        }
7723
7724        try {
7725            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7726            PackageParser.collectCertificates(pkg, policyFlags);
7727        } catch (PackageParserException e) {
7728            throw PackageManagerException.from(e);
7729        } finally {
7730            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7731        }
7732    }
7733
7734    /**
7735     *  Traces a package scan.
7736     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7737     */
7738    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7739            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7740        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7741        try {
7742            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7743        } finally {
7744            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7745        }
7746    }
7747
7748    /**
7749     *  Scans a package and returns the newly parsed package.
7750     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7751     */
7752    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7753            long currentTime, UserHandle user) throws PackageManagerException {
7754        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7755        PackageParser pp = new PackageParser();
7756        pp.setSeparateProcesses(mSeparateProcesses);
7757        pp.setOnlyCoreApps(mOnlyCore);
7758        pp.setDisplayMetrics(mMetrics);
7759        pp.setCallback(mPackageParserCallback);
7760
7761        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7762            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7763        }
7764
7765        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7766        final PackageParser.Package pkg;
7767        try {
7768            pkg = pp.parsePackage(scanFile, parseFlags);
7769        } catch (PackageParserException e) {
7770            throw PackageManagerException.from(e);
7771        } finally {
7772            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7773        }
7774
7775        // Static shared libraries have synthetic package names
7776        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7777            renameStaticSharedLibraryPackage(pkg);
7778        }
7779
7780        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7781    }
7782
7783    /**
7784     *  Scans a package and returns the newly parsed package.
7785     *  @throws PackageManagerException on a parse error.
7786     */
7787    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7788            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7789            throws PackageManagerException {
7790        // If the package has children and this is the first dive in the function
7791        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7792        // packages (parent and children) would be successfully scanned before the
7793        // actual scan since scanning mutates internal state and we want to atomically
7794        // install the package and its children.
7795        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7796            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7797                scanFlags |= SCAN_CHECK_ONLY;
7798            }
7799        } else {
7800            scanFlags &= ~SCAN_CHECK_ONLY;
7801        }
7802
7803        // Scan the parent
7804        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7805                scanFlags, currentTime, user);
7806
7807        // Scan the children
7808        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7809        for (int i = 0; i < childCount; i++) {
7810            PackageParser.Package childPackage = pkg.childPackages.get(i);
7811            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7812                    currentTime, user);
7813        }
7814
7815
7816        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7817            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7818        }
7819
7820        return scannedPkg;
7821    }
7822
7823    /**
7824     *  Scans a package and returns the newly parsed package.
7825     *  @throws PackageManagerException on a parse error.
7826     */
7827    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7828            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7829            throws PackageManagerException {
7830        PackageSetting ps = null;
7831        PackageSetting updatedPkg;
7832        // reader
7833        synchronized (mPackages) {
7834            // Look to see if we already know about this package.
7835            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7836            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7837                // This package has been renamed to its original name.  Let's
7838                // use that.
7839                ps = mSettings.getPackageLPr(oldName);
7840            }
7841            // If there was no original package, see one for the real package name.
7842            if (ps == null) {
7843                ps = mSettings.getPackageLPr(pkg.packageName);
7844            }
7845            // Check to see if this package could be hiding/updating a system
7846            // package.  Must look for it either under the original or real
7847            // package name depending on our state.
7848            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7849            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7850
7851            // If this is a package we don't know about on the system partition, we
7852            // may need to remove disabled child packages on the system partition
7853            // or may need to not add child packages if the parent apk is updated
7854            // on the data partition and no longer defines this child package.
7855            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7856                // If this is a parent package for an updated system app and this system
7857                // app got an OTA update which no longer defines some of the child packages
7858                // we have to prune them from the disabled system packages.
7859                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7860                if (disabledPs != null) {
7861                    final int scannedChildCount = (pkg.childPackages != null)
7862                            ? pkg.childPackages.size() : 0;
7863                    final int disabledChildCount = disabledPs.childPackageNames != null
7864                            ? disabledPs.childPackageNames.size() : 0;
7865                    for (int i = 0; i < disabledChildCount; i++) {
7866                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7867                        boolean disabledPackageAvailable = false;
7868                        for (int j = 0; j < scannedChildCount; j++) {
7869                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7870                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7871                                disabledPackageAvailable = true;
7872                                break;
7873                            }
7874                         }
7875                         if (!disabledPackageAvailable) {
7876                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7877                         }
7878                    }
7879                }
7880            }
7881        }
7882
7883        boolean updatedPkgBetter = false;
7884        // First check if this is a system package that may involve an update
7885        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7886            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7887            // it needs to drop FLAG_PRIVILEGED.
7888            if (locationIsPrivileged(scanFile)) {
7889                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7890            } else {
7891                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7892            }
7893
7894            if (ps != null && !ps.codePath.equals(scanFile)) {
7895                // The path has changed from what was last scanned...  check the
7896                // version of the new path against what we have stored to determine
7897                // what to do.
7898                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7899                if (pkg.mVersionCode <= ps.versionCode) {
7900                    // The system package has been updated and the code path does not match
7901                    // Ignore entry. Skip it.
7902                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7903                            + " ignored: updated version " + ps.versionCode
7904                            + " better than this " + pkg.mVersionCode);
7905                    if (!updatedPkg.codePath.equals(scanFile)) {
7906                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7907                                + ps.name + " changing from " + updatedPkg.codePathString
7908                                + " to " + scanFile);
7909                        updatedPkg.codePath = scanFile;
7910                        updatedPkg.codePathString = scanFile.toString();
7911                        updatedPkg.resourcePath = scanFile;
7912                        updatedPkg.resourcePathString = scanFile.toString();
7913                    }
7914                    updatedPkg.pkg = pkg;
7915                    updatedPkg.versionCode = pkg.mVersionCode;
7916
7917                    // Update the disabled system child packages to point to the package too.
7918                    final int childCount = updatedPkg.childPackageNames != null
7919                            ? updatedPkg.childPackageNames.size() : 0;
7920                    for (int i = 0; i < childCount; i++) {
7921                        String childPackageName = updatedPkg.childPackageNames.get(i);
7922                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7923                                childPackageName);
7924                        if (updatedChildPkg != null) {
7925                            updatedChildPkg.pkg = pkg;
7926                            updatedChildPkg.versionCode = pkg.mVersionCode;
7927                        }
7928                    }
7929
7930                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7931                            + scanFile + " ignored: updated version " + ps.versionCode
7932                            + " better than this " + pkg.mVersionCode);
7933                } else {
7934                    // The current app on the system partition is better than
7935                    // what we have updated to on the data partition; switch
7936                    // back to the system partition version.
7937                    // At this point, its safely assumed that package installation for
7938                    // apps in system partition will go through. If not there won't be a working
7939                    // version of the app
7940                    // writer
7941                    synchronized (mPackages) {
7942                        // Just remove the loaded entries from package lists.
7943                        mPackages.remove(ps.name);
7944                    }
7945
7946                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7947                            + " reverting from " + ps.codePathString
7948                            + ": new version " + pkg.mVersionCode
7949                            + " better than installed " + ps.versionCode);
7950
7951                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7952                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7953                    synchronized (mInstallLock) {
7954                        args.cleanUpResourcesLI();
7955                    }
7956                    synchronized (mPackages) {
7957                        mSettings.enableSystemPackageLPw(ps.name);
7958                    }
7959                    updatedPkgBetter = true;
7960                }
7961            }
7962        }
7963
7964        if (updatedPkg != null) {
7965            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7966            // initially
7967            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7968
7969            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7970            // flag set initially
7971            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7972                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7973            }
7974        }
7975
7976        // Verify certificates against what was last scanned
7977        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7978
7979        /*
7980         * A new system app appeared, but we already had a non-system one of the
7981         * same name installed earlier.
7982         */
7983        boolean shouldHideSystemApp = false;
7984        if (updatedPkg == null && ps != null
7985                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7986            /*
7987             * Check to make sure the signatures match first. If they don't,
7988             * wipe the installed application and its data.
7989             */
7990            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7991                    != PackageManager.SIGNATURE_MATCH) {
7992                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7993                        + " signatures don't match existing userdata copy; removing");
7994                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7995                        "scanPackageInternalLI")) {
7996                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7997                }
7998                ps = null;
7999            } else {
8000                /*
8001                 * If the newly-added system app is an older version than the
8002                 * already installed version, hide it. It will be scanned later
8003                 * and re-added like an update.
8004                 */
8005                if (pkg.mVersionCode <= ps.versionCode) {
8006                    shouldHideSystemApp = true;
8007                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8008                            + " but new version " + pkg.mVersionCode + " better than installed "
8009                            + ps.versionCode + "; hiding system");
8010                } else {
8011                    /*
8012                     * The newly found system app is a newer version that the
8013                     * one previously installed. Simply remove the
8014                     * already-installed application and replace it with our own
8015                     * while keeping the application data.
8016                     */
8017                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8018                            + " reverting from " + ps.codePathString + ": new version "
8019                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8020                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8021                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8022                    synchronized (mInstallLock) {
8023                        args.cleanUpResourcesLI();
8024                    }
8025                }
8026            }
8027        }
8028
8029        // The apk is forward locked (not public) if its code and resources
8030        // are kept in different files. (except for app in either system or
8031        // vendor path).
8032        // TODO grab this value from PackageSettings
8033        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8034            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8035                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8036            }
8037        }
8038
8039        // TODO: extend to support forward-locked splits
8040        String resourcePath = null;
8041        String baseResourcePath = null;
8042        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8043            if (ps != null && ps.resourcePathString != null) {
8044                resourcePath = ps.resourcePathString;
8045                baseResourcePath = ps.resourcePathString;
8046            } else {
8047                // Should not happen at all. Just log an error.
8048                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8049            }
8050        } else {
8051            resourcePath = pkg.codePath;
8052            baseResourcePath = pkg.baseCodePath;
8053        }
8054
8055        // Set application objects path explicitly.
8056        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8057        pkg.setApplicationInfoCodePath(pkg.codePath);
8058        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8059        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8060        pkg.setApplicationInfoResourcePath(resourcePath);
8061        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8062        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8063
8064        final int userId = ((user == null) ? 0 : user.getIdentifier());
8065        if (ps != null && ps.getInstantApp(userId)) {
8066            scanFlags |= SCAN_AS_INSTANT_APP;
8067        }
8068
8069        // Note that we invoke the following method only if we are about to unpack an application
8070        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8071                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8072
8073        /*
8074         * If the system app should be overridden by a previously installed
8075         * data, hide the system app now and let the /data/app scan pick it up
8076         * again.
8077         */
8078        if (shouldHideSystemApp) {
8079            synchronized (mPackages) {
8080                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8081            }
8082        }
8083
8084        return scannedPkg;
8085    }
8086
8087    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8088        // Derive the new package synthetic package name
8089        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8090                + pkg.staticSharedLibVersion);
8091    }
8092
8093    private static String fixProcessName(String defProcessName,
8094            String processName) {
8095        if (processName == null) {
8096            return defProcessName;
8097        }
8098        return processName;
8099    }
8100
8101    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8102            throws PackageManagerException {
8103        if (pkgSetting.signatures.mSignatures != null) {
8104            // Already existing package. Make sure signatures match
8105            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8106                    == PackageManager.SIGNATURE_MATCH;
8107            if (!match) {
8108                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8109                        == PackageManager.SIGNATURE_MATCH;
8110            }
8111            if (!match) {
8112                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8113                        == PackageManager.SIGNATURE_MATCH;
8114            }
8115            if (!match) {
8116                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8117                        + pkg.packageName + " signatures do not match the "
8118                        + "previously installed version; ignoring!");
8119            }
8120        }
8121
8122        // Check for shared user signatures
8123        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8124            // Already existing package. Make sure signatures match
8125            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8126                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8127            if (!match) {
8128                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8129                        == PackageManager.SIGNATURE_MATCH;
8130            }
8131            if (!match) {
8132                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8133                        == PackageManager.SIGNATURE_MATCH;
8134            }
8135            if (!match) {
8136                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8137                        "Package " + pkg.packageName
8138                        + " has no signatures that match those in shared user "
8139                        + pkgSetting.sharedUser.name + "; ignoring!");
8140            }
8141        }
8142    }
8143
8144    /**
8145     * Enforces that only the system UID or root's UID can call a method exposed
8146     * via Binder.
8147     *
8148     * @param message used as message if SecurityException is thrown
8149     * @throws SecurityException if the caller is not system or root
8150     */
8151    private static final void enforceSystemOrRoot(String message) {
8152        final int uid = Binder.getCallingUid();
8153        if (uid != Process.SYSTEM_UID && uid != 0) {
8154            throw new SecurityException(message);
8155        }
8156    }
8157
8158    @Override
8159    public void performFstrimIfNeeded() {
8160        enforceSystemOrRoot("Only the system can request fstrim");
8161
8162        // Before everything else, see whether we need to fstrim.
8163        try {
8164            IStorageManager sm = PackageHelper.getStorageManager();
8165            if (sm != null) {
8166                boolean doTrim = false;
8167                final long interval = android.provider.Settings.Global.getLong(
8168                        mContext.getContentResolver(),
8169                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8170                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8171                if (interval > 0) {
8172                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8173                    if (timeSinceLast > interval) {
8174                        doTrim = true;
8175                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8176                                + "; running immediately");
8177                    }
8178                }
8179                if (doTrim) {
8180                    final boolean dexOptDialogShown;
8181                    synchronized (mPackages) {
8182                        dexOptDialogShown = mDexOptDialogShown;
8183                    }
8184                    if (!isFirstBoot() && dexOptDialogShown) {
8185                        try {
8186                            ActivityManager.getService().showBootMessage(
8187                                    mContext.getResources().getString(
8188                                            R.string.android_upgrading_fstrim), true);
8189                        } catch (RemoteException e) {
8190                        }
8191                    }
8192                    sm.runMaintenance();
8193                }
8194            } else {
8195                Slog.e(TAG, "storageManager service unavailable!");
8196            }
8197        } catch (RemoteException e) {
8198            // Can't happen; StorageManagerService is local
8199        }
8200    }
8201
8202    @Override
8203    public void updatePackagesIfNeeded() {
8204        enforceSystemOrRoot("Only the system can request package update");
8205
8206        // We need to re-extract after an OTA.
8207        boolean causeUpgrade = isUpgrade();
8208
8209        // First boot or factory reset.
8210        // Note: we also handle devices that are upgrading to N right now as if it is their
8211        //       first boot, as they do not have profile data.
8212        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8213
8214        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8215        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8216
8217        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8218            return;
8219        }
8220
8221        List<PackageParser.Package> pkgs;
8222        synchronized (mPackages) {
8223            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8224        }
8225
8226        final long startTime = System.nanoTime();
8227        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8228                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8229
8230        final int elapsedTimeSeconds =
8231                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8232
8233        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8234        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8235        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8236        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8237        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8238    }
8239
8240    /**
8241     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8242     * containing statistics about the invocation. The array consists of three elements,
8243     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8244     * and {@code numberOfPackagesFailed}.
8245     */
8246    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8247            String compilerFilter) {
8248
8249        int numberOfPackagesVisited = 0;
8250        int numberOfPackagesOptimized = 0;
8251        int numberOfPackagesSkipped = 0;
8252        int numberOfPackagesFailed = 0;
8253        final int numberOfPackagesToDexopt = pkgs.size();
8254
8255        for (PackageParser.Package pkg : pkgs) {
8256            numberOfPackagesVisited++;
8257
8258            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8259                if (DEBUG_DEXOPT) {
8260                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8261                }
8262                numberOfPackagesSkipped++;
8263                continue;
8264            }
8265
8266            if (DEBUG_DEXOPT) {
8267                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8268                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8269            }
8270
8271            if (showDialog) {
8272                try {
8273                    ActivityManager.getService().showBootMessage(
8274                            mContext.getResources().getString(R.string.android_upgrading_apk,
8275                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8276                } catch (RemoteException e) {
8277                }
8278                synchronized (mPackages) {
8279                    mDexOptDialogShown = true;
8280                }
8281            }
8282
8283            // If the OTA updates a system app which was previously preopted to a non-preopted state
8284            // the app might end up being verified at runtime. That's because by default the apps
8285            // are verify-profile but for preopted apps there's no profile.
8286            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8287            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8288            // filter (by default interpret-only).
8289            // Note that at this stage unused apps are already filtered.
8290            if (isSystemApp(pkg) &&
8291                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8292                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8293                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8294            }
8295
8296            // checkProfiles is false to avoid merging profiles during boot which
8297            // might interfere with background compilation (b/28612421).
8298            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8299            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8300            // trade-off worth doing to save boot time work.
8301            int dexOptStatus = performDexOptTraced(pkg.packageName,
8302                    false /* checkProfiles */,
8303                    compilerFilter,
8304                    false /* force */);
8305            switch (dexOptStatus) {
8306                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8307                    numberOfPackagesOptimized++;
8308                    break;
8309                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8310                    numberOfPackagesSkipped++;
8311                    break;
8312                case PackageDexOptimizer.DEX_OPT_FAILED:
8313                    numberOfPackagesFailed++;
8314                    break;
8315                default:
8316                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8317                    break;
8318            }
8319        }
8320
8321        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8322                numberOfPackagesFailed };
8323    }
8324
8325    @Override
8326    public void notifyPackageUse(String packageName, int reason) {
8327        synchronized (mPackages) {
8328            PackageParser.Package p = mPackages.get(packageName);
8329            if (p == null) {
8330                return;
8331            }
8332            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8333        }
8334    }
8335
8336    @Override
8337    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8338        int userId = UserHandle.getCallingUserId();
8339        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8340        if (ai == null) {
8341            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8342                + loadingPackageName + ", user=" + userId);
8343            return;
8344        }
8345        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8346    }
8347
8348    // TODO: this is not used nor needed. Delete it.
8349    @Override
8350    public boolean performDexOptIfNeeded(String packageName) {
8351        int dexOptStatus = performDexOptTraced(packageName,
8352                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8353        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8354    }
8355
8356    @Override
8357    public boolean performDexOpt(String packageName,
8358            boolean checkProfiles, int compileReason, boolean force) {
8359        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8360                getCompilerFilterForReason(compileReason), force);
8361        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8362    }
8363
8364    @Override
8365    public boolean performDexOptMode(String packageName,
8366            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8367        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8368                targetCompilerFilter, force);
8369        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8370    }
8371
8372    private int performDexOptTraced(String packageName,
8373                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8374        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8375        try {
8376            return performDexOptInternal(packageName, checkProfiles,
8377                    targetCompilerFilter, force);
8378        } finally {
8379            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8380        }
8381    }
8382
8383    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8384    // if the package can now be considered up to date for the given filter.
8385    private int performDexOptInternal(String packageName,
8386                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8387        PackageParser.Package p;
8388        synchronized (mPackages) {
8389            p = mPackages.get(packageName);
8390            if (p == null) {
8391                // Package could not be found. Report failure.
8392                return PackageDexOptimizer.DEX_OPT_FAILED;
8393            }
8394            mPackageUsage.maybeWriteAsync(mPackages);
8395            mCompilerStats.maybeWriteAsync();
8396        }
8397        long callingId = Binder.clearCallingIdentity();
8398        try {
8399            synchronized (mInstallLock) {
8400                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8401                        targetCompilerFilter, force);
8402            }
8403        } finally {
8404            Binder.restoreCallingIdentity(callingId);
8405        }
8406    }
8407
8408    public ArraySet<String> getOptimizablePackages() {
8409        ArraySet<String> pkgs = new ArraySet<String>();
8410        synchronized (mPackages) {
8411            for (PackageParser.Package p : mPackages.values()) {
8412                if (PackageDexOptimizer.canOptimizePackage(p)) {
8413                    pkgs.add(p.packageName);
8414                }
8415            }
8416        }
8417        return pkgs;
8418    }
8419
8420    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8421            boolean checkProfiles, String targetCompilerFilter,
8422            boolean force) {
8423        // Select the dex optimizer based on the force parameter.
8424        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8425        //       allocate an object here.
8426        PackageDexOptimizer pdo = force
8427                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8428                : mPackageDexOptimizer;
8429
8430        // Optimize all dependencies first. Note: we ignore the return value and march on
8431        // on errors.
8432        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8433        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8434        if (!deps.isEmpty()) {
8435            for (PackageParser.Package depPackage : deps) {
8436                // TODO: Analyze and investigate if we (should) profile libraries.
8437                // Currently this will do a full compilation of the library by default.
8438                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8439                        false /* checkProfiles */,
8440                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8441                        getOrCreateCompilerPackageStats(depPackage),
8442                        mDexManager.isUsedByOtherApps(p.packageName));
8443            }
8444        }
8445        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8446                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8447                mDexManager.isUsedByOtherApps(p.packageName));
8448    }
8449
8450    // Performs dexopt on the used secondary dex files belonging to the given package.
8451    // Returns true if all dex files were process successfully (which could mean either dexopt or
8452    // skip). Returns false if any of the files caused errors.
8453    @Override
8454    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8455            boolean force) {
8456        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8457    }
8458
8459    /**
8460     * Reconcile the information we have about the secondary dex files belonging to
8461     * {@code packagName} and the actual dex files. For all dex files that were
8462     * deleted, update the internal records and delete the generated oat files.
8463     */
8464    @Override
8465    public void reconcileSecondaryDexFiles(String packageName) {
8466        mDexManager.reconcileSecondaryDexFiles(packageName);
8467    }
8468
8469    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8470    // a reference there.
8471    /*package*/ DexManager getDexManager() {
8472        return mDexManager;
8473    }
8474
8475    /**
8476     * Execute the background dexopt job immediately.
8477     */
8478    @Override
8479    public boolean runBackgroundDexoptJob() {
8480        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8481    }
8482
8483    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8484        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8485                || p.usesStaticLibraries != null) {
8486            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8487            Set<String> collectedNames = new HashSet<>();
8488            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8489
8490            retValue.remove(p);
8491
8492            return retValue;
8493        } else {
8494            return Collections.emptyList();
8495        }
8496    }
8497
8498    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8499            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8500        if (!collectedNames.contains(p.packageName)) {
8501            collectedNames.add(p.packageName);
8502            collected.add(p);
8503
8504            if (p.usesLibraries != null) {
8505                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8506                        null, collected, collectedNames);
8507            }
8508            if (p.usesOptionalLibraries != null) {
8509                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8510                        null, collected, collectedNames);
8511            }
8512            if (p.usesStaticLibraries != null) {
8513                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8514                        p.usesStaticLibrariesVersions, collected, collectedNames);
8515            }
8516        }
8517    }
8518
8519    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8520            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8521        final int libNameCount = libs.size();
8522        for (int i = 0; i < libNameCount; i++) {
8523            String libName = libs.get(i);
8524            int version = (versions != null && versions.length == libNameCount)
8525                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8526            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8527            if (libPkg != null) {
8528                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8529            }
8530        }
8531    }
8532
8533    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8534        synchronized (mPackages) {
8535            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8536            if (libEntry != null) {
8537                return mPackages.get(libEntry.apk);
8538            }
8539            return null;
8540        }
8541    }
8542
8543    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8544        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8545        if (versionedLib == null) {
8546            return null;
8547        }
8548        return versionedLib.get(version);
8549    }
8550
8551    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8552        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8553                pkg.staticSharedLibName);
8554        if (versionedLib == null) {
8555            return null;
8556        }
8557        int previousLibVersion = -1;
8558        final int versionCount = versionedLib.size();
8559        for (int i = 0; i < versionCount; i++) {
8560            final int libVersion = versionedLib.keyAt(i);
8561            if (libVersion < pkg.staticSharedLibVersion) {
8562                previousLibVersion = Math.max(previousLibVersion, libVersion);
8563            }
8564        }
8565        if (previousLibVersion >= 0) {
8566            return versionedLib.get(previousLibVersion);
8567        }
8568        return null;
8569    }
8570
8571    public void shutdown() {
8572        mPackageUsage.writeNow(mPackages);
8573        mCompilerStats.writeNow();
8574    }
8575
8576    @Override
8577    public void dumpProfiles(String packageName) {
8578        PackageParser.Package pkg;
8579        synchronized (mPackages) {
8580            pkg = mPackages.get(packageName);
8581            if (pkg == null) {
8582                throw new IllegalArgumentException("Unknown package: " + packageName);
8583            }
8584        }
8585        /* Only the shell, root, or the app user should be able to dump profiles. */
8586        int callingUid = Binder.getCallingUid();
8587        if (callingUid != Process.SHELL_UID &&
8588            callingUid != Process.ROOT_UID &&
8589            callingUid != pkg.applicationInfo.uid) {
8590            throw new SecurityException("dumpProfiles");
8591        }
8592
8593        synchronized (mInstallLock) {
8594            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8595            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8596            try {
8597                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8598                String codePaths = TextUtils.join(";", allCodePaths);
8599                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8600            } catch (InstallerException e) {
8601                Slog.w(TAG, "Failed to dump profiles", e);
8602            }
8603            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8604        }
8605    }
8606
8607    @Override
8608    public void forceDexOpt(String packageName) {
8609        enforceSystemOrRoot("forceDexOpt");
8610
8611        PackageParser.Package pkg;
8612        synchronized (mPackages) {
8613            pkg = mPackages.get(packageName);
8614            if (pkg == null) {
8615                throw new IllegalArgumentException("Unknown package: " + packageName);
8616            }
8617        }
8618
8619        synchronized (mInstallLock) {
8620            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8621
8622            // Whoever is calling forceDexOpt wants a fully compiled package.
8623            // Don't use profiles since that may cause compilation to be skipped.
8624            final int res = performDexOptInternalWithDependenciesLI(pkg,
8625                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8626                    true /* force */);
8627
8628            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8629            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8630                throw new IllegalStateException("Failed to dexopt: " + res);
8631            }
8632        }
8633    }
8634
8635    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8636        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8637            Slog.w(TAG, "Unable to update from " + oldPkg.name
8638                    + " to " + newPkg.packageName
8639                    + ": old package not in system partition");
8640            return false;
8641        } else if (mPackages.get(oldPkg.name) != null) {
8642            Slog.w(TAG, "Unable to update from " + oldPkg.name
8643                    + " to " + newPkg.packageName
8644                    + ": old package still exists");
8645            return false;
8646        }
8647        return true;
8648    }
8649
8650    void removeCodePathLI(File codePath) {
8651        if (codePath.isDirectory()) {
8652            try {
8653                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8654            } catch (InstallerException e) {
8655                Slog.w(TAG, "Failed to remove code path", e);
8656            }
8657        } else {
8658            codePath.delete();
8659        }
8660    }
8661
8662    private int[] resolveUserIds(int userId) {
8663        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8664    }
8665
8666    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8667        if (pkg == null) {
8668            Slog.wtf(TAG, "Package was null!", new Throwable());
8669            return;
8670        }
8671        clearAppDataLeafLIF(pkg, userId, flags);
8672        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8673        for (int i = 0; i < childCount; i++) {
8674            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8675        }
8676    }
8677
8678    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8679        final PackageSetting ps;
8680        synchronized (mPackages) {
8681            ps = mSettings.mPackages.get(pkg.packageName);
8682        }
8683        for (int realUserId : resolveUserIds(userId)) {
8684            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8685            try {
8686                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8687                        ceDataInode);
8688            } catch (InstallerException e) {
8689                Slog.w(TAG, String.valueOf(e));
8690            }
8691        }
8692    }
8693
8694    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8695        if (pkg == null) {
8696            Slog.wtf(TAG, "Package was null!", new Throwable());
8697            return;
8698        }
8699        destroyAppDataLeafLIF(pkg, userId, flags);
8700        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8701        for (int i = 0; i < childCount; i++) {
8702            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8703        }
8704    }
8705
8706    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8707        final PackageSetting ps;
8708        synchronized (mPackages) {
8709            ps = mSettings.mPackages.get(pkg.packageName);
8710        }
8711        for (int realUserId : resolveUserIds(userId)) {
8712            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8713            try {
8714                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8715                        ceDataInode);
8716            } catch (InstallerException e) {
8717                Slog.w(TAG, String.valueOf(e));
8718            }
8719            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8720        }
8721    }
8722
8723    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8724        if (pkg == null) {
8725            Slog.wtf(TAG, "Package was null!", new Throwable());
8726            return;
8727        }
8728        destroyAppProfilesLeafLIF(pkg);
8729        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8730        for (int i = 0; i < childCount; i++) {
8731            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8732        }
8733    }
8734
8735    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8736        try {
8737            mInstaller.destroyAppProfiles(pkg.packageName);
8738        } catch (InstallerException e) {
8739            Slog.w(TAG, String.valueOf(e));
8740        }
8741    }
8742
8743    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8744        if (pkg == null) {
8745            Slog.wtf(TAG, "Package was null!", new Throwable());
8746            return;
8747        }
8748        clearAppProfilesLeafLIF(pkg);
8749        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8750        for (int i = 0; i < childCount; i++) {
8751            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8752        }
8753    }
8754
8755    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8756        try {
8757            mInstaller.clearAppProfiles(pkg.packageName);
8758        } catch (InstallerException e) {
8759            Slog.w(TAG, String.valueOf(e));
8760        }
8761    }
8762
8763    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8764            long lastUpdateTime) {
8765        // Set parent install/update time
8766        PackageSetting ps = (PackageSetting) pkg.mExtras;
8767        if (ps != null) {
8768            ps.firstInstallTime = firstInstallTime;
8769            ps.lastUpdateTime = lastUpdateTime;
8770        }
8771        // Set children install/update time
8772        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8773        for (int i = 0; i < childCount; i++) {
8774            PackageParser.Package childPkg = pkg.childPackages.get(i);
8775            ps = (PackageSetting) childPkg.mExtras;
8776            if (ps != null) {
8777                ps.firstInstallTime = firstInstallTime;
8778                ps.lastUpdateTime = lastUpdateTime;
8779            }
8780        }
8781    }
8782
8783    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8784            PackageParser.Package changingLib) {
8785        if (file.path != null) {
8786            usesLibraryFiles.add(file.path);
8787            return;
8788        }
8789        PackageParser.Package p = mPackages.get(file.apk);
8790        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8791            // If we are doing this while in the middle of updating a library apk,
8792            // then we need to make sure to use that new apk for determining the
8793            // dependencies here.  (We haven't yet finished committing the new apk
8794            // to the package manager state.)
8795            if (p == null || p.packageName.equals(changingLib.packageName)) {
8796                p = changingLib;
8797            }
8798        }
8799        if (p != null) {
8800            usesLibraryFiles.addAll(p.getAllCodePaths());
8801        }
8802    }
8803
8804    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8805            PackageParser.Package changingLib) throws PackageManagerException {
8806        if (pkg == null) {
8807            return;
8808        }
8809        ArraySet<String> usesLibraryFiles = null;
8810        if (pkg.usesLibraries != null) {
8811            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8812                    null, null, pkg.packageName, changingLib, true, null);
8813        }
8814        if (pkg.usesStaticLibraries != null) {
8815            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8816                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8817                    pkg.packageName, changingLib, true, usesLibraryFiles);
8818        }
8819        if (pkg.usesOptionalLibraries != null) {
8820            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8821                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8822        }
8823        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8824            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8825        } else {
8826            pkg.usesLibraryFiles = null;
8827        }
8828    }
8829
8830    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8831            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8832            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8833            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8834            throws PackageManagerException {
8835        final int libCount = requestedLibraries.size();
8836        for (int i = 0; i < libCount; i++) {
8837            final String libName = requestedLibraries.get(i);
8838            final int libVersion = requiredVersions != null ? requiredVersions[i]
8839                    : SharedLibraryInfo.VERSION_UNDEFINED;
8840            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8841            if (libEntry == null) {
8842                if (required) {
8843                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8844                            "Package " + packageName + " requires unavailable shared library "
8845                                    + libName + "; failing!");
8846                } else {
8847                    Slog.w(TAG, "Package " + packageName
8848                            + " desires unavailable shared library "
8849                            + libName + "; ignoring!");
8850                }
8851            } else {
8852                if (requiredVersions != null && requiredCertDigests != null) {
8853                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8854                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8855                            "Package " + packageName + " requires unavailable static shared"
8856                                    + " library " + libName + " version "
8857                                    + libEntry.info.getVersion() + "; failing!");
8858                    }
8859
8860                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8861                    if (libPkg == null) {
8862                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8863                                "Package " + packageName + " requires unavailable static shared"
8864                                        + " library; failing!");
8865                    }
8866
8867                    String expectedCertDigest = requiredCertDigests[i];
8868                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8869                                libPkg.mSignatures[0]);
8870                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8871                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8872                                "Package " + packageName + " requires differently signed" +
8873                                        " static shared library; failing!");
8874                    }
8875                }
8876
8877                if (outUsedLibraries == null) {
8878                    outUsedLibraries = new ArraySet<>();
8879                }
8880                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8881            }
8882        }
8883        return outUsedLibraries;
8884    }
8885
8886    private static boolean hasString(List<String> list, List<String> which) {
8887        if (list == null) {
8888            return false;
8889        }
8890        for (int i=list.size()-1; i>=0; i--) {
8891            for (int j=which.size()-1; j>=0; j--) {
8892                if (which.get(j).equals(list.get(i))) {
8893                    return true;
8894                }
8895            }
8896        }
8897        return false;
8898    }
8899
8900    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8901            PackageParser.Package changingPkg) {
8902        ArrayList<PackageParser.Package> res = null;
8903        for (PackageParser.Package pkg : mPackages.values()) {
8904            if (changingPkg != null
8905                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8906                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8907                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8908                            changingPkg.staticSharedLibName)) {
8909                return null;
8910            }
8911            if (res == null) {
8912                res = new ArrayList<>();
8913            }
8914            res.add(pkg);
8915            try {
8916                updateSharedLibrariesLPr(pkg, changingPkg);
8917            } catch (PackageManagerException e) {
8918                // If a system app update or an app and a required lib missing we
8919                // delete the package and for updated system apps keep the data as
8920                // it is better for the user to reinstall than to be in an limbo
8921                // state. Also libs disappearing under an app should never happen
8922                // - just in case.
8923                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8924                    final int flags = pkg.isUpdatedSystemApp()
8925                            ? PackageManager.DELETE_KEEP_DATA : 0;
8926                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8927                            flags , null, true, null);
8928                }
8929                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8930            }
8931        }
8932        return res;
8933    }
8934
8935    /**
8936     * Derive the value of the {@code cpuAbiOverride} based on the provided
8937     * value and an optional stored value from the package settings.
8938     */
8939    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8940        String cpuAbiOverride = null;
8941
8942        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8943            cpuAbiOverride = null;
8944        } else if (abiOverride != null) {
8945            cpuAbiOverride = abiOverride;
8946        } else if (settings != null) {
8947            cpuAbiOverride = settings.cpuAbiOverrideString;
8948        }
8949
8950        return cpuAbiOverride;
8951    }
8952
8953    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8954            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8955                    throws PackageManagerException {
8956        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8957        // If the package has children and this is the first dive in the function
8958        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8959        // whether all packages (parent and children) would be successfully scanned
8960        // before the actual scan since scanning mutates internal state and we want
8961        // to atomically install the package and its children.
8962        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8963            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8964                scanFlags |= SCAN_CHECK_ONLY;
8965            }
8966        } else {
8967            scanFlags &= ~SCAN_CHECK_ONLY;
8968        }
8969
8970        final PackageParser.Package scannedPkg;
8971        try {
8972            // Scan the parent
8973            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8974            // Scan the children
8975            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8976            for (int i = 0; i < childCount; i++) {
8977                PackageParser.Package childPkg = pkg.childPackages.get(i);
8978                scanPackageLI(childPkg, policyFlags,
8979                        scanFlags, currentTime, user);
8980            }
8981        } finally {
8982            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8983        }
8984
8985        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8986            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8987        }
8988
8989        return scannedPkg;
8990    }
8991
8992    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8993            int scanFlags, long currentTime, @Nullable UserHandle user)
8994                    throws PackageManagerException {
8995        boolean success = false;
8996        try {
8997            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8998                    currentTime, user);
8999            success = true;
9000            return res;
9001        } finally {
9002            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9003                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9004                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9005                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9006                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9007            }
9008        }
9009    }
9010
9011    /**
9012     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9013     */
9014    private static boolean apkHasCode(String fileName) {
9015        StrictJarFile jarFile = null;
9016        try {
9017            jarFile = new StrictJarFile(fileName,
9018                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9019            return jarFile.findEntry("classes.dex") != null;
9020        } catch (IOException ignore) {
9021        } finally {
9022            try {
9023                if (jarFile != null) {
9024                    jarFile.close();
9025                }
9026            } catch (IOException ignore) {}
9027        }
9028        return false;
9029    }
9030
9031    /**
9032     * Enforces code policy for the package. This ensures that if an APK has
9033     * declared hasCode="true" in its manifest that the APK actually contains
9034     * code.
9035     *
9036     * @throws PackageManagerException If bytecode could not be found when it should exist
9037     */
9038    private static void assertCodePolicy(PackageParser.Package pkg)
9039            throws PackageManagerException {
9040        final boolean shouldHaveCode =
9041                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9042        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9043            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9044                    "Package " + pkg.baseCodePath + " code is missing");
9045        }
9046
9047        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9048            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9049                final boolean splitShouldHaveCode =
9050                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9051                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9052                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9053                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9054                }
9055            }
9056        }
9057    }
9058
9059    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9060            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9061                    throws PackageManagerException {
9062        if (DEBUG_PACKAGE_SCANNING) {
9063            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9064                Log.d(TAG, "Scanning package " + pkg.packageName);
9065        }
9066
9067        applyPolicy(pkg, policyFlags);
9068
9069        assertPackageIsValid(pkg, policyFlags, scanFlags);
9070
9071        // Initialize package source and resource directories
9072        final File scanFile = new File(pkg.codePath);
9073        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9074        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9075
9076        SharedUserSetting suid = null;
9077        PackageSetting pkgSetting = null;
9078
9079        // Getting the package setting may have a side-effect, so if we
9080        // are only checking if scan would succeed, stash a copy of the
9081        // old setting to restore at the end.
9082        PackageSetting nonMutatedPs = null;
9083
9084        // We keep references to the derived CPU Abis from settings in oder to reuse
9085        // them in the case where we're not upgrading or booting for the first time.
9086        String primaryCpuAbiFromSettings = null;
9087        String secondaryCpuAbiFromSettings = null;
9088
9089        // writer
9090        synchronized (mPackages) {
9091            if (pkg.mSharedUserId != null) {
9092                // SIDE EFFECTS; may potentially allocate a new shared user
9093                suid = mSettings.getSharedUserLPw(
9094                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9095                if (DEBUG_PACKAGE_SCANNING) {
9096                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9097                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9098                                + "): packages=" + suid.packages);
9099                }
9100            }
9101
9102            // Check if we are renaming from an original package name.
9103            PackageSetting origPackage = null;
9104            String realName = null;
9105            if (pkg.mOriginalPackages != null) {
9106                // This package may need to be renamed to a previously
9107                // installed name.  Let's check on that...
9108                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9109                if (pkg.mOriginalPackages.contains(renamed)) {
9110                    // This package had originally been installed as the
9111                    // original name, and we have already taken care of
9112                    // transitioning to the new one.  Just update the new
9113                    // one to continue using the old name.
9114                    realName = pkg.mRealPackage;
9115                    if (!pkg.packageName.equals(renamed)) {
9116                        // Callers into this function may have already taken
9117                        // care of renaming the package; only do it here if
9118                        // it is not already done.
9119                        pkg.setPackageName(renamed);
9120                    }
9121                } else {
9122                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9123                        if ((origPackage = mSettings.getPackageLPr(
9124                                pkg.mOriginalPackages.get(i))) != null) {
9125                            // We do have the package already installed under its
9126                            // original name...  should we use it?
9127                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9128                                // New package is not compatible with original.
9129                                origPackage = null;
9130                                continue;
9131                            } else if (origPackage.sharedUser != null) {
9132                                // Make sure uid is compatible between packages.
9133                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9134                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9135                                            + " to " + pkg.packageName + ": old uid "
9136                                            + origPackage.sharedUser.name
9137                                            + " differs from " + pkg.mSharedUserId);
9138                                    origPackage = null;
9139                                    continue;
9140                                }
9141                                // TODO: Add case when shared user id is added [b/28144775]
9142                            } else {
9143                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9144                                        + pkg.packageName + " to old name " + origPackage.name);
9145                            }
9146                            break;
9147                        }
9148                    }
9149                }
9150            }
9151
9152            if (mTransferedPackages.contains(pkg.packageName)) {
9153                Slog.w(TAG, "Package " + pkg.packageName
9154                        + " was transferred to another, but its .apk remains");
9155            }
9156
9157            // See comments in nonMutatedPs declaration
9158            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9159                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9160                if (foundPs != null) {
9161                    nonMutatedPs = new PackageSetting(foundPs);
9162                }
9163            }
9164
9165            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9166                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9167                if (foundPs != null) {
9168                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9169                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9170                }
9171            }
9172
9173            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9174            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9175                PackageManagerService.reportSettingsProblem(Log.WARN,
9176                        "Package " + pkg.packageName + " shared user changed from "
9177                                + (pkgSetting.sharedUser != null
9178                                        ? pkgSetting.sharedUser.name : "<nothing>")
9179                                + " to "
9180                                + (suid != null ? suid.name : "<nothing>")
9181                                + "; replacing with new");
9182                pkgSetting = null;
9183            }
9184            final PackageSetting oldPkgSetting =
9185                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9186            final PackageSetting disabledPkgSetting =
9187                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9188
9189            String[] usesStaticLibraries = null;
9190            if (pkg.usesStaticLibraries != null) {
9191                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9192                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9193            }
9194
9195            if (pkgSetting == null) {
9196                final String parentPackageName = (pkg.parentPackage != null)
9197                        ? pkg.parentPackage.packageName : null;
9198                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9199                // REMOVE SharedUserSetting from method; update in a separate call
9200                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9201                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9202                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9203                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9204                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9205                        true /*allowInstall*/, instantApp, parentPackageName,
9206                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9207                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9208                // SIDE EFFECTS; updates system state; move elsewhere
9209                if (origPackage != null) {
9210                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9211                }
9212                mSettings.addUserToSettingLPw(pkgSetting);
9213            } else {
9214                // REMOVE SharedUserSetting from method; update in a separate call.
9215                //
9216                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9217                // secondaryCpuAbi are not known at this point so we always update them
9218                // to null here, only to reset them at a later point.
9219                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9220                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9221                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9222                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9223                        UserManagerService.getInstance(), usesStaticLibraries,
9224                        pkg.usesStaticLibrariesVersions);
9225            }
9226            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9227            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9228
9229            // SIDE EFFECTS; modifies system state; move elsewhere
9230            if (pkgSetting.origPackage != null) {
9231                // If we are first transitioning from an original package,
9232                // fix up the new package's name now.  We need to do this after
9233                // looking up the package under its new name, so getPackageLP
9234                // can take care of fiddling things correctly.
9235                pkg.setPackageName(origPackage.name);
9236
9237                // File a report about this.
9238                String msg = "New package " + pkgSetting.realName
9239                        + " renamed to replace old package " + pkgSetting.name;
9240                reportSettingsProblem(Log.WARN, msg);
9241
9242                // Make a note of it.
9243                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9244                    mTransferedPackages.add(origPackage.name);
9245                }
9246
9247                // No longer need to retain this.
9248                pkgSetting.origPackage = null;
9249            }
9250
9251            // SIDE EFFECTS; modifies system state; move elsewhere
9252            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9253                // Make a note of it.
9254                mTransferedPackages.add(pkg.packageName);
9255            }
9256
9257            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9258                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9259            }
9260
9261            if ((scanFlags & SCAN_BOOTING) == 0
9262                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9263                // Check all shared libraries and map to their actual file path.
9264                // We only do this here for apps not on a system dir, because those
9265                // are the only ones that can fail an install due to this.  We
9266                // will take care of the system apps by updating all of their
9267                // library paths after the scan is done. Also during the initial
9268                // scan don't update any libs as we do this wholesale after all
9269                // apps are scanned to avoid dependency based scanning.
9270                updateSharedLibrariesLPr(pkg, null);
9271            }
9272
9273            if (mFoundPolicyFile) {
9274                SELinuxMMAC.assignSeInfoValue(pkg);
9275            }
9276            pkg.applicationInfo.uid = pkgSetting.appId;
9277            pkg.mExtras = pkgSetting;
9278
9279
9280            // Static shared libs have same package with different versions where
9281            // we internally use a synthetic package name to allow multiple versions
9282            // of the same package, therefore we need to compare signatures against
9283            // the package setting for the latest library version.
9284            PackageSetting signatureCheckPs = pkgSetting;
9285            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9286                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9287                if (libraryEntry != null) {
9288                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9289                }
9290            }
9291
9292            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9293                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9294                    // We just determined the app is signed correctly, so bring
9295                    // over the latest parsed certs.
9296                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9297                } else {
9298                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9299                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9300                                "Package " + pkg.packageName + " upgrade keys do not match the "
9301                                + "previously installed version");
9302                    } else {
9303                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9304                        String msg = "System package " + pkg.packageName
9305                                + " signature changed; retaining data.";
9306                        reportSettingsProblem(Log.WARN, msg);
9307                    }
9308                }
9309            } else {
9310                try {
9311                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9312                    verifySignaturesLP(signatureCheckPs, pkg);
9313                    // We just determined the app is signed correctly, so bring
9314                    // over the latest parsed certs.
9315                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9316                } catch (PackageManagerException e) {
9317                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9318                        throw e;
9319                    }
9320                    // The signature has changed, but this package is in the system
9321                    // image...  let's recover!
9322                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9323                    // However...  if this package is part of a shared user, but it
9324                    // doesn't match the signature of the shared user, let's fail.
9325                    // What this means is that you can't change the signatures
9326                    // associated with an overall shared user, which doesn't seem all
9327                    // that unreasonable.
9328                    if (signatureCheckPs.sharedUser != null) {
9329                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9330                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9331                            throw new PackageManagerException(
9332                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9333                                    "Signature mismatch for shared user: "
9334                                            + pkgSetting.sharedUser);
9335                        }
9336                    }
9337                    // File a report about this.
9338                    String msg = "System package " + pkg.packageName
9339                            + " signature changed; retaining data.";
9340                    reportSettingsProblem(Log.WARN, msg);
9341                }
9342            }
9343
9344            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9345                // This package wants to adopt ownership of permissions from
9346                // another package.
9347                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9348                    final String origName = pkg.mAdoptPermissions.get(i);
9349                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9350                    if (orig != null) {
9351                        if (verifyPackageUpdateLPr(orig, pkg)) {
9352                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9353                                    + pkg.packageName);
9354                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9355                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9356                        }
9357                    }
9358                }
9359            }
9360        }
9361
9362        pkg.applicationInfo.processName = fixProcessName(
9363                pkg.applicationInfo.packageName,
9364                pkg.applicationInfo.processName);
9365
9366        if (pkg != mPlatformPackage) {
9367            // Get all of our default paths setup
9368            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9369        }
9370
9371        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9372
9373        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9374            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9375                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9376                derivePackageAbi(
9377                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9378                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9379
9380                // Some system apps still use directory structure for native libraries
9381                // in which case we might end up not detecting abi solely based on apk
9382                // structure. Try to detect abi based on directory structure.
9383                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9384                        pkg.applicationInfo.primaryCpuAbi == null) {
9385                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9386                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9387                }
9388            } else {
9389                // This is not a first boot or an upgrade, don't bother deriving the
9390                // ABI during the scan. Instead, trust the value that was stored in the
9391                // package setting.
9392                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9393                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9394
9395                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9396
9397                if (DEBUG_ABI_SELECTION) {
9398                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9399                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9400                        pkg.applicationInfo.secondaryCpuAbi);
9401                }
9402            }
9403        } else {
9404            if ((scanFlags & SCAN_MOVE) != 0) {
9405                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9406                // but we already have this packages package info in the PackageSetting. We just
9407                // use that and derive the native library path based on the new codepath.
9408                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9409                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9410            }
9411
9412            // Set native library paths again. For moves, the path will be updated based on the
9413            // ABIs we've determined above. For non-moves, the path will be updated based on the
9414            // ABIs we determined during compilation, but the path will depend on the final
9415            // package path (after the rename away from the stage path).
9416            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9417        }
9418
9419        // This is a special case for the "system" package, where the ABI is
9420        // dictated by the zygote configuration (and init.rc). We should keep track
9421        // of this ABI so that we can deal with "normal" applications that run under
9422        // the same UID correctly.
9423        if (mPlatformPackage == pkg) {
9424            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9425                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9426        }
9427
9428        // If there's a mismatch between the abi-override in the package setting
9429        // and the abiOverride specified for the install. Warn about this because we
9430        // would've already compiled the app without taking the package setting into
9431        // account.
9432        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9433            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9434                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9435                        " for package " + pkg.packageName);
9436            }
9437        }
9438
9439        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9440        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9441        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9442
9443        // Copy the derived override back to the parsed package, so that we can
9444        // update the package settings accordingly.
9445        pkg.cpuAbiOverride = cpuAbiOverride;
9446
9447        if (DEBUG_ABI_SELECTION) {
9448            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9449                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9450                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9451        }
9452
9453        // Push the derived path down into PackageSettings so we know what to
9454        // clean up at uninstall time.
9455        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9456
9457        if (DEBUG_ABI_SELECTION) {
9458            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9459                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9460                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9461        }
9462
9463        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9464        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9465            // We don't do this here during boot because we can do it all
9466            // at once after scanning all existing packages.
9467            //
9468            // We also do this *before* we perform dexopt on this package, so that
9469            // we can avoid redundant dexopts, and also to make sure we've got the
9470            // code and package path correct.
9471            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9472        }
9473
9474        if (mFactoryTest && pkg.requestedPermissions.contains(
9475                android.Manifest.permission.FACTORY_TEST)) {
9476            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9477        }
9478
9479        if (isSystemApp(pkg)) {
9480            pkgSetting.isOrphaned = true;
9481        }
9482
9483        // Take care of first install / last update times.
9484        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9485        if (currentTime != 0) {
9486            if (pkgSetting.firstInstallTime == 0) {
9487                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9488            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9489                pkgSetting.lastUpdateTime = currentTime;
9490            }
9491        } else if (pkgSetting.firstInstallTime == 0) {
9492            // We need *something*.  Take time time stamp of the file.
9493            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9494        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9495            if (scanFileTime != pkgSetting.timeStamp) {
9496                // A package on the system image has changed; consider this
9497                // to be an update.
9498                pkgSetting.lastUpdateTime = scanFileTime;
9499            }
9500        }
9501        pkgSetting.setTimeStamp(scanFileTime);
9502
9503        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9504            if (nonMutatedPs != null) {
9505                synchronized (mPackages) {
9506                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9507                }
9508            }
9509        } else {
9510            final int userId = user == null ? 0 : user.getIdentifier();
9511            // Modify state for the given package setting
9512            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9513                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9514            if (pkgSetting.getInstantApp(userId)) {
9515                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9516            }
9517        }
9518        return pkg;
9519    }
9520
9521    /**
9522     * Applies policy to the parsed package based upon the given policy flags.
9523     * Ensures the package is in a good state.
9524     * <p>
9525     * Implementation detail: This method must NOT have any side effect. It would
9526     * ideally be static, but, it requires locks to read system state.
9527     */
9528    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9529        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9530            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9531            if (pkg.applicationInfo.isDirectBootAware()) {
9532                // we're direct boot aware; set for all components
9533                for (PackageParser.Service s : pkg.services) {
9534                    s.info.encryptionAware = s.info.directBootAware = true;
9535                }
9536                for (PackageParser.Provider p : pkg.providers) {
9537                    p.info.encryptionAware = p.info.directBootAware = true;
9538                }
9539                for (PackageParser.Activity a : pkg.activities) {
9540                    a.info.encryptionAware = a.info.directBootAware = true;
9541                }
9542                for (PackageParser.Activity r : pkg.receivers) {
9543                    r.info.encryptionAware = r.info.directBootAware = true;
9544                }
9545            }
9546        } else {
9547            // Only allow system apps to be flagged as core apps.
9548            pkg.coreApp = false;
9549            // clear flags not applicable to regular apps
9550            pkg.applicationInfo.privateFlags &=
9551                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9552            pkg.applicationInfo.privateFlags &=
9553                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9554        }
9555        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9556
9557        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9558            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9559        }
9560
9561        if (!isSystemApp(pkg)) {
9562            // Only system apps can use these features.
9563            pkg.mOriginalPackages = null;
9564            pkg.mRealPackage = null;
9565            pkg.mAdoptPermissions = null;
9566        }
9567    }
9568
9569    /**
9570     * Asserts the parsed package is valid according to the given policy. If the
9571     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9572     * <p>
9573     * Implementation detail: This method must NOT have any side effects. It would
9574     * ideally be static, but, it requires locks to read system state.
9575     *
9576     * @throws PackageManagerException If the package fails any of the validation checks
9577     */
9578    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9579            throws PackageManagerException {
9580        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9581            assertCodePolicy(pkg);
9582        }
9583
9584        if (pkg.applicationInfo.getCodePath() == null ||
9585                pkg.applicationInfo.getResourcePath() == null) {
9586            // Bail out. The resource and code paths haven't been set.
9587            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9588                    "Code and resource paths haven't been set correctly");
9589        }
9590
9591        // Make sure we're not adding any bogus keyset info
9592        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9593        ksms.assertScannedPackageValid(pkg);
9594
9595        synchronized (mPackages) {
9596            // The special "android" package can only be defined once
9597            if (pkg.packageName.equals("android")) {
9598                if (mAndroidApplication != null) {
9599                    Slog.w(TAG, "*************************************************");
9600                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9601                    Slog.w(TAG, " codePath=" + pkg.codePath);
9602                    Slog.w(TAG, "*************************************************");
9603                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9604                            "Core android package being redefined.  Skipping.");
9605                }
9606            }
9607
9608            // A package name must be unique; don't allow duplicates
9609            if (mPackages.containsKey(pkg.packageName)) {
9610                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9611                        "Application package " + pkg.packageName
9612                        + " already installed.  Skipping duplicate.");
9613            }
9614
9615            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9616                // Static libs have a synthetic package name containing the version
9617                // but we still want the base name to be unique.
9618                if (mPackages.containsKey(pkg.manifestPackageName)) {
9619                    throw new PackageManagerException(
9620                            "Duplicate static shared lib provider package");
9621                }
9622
9623                // Static shared libraries should have at least O target SDK
9624                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9625                    throw new PackageManagerException(
9626                            "Packages declaring static-shared libs must target O SDK or higher");
9627                }
9628
9629                // Package declaring static a shared lib cannot be instant apps
9630                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9631                    throw new PackageManagerException(
9632                            "Packages declaring static-shared libs cannot be instant apps");
9633                }
9634
9635                // Package declaring static a shared lib cannot be renamed since the package
9636                // name is synthetic and apps can't code around package manager internals.
9637                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9638                    throw new PackageManagerException(
9639                            "Packages declaring static-shared libs cannot be renamed");
9640                }
9641
9642                // Package declaring static a shared lib cannot declare child packages
9643                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9644                    throw new PackageManagerException(
9645                            "Packages declaring static-shared libs cannot have child packages");
9646                }
9647
9648                // Package declaring static a shared lib cannot declare dynamic libs
9649                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9650                    throw new PackageManagerException(
9651                            "Packages declaring static-shared libs cannot declare dynamic libs");
9652                }
9653
9654                // Package declaring static a shared lib cannot declare shared users
9655                if (pkg.mSharedUserId != null) {
9656                    throw new PackageManagerException(
9657                            "Packages declaring static-shared libs cannot declare shared users");
9658                }
9659
9660                // Static shared libs cannot declare activities
9661                if (!pkg.activities.isEmpty()) {
9662                    throw new PackageManagerException(
9663                            "Static shared libs cannot declare activities");
9664                }
9665
9666                // Static shared libs cannot declare services
9667                if (!pkg.services.isEmpty()) {
9668                    throw new PackageManagerException(
9669                            "Static shared libs cannot declare services");
9670                }
9671
9672                // Static shared libs cannot declare providers
9673                if (!pkg.providers.isEmpty()) {
9674                    throw new PackageManagerException(
9675                            "Static shared libs cannot declare content providers");
9676                }
9677
9678                // Static shared libs cannot declare receivers
9679                if (!pkg.receivers.isEmpty()) {
9680                    throw new PackageManagerException(
9681                            "Static shared libs cannot declare broadcast receivers");
9682                }
9683
9684                // Static shared libs cannot declare permission groups
9685                if (!pkg.permissionGroups.isEmpty()) {
9686                    throw new PackageManagerException(
9687                            "Static shared libs cannot declare permission groups");
9688                }
9689
9690                // Static shared libs cannot declare permissions
9691                if (!pkg.permissions.isEmpty()) {
9692                    throw new PackageManagerException(
9693                            "Static shared libs cannot declare permissions");
9694                }
9695
9696                // Static shared libs cannot declare protected broadcasts
9697                if (pkg.protectedBroadcasts != null) {
9698                    throw new PackageManagerException(
9699                            "Static shared libs cannot declare protected broadcasts");
9700                }
9701
9702                // Static shared libs cannot be overlay targets
9703                if (pkg.mOverlayTarget != null) {
9704                    throw new PackageManagerException(
9705                            "Static shared libs cannot be overlay targets");
9706                }
9707
9708                // The version codes must be ordered as lib versions
9709                int minVersionCode = Integer.MIN_VALUE;
9710                int maxVersionCode = Integer.MAX_VALUE;
9711
9712                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9713                        pkg.staticSharedLibName);
9714                if (versionedLib != null) {
9715                    final int versionCount = versionedLib.size();
9716                    for (int i = 0; i < versionCount; i++) {
9717                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9718                        // TODO: We will change version code to long, so in the new API it is long
9719                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9720                                .getVersionCode();
9721                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9722                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9723                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9724                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9725                        } else {
9726                            minVersionCode = maxVersionCode = libVersionCode;
9727                            break;
9728                        }
9729                    }
9730                }
9731                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9732                    throw new PackageManagerException("Static shared"
9733                            + " lib version codes must be ordered as lib versions");
9734                }
9735            }
9736
9737            // Only privileged apps and updated privileged apps can add child packages.
9738            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9739                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9740                    throw new PackageManagerException("Only privileged apps can add child "
9741                            + "packages. Ignoring package " + pkg.packageName);
9742                }
9743                final int childCount = pkg.childPackages.size();
9744                for (int i = 0; i < childCount; i++) {
9745                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9746                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9747                            childPkg.packageName)) {
9748                        throw new PackageManagerException("Can't override child of "
9749                                + "another disabled app. Ignoring package " + pkg.packageName);
9750                    }
9751                }
9752            }
9753
9754            // If we're only installing presumed-existing packages, require that the
9755            // scanned APK is both already known and at the path previously established
9756            // for it.  Previously unknown packages we pick up normally, but if we have an
9757            // a priori expectation about this package's install presence, enforce it.
9758            // With a singular exception for new system packages. When an OTA contains
9759            // a new system package, we allow the codepath to change from a system location
9760            // to the user-installed location. If we don't allow this change, any newer,
9761            // user-installed version of the application will be ignored.
9762            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9763                if (mExpectingBetter.containsKey(pkg.packageName)) {
9764                    logCriticalInfo(Log.WARN,
9765                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9766                } else {
9767                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9768                    if (known != null) {
9769                        if (DEBUG_PACKAGE_SCANNING) {
9770                            Log.d(TAG, "Examining " + pkg.codePath
9771                                    + " and requiring known paths " + known.codePathString
9772                                    + " & " + known.resourcePathString);
9773                        }
9774                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9775                                || !pkg.applicationInfo.getResourcePath().equals(
9776                                        known.resourcePathString)) {
9777                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9778                                    "Application package " + pkg.packageName
9779                                    + " found at " + pkg.applicationInfo.getCodePath()
9780                                    + " but expected at " + known.codePathString
9781                                    + "; ignoring.");
9782                        }
9783                    }
9784                }
9785            }
9786
9787            // Verify that this new package doesn't have any content providers
9788            // that conflict with existing packages.  Only do this if the
9789            // package isn't already installed, since we don't want to break
9790            // things that are installed.
9791            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9792                final int N = pkg.providers.size();
9793                int i;
9794                for (i=0; i<N; i++) {
9795                    PackageParser.Provider p = pkg.providers.get(i);
9796                    if (p.info.authority != null) {
9797                        String names[] = p.info.authority.split(";");
9798                        for (int j = 0; j < names.length; j++) {
9799                            if (mProvidersByAuthority.containsKey(names[j])) {
9800                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9801                                final String otherPackageName =
9802                                        ((other != null && other.getComponentName() != null) ?
9803                                                other.getComponentName().getPackageName() : "?");
9804                                throw new PackageManagerException(
9805                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9806                                        "Can't install because provider name " + names[j]
9807                                                + " (in package " + pkg.applicationInfo.packageName
9808                                                + ") is already used by " + otherPackageName);
9809                            }
9810                        }
9811                    }
9812                }
9813            }
9814        }
9815    }
9816
9817    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9818            int type, String declaringPackageName, int declaringVersionCode) {
9819        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9820        if (versionedLib == null) {
9821            versionedLib = new SparseArray<>();
9822            mSharedLibraries.put(name, versionedLib);
9823            if (type == SharedLibraryInfo.TYPE_STATIC) {
9824                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9825            }
9826        } else if (versionedLib.indexOfKey(version) >= 0) {
9827            return false;
9828        }
9829        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9830                version, type, declaringPackageName, declaringVersionCode);
9831        versionedLib.put(version, libEntry);
9832        return true;
9833    }
9834
9835    private boolean removeSharedLibraryLPw(String name, int version) {
9836        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9837        if (versionedLib == null) {
9838            return false;
9839        }
9840        final int libIdx = versionedLib.indexOfKey(version);
9841        if (libIdx < 0) {
9842            return false;
9843        }
9844        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9845        versionedLib.remove(version);
9846        if (versionedLib.size() <= 0) {
9847            mSharedLibraries.remove(name);
9848            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9849                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9850                        .getPackageName());
9851            }
9852        }
9853        return true;
9854    }
9855
9856    /**
9857     * Adds a scanned package to the system. When this method is finished, the package will
9858     * be available for query, resolution, etc...
9859     */
9860    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9861            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9862        final String pkgName = pkg.packageName;
9863        if (mCustomResolverComponentName != null &&
9864                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9865            setUpCustomResolverActivity(pkg);
9866        }
9867
9868        if (pkg.packageName.equals("android")) {
9869            synchronized (mPackages) {
9870                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9871                    // Set up information for our fall-back user intent resolution activity.
9872                    mPlatformPackage = pkg;
9873                    pkg.mVersionCode = mSdkVersion;
9874                    mAndroidApplication = pkg.applicationInfo;
9875                    if (!mResolverReplaced) {
9876                        mResolveActivity.applicationInfo = mAndroidApplication;
9877                        mResolveActivity.name = ResolverActivity.class.getName();
9878                        mResolveActivity.packageName = mAndroidApplication.packageName;
9879                        mResolveActivity.processName = "system:ui";
9880                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9881                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9882                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9883                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9884                        mResolveActivity.exported = true;
9885                        mResolveActivity.enabled = true;
9886                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9887                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9888                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9889                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9890                                | ActivityInfo.CONFIG_ORIENTATION
9891                                | ActivityInfo.CONFIG_KEYBOARD
9892                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9893                        mResolveInfo.activityInfo = mResolveActivity;
9894                        mResolveInfo.priority = 0;
9895                        mResolveInfo.preferredOrder = 0;
9896                        mResolveInfo.match = 0;
9897                        mResolveComponentName = new ComponentName(
9898                                mAndroidApplication.packageName, mResolveActivity.name);
9899                    }
9900                }
9901            }
9902        }
9903
9904        ArrayList<PackageParser.Package> clientLibPkgs = null;
9905        // writer
9906        synchronized (mPackages) {
9907            boolean hasStaticSharedLibs = false;
9908
9909            // Any app can add new static shared libraries
9910            if (pkg.staticSharedLibName != null) {
9911                // Static shared libs don't allow renaming as they have synthetic package
9912                // names to allow install of multiple versions, so use name from manifest.
9913                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9914                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9915                        pkg.manifestPackageName, pkg.mVersionCode)) {
9916                    hasStaticSharedLibs = true;
9917                } else {
9918                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9919                                + pkg.staticSharedLibName + " already exists; skipping");
9920                }
9921                // Static shared libs cannot be updated once installed since they
9922                // use synthetic package name which includes the version code, so
9923                // not need to update other packages's shared lib dependencies.
9924            }
9925
9926            if (!hasStaticSharedLibs
9927                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9928                // Only system apps can add new dynamic shared libraries.
9929                if (pkg.libraryNames != null) {
9930                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9931                        String name = pkg.libraryNames.get(i);
9932                        boolean allowed = false;
9933                        if (pkg.isUpdatedSystemApp()) {
9934                            // New library entries can only be added through the
9935                            // system image.  This is important to get rid of a lot
9936                            // of nasty edge cases: for example if we allowed a non-
9937                            // system update of the app to add a library, then uninstalling
9938                            // the update would make the library go away, and assumptions
9939                            // we made such as through app install filtering would now
9940                            // have allowed apps on the device which aren't compatible
9941                            // with it.  Better to just have the restriction here, be
9942                            // conservative, and create many fewer cases that can negatively
9943                            // impact the user experience.
9944                            final PackageSetting sysPs = mSettings
9945                                    .getDisabledSystemPkgLPr(pkg.packageName);
9946                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9947                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9948                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9949                                        allowed = true;
9950                                        break;
9951                                    }
9952                                }
9953                            }
9954                        } else {
9955                            allowed = true;
9956                        }
9957                        if (allowed) {
9958                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9959                                    SharedLibraryInfo.VERSION_UNDEFINED,
9960                                    SharedLibraryInfo.TYPE_DYNAMIC,
9961                                    pkg.packageName, pkg.mVersionCode)) {
9962                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9963                                        + name + " already exists; skipping");
9964                            }
9965                        } else {
9966                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9967                                    + name + " that is not declared on system image; skipping");
9968                        }
9969                    }
9970
9971                    if ((scanFlags & SCAN_BOOTING) == 0) {
9972                        // If we are not booting, we need to update any applications
9973                        // that are clients of our shared library.  If we are booting,
9974                        // this will all be done once the scan is complete.
9975                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9976                    }
9977                }
9978            }
9979        }
9980
9981        if ((scanFlags & SCAN_BOOTING) != 0) {
9982            // No apps can run during boot scan, so they don't need to be frozen
9983        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9984            // Caller asked to not kill app, so it's probably not frozen
9985        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9986            // Caller asked us to ignore frozen check for some reason; they
9987            // probably didn't know the package name
9988        } else {
9989            // We're doing major surgery on this package, so it better be frozen
9990            // right now to keep it from launching
9991            checkPackageFrozen(pkgName);
9992        }
9993
9994        // Also need to kill any apps that are dependent on the library.
9995        if (clientLibPkgs != null) {
9996            for (int i=0; i<clientLibPkgs.size(); i++) {
9997                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9998                killApplication(clientPkg.applicationInfo.packageName,
9999                        clientPkg.applicationInfo.uid, "update lib");
10000            }
10001        }
10002
10003        // writer
10004        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10005
10006        synchronized (mPackages) {
10007            // We don't expect installation to fail beyond this point
10008
10009            // Add the new setting to mSettings
10010            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10011            // Add the new setting to mPackages
10012            mPackages.put(pkg.applicationInfo.packageName, pkg);
10013            // Make sure we don't accidentally delete its data.
10014            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10015            while (iter.hasNext()) {
10016                PackageCleanItem item = iter.next();
10017                if (pkgName.equals(item.packageName)) {
10018                    iter.remove();
10019                }
10020            }
10021
10022            // Add the package's KeySets to the global KeySetManagerService
10023            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10024            ksms.addScannedPackageLPw(pkg);
10025
10026            int N = pkg.providers.size();
10027            StringBuilder r = null;
10028            int i;
10029            for (i=0; i<N; i++) {
10030                PackageParser.Provider p = pkg.providers.get(i);
10031                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10032                        p.info.processName);
10033                mProviders.addProvider(p);
10034                p.syncable = p.info.isSyncable;
10035                if (p.info.authority != null) {
10036                    String names[] = p.info.authority.split(";");
10037                    p.info.authority = null;
10038                    for (int j = 0; j < names.length; j++) {
10039                        if (j == 1 && p.syncable) {
10040                            // We only want the first authority for a provider to possibly be
10041                            // syncable, so if we already added this provider using a different
10042                            // authority clear the syncable flag. We copy the provider before
10043                            // changing it because the mProviders object contains a reference
10044                            // to a provider that we don't want to change.
10045                            // Only do this for the second authority since the resulting provider
10046                            // object can be the same for all future authorities for this provider.
10047                            p = new PackageParser.Provider(p);
10048                            p.syncable = false;
10049                        }
10050                        if (!mProvidersByAuthority.containsKey(names[j])) {
10051                            mProvidersByAuthority.put(names[j], p);
10052                            if (p.info.authority == null) {
10053                                p.info.authority = names[j];
10054                            } else {
10055                                p.info.authority = p.info.authority + ";" + names[j];
10056                            }
10057                            if (DEBUG_PACKAGE_SCANNING) {
10058                                if (chatty)
10059                                    Log.d(TAG, "Registered content provider: " + names[j]
10060                                            + ", className = " + p.info.name + ", isSyncable = "
10061                                            + p.info.isSyncable);
10062                            }
10063                        } else {
10064                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10065                            Slog.w(TAG, "Skipping provider name " + names[j] +
10066                                    " (in package " + pkg.applicationInfo.packageName +
10067                                    "): name already used by "
10068                                    + ((other != null && other.getComponentName() != null)
10069                                            ? other.getComponentName().getPackageName() : "?"));
10070                        }
10071                    }
10072                }
10073                if (chatty) {
10074                    if (r == null) {
10075                        r = new StringBuilder(256);
10076                    } else {
10077                        r.append(' ');
10078                    }
10079                    r.append(p.info.name);
10080                }
10081            }
10082            if (r != null) {
10083                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10084            }
10085
10086            N = pkg.services.size();
10087            r = null;
10088            for (i=0; i<N; i++) {
10089                PackageParser.Service s = pkg.services.get(i);
10090                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10091                        s.info.processName);
10092                mServices.addService(s);
10093                if (chatty) {
10094                    if (r == null) {
10095                        r = new StringBuilder(256);
10096                    } else {
10097                        r.append(' ');
10098                    }
10099                    r.append(s.info.name);
10100                }
10101            }
10102            if (r != null) {
10103                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10104            }
10105
10106            N = pkg.receivers.size();
10107            r = null;
10108            for (i=0; i<N; i++) {
10109                PackageParser.Activity a = pkg.receivers.get(i);
10110                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10111                        a.info.processName);
10112                mReceivers.addActivity(a, "receiver");
10113                if (chatty) {
10114                    if (r == null) {
10115                        r = new StringBuilder(256);
10116                    } else {
10117                        r.append(' ');
10118                    }
10119                    r.append(a.info.name);
10120                }
10121            }
10122            if (r != null) {
10123                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10124            }
10125
10126            N = pkg.activities.size();
10127            r = null;
10128            for (i=0; i<N; i++) {
10129                PackageParser.Activity a = pkg.activities.get(i);
10130                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10131                        a.info.processName);
10132                mActivities.addActivity(a, "activity");
10133                if (chatty) {
10134                    if (r == null) {
10135                        r = new StringBuilder(256);
10136                    } else {
10137                        r.append(' ');
10138                    }
10139                    r.append(a.info.name);
10140                }
10141            }
10142            if (r != null) {
10143                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10144            }
10145
10146            N = pkg.permissionGroups.size();
10147            r = null;
10148            for (i=0; i<N; i++) {
10149                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10150                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10151                final String curPackageName = cur == null ? null : cur.info.packageName;
10152                // Dont allow ephemeral apps to define new permission groups.
10153                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10154                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10155                            + pg.info.packageName
10156                            + " ignored: instant apps cannot define new permission groups.");
10157                    continue;
10158                }
10159                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10160                if (cur == null || isPackageUpdate) {
10161                    mPermissionGroups.put(pg.info.name, pg);
10162                    if (chatty) {
10163                        if (r == null) {
10164                            r = new StringBuilder(256);
10165                        } else {
10166                            r.append(' ');
10167                        }
10168                        if (isPackageUpdate) {
10169                            r.append("UPD:");
10170                        }
10171                        r.append(pg.info.name);
10172                    }
10173                } else {
10174                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10175                            + pg.info.packageName + " ignored: original from "
10176                            + cur.info.packageName);
10177                    if (chatty) {
10178                        if (r == null) {
10179                            r = new StringBuilder(256);
10180                        } else {
10181                            r.append(' ');
10182                        }
10183                        r.append("DUP:");
10184                        r.append(pg.info.name);
10185                    }
10186                }
10187            }
10188            if (r != null) {
10189                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10190            }
10191
10192            N = pkg.permissions.size();
10193            r = null;
10194            for (i=0; i<N; i++) {
10195                PackageParser.Permission p = pkg.permissions.get(i);
10196
10197                // Dont allow ephemeral apps to define new permissions.
10198                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10199                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10200                            + p.info.packageName
10201                            + " ignored: instant apps cannot define new permissions.");
10202                    continue;
10203                }
10204
10205                // Assume by default that we did not install this permission into the system.
10206                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10207
10208                // Now that permission groups have a special meaning, we ignore permission
10209                // groups for legacy apps to prevent unexpected behavior. In particular,
10210                // permissions for one app being granted to someone just becase they happen
10211                // to be in a group defined by another app (before this had no implications).
10212                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10213                    p.group = mPermissionGroups.get(p.info.group);
10214                    // Warn for a permission in an unknown group.
10215                    if (p.info.group != null && p.group == null) {
10216                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10217                                + p.info.packageName + " in an unknown group " + p.info.group);
10218                    }
10219                }
10220
10221                ArrayMap<String, BasePermission> permissionMap =
10222                        p.tree ? mSettings.mPermissionTrees
10223                                : mSettings.mPermissions;
10224                BasePermission bp = permissionMap.get(p.info.name);
10225
10226                // Allow system apps to redefine non-system permissions
10227                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10228                    final boolean currentOwnerIsSystem = (bp.perm != null
10229                            && isSystemApp(bp.perm.owner));
10230                    if (isSystemApp(p.owner)) {
10231                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10232                            // It's a built-in permission and no owner, take ownership now
10233                            bp.packageSetting = pkgSetting;
10234                            bp.perm = p;
10235                            bp.uid = pkg.applicationInfo.uid;
10236                            bp.sourcePackage = p.info.packageName;
10237                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10238                        } else if (!currentOwnerIsSystem) {
10239                            String msg = "New decl " + p.owner + " of permission  "
10240                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10241                            reportSettingsProblem(Log.WARN, msg);
10242                            bp = null;
10243                        }
10244                    }
10245                }
10246
10247                if (bp == null) {
10248                    bp = new BasePermission(p.info.name, p.info.packageName,
10249                            BasePermission.TYPE_NORMAL);
10250                    permissionMap.put(p.info.name, bp);
10251                }
10252
10253                if (bp.perm == null) {
10254                    if (bp.sourcePackage == null
10255                            || bp.sourcePackage.equals(p.info.packageName)) {
10256                        BasePermission tree = findPermissionTreeLP(p.info.name);
10257                        if (tree == null
10258                                || tree.sourcePackage.equals(p.info.packageName)) {
10259                            bp.packageSetting = pkgSetting;
10260                            bp.perm = p;
10261                            bp.uid = pkg.applicationInfo.uid;
10262                            bp.sourcePackage = p.info.packageName;
10263                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10264                            if (chatty) {
10265                                if (r == null) {
10266                                    r = new StringBuilder(256);
10267                                } else {
10268                                    r.append(' ');
10269                                }
10270                                r.append(p.info.name);
10271                            }
10272                        } else {
10273                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10274                                    + p.info.packageName + " ignored: base tree "
10275                                    + tree.name + " is from package "
10276                                    + tree.sourcePackage);
10277                        }
10278                    } else {
10279                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10280                                + p.info.packageName + " ignored: original from "
10281                                + bp.sourcePackage);
10282                    }
10283                } else if (chatty) {
10284                    if (r == null) {
10285                        r = new StringBuilder(256);
10286                    } else {
10287                        r.append(' ');
10288                    }
10289                    r.append("DUP:");
10290                    r.append(p.info.name);
10291                }
10292                if (bp.perm == p) {
10293                    bp.protectionLevel = p.info.protectionLevel;
10294                }
10295            }
10296
10297            if (r != null) {
10298                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10299            }
10300
10301            N = pkg.instrumentation.size();
10302            r = null;
10303            for (i=0; i<N; i++) {
10304                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10305                a.info.packageName = pkg.applicationInfo.packageName;
10306                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10307                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10308                a.info.splitNames = pkg.splitNames;
10309                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10310                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10311                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10312                a.info.dataDir = pkg.applicationInfo.dataDir;
10313                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10314                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10315                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10316                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10317                mInstrumentation.put(a.getComponentName(), a);
10318                if (chatty) {
10319                    if (r == null) {
10320                        r = new StringBuilder(256);
10321                    } else {
10322                        r.append(' ');
10323                    }
10324                    r.append(a.info.name);
10325                }
10326            }
10327            if (r != null) {
10328                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10329            }
10330
10331            if (pkg.protectedBroadcasts != null) {
10332                N = pkg.protectedBroadcasts.size();
10333                for (i=0; i<N; i++) {
10334                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10335                }
10336            }
10337        }
10338
10339        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10340    }
10341
10342    /**
10343     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10344     * is derived purely on the basis of the contents of {@code scanFile} and
10345     * {@code cpuAbiOverride}.
10346     *
10347     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10348     */
10349    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10350                                 String cpuAbiOverride, boolean extractLibs,
10351                                 File appLib32InstallDir)
10352            throws PackageManagerException {
10353        // Give ourselves some initial paths; we'll come back for another
10354        // pass once we've determined ABI below.
10355        setNativeLibraryPaths(pkg, appLib32InstallDir);
10356
10357        // We would never need to extract libs for forward-locked and external packages,
10358        // since the container service will do it for us. We shouldn't attempt to
10359        // extract libs from system app when it was not updated.
10360        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10361                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10362            extractLibs = false;
10363        }
10364
10365        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10366        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10367
10368        NativeLibraryHelper.Handle handle = null;
10369        try {
10370            handle = NativeLibraryHelper.Handle.create(pkg);
10371            // TODO(multiArch): This can be null for apps that didn't go through the
10372            // usual installation process. We can calculate it again, like we
10373            // do during install time.
10374            //
10375            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10376            // unnecessary.
10377            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10378
10379            // Null out the abis so that they can be recalculated.
10380            pkg.applicationInfo.primaryCpuAbi = null;
10381            pkg.applicationInfo.secondaryCpuAbi = null;
10382            if (isMultiArch(pkg.applicationInfo)) {
10383                // Warn if we've set an abiOverride for multi-lib packages..
10384                // By definition, we need to copy both 32 and 64 bit libraries for
10385                // such packages.
10386                if (pkg.cpuAbiOverride != null
10387                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10388                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10389                }
10390
10391                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10392                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10393                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10394                    if (extractLibs) {
10395                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10396                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10397                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10398                                useIsaSpecificSubdirs);
10399                    } else {
10400                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10401                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10402                    }
10403                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10404                }
10405
10406                maybeThrowExceptionForMultiArchCopy(
10407                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10408
10409                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10410                    if (extractLibs) {
10411                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10412                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10413                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10414                                useIsaSpecificSubdirs);
10415                    } else {
10416                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10417                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10418                    }
10419                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10420                }
10421
10422                maybeThrowExceptionForMultiArchCopy(
10423                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10424
10425                if (abi64 >= 0) {
10426                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10427                }
10428
10429                if (abi32 >= 0) {
10430                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10431                    if (abi64 >= 0) {
10432                        if (pkg.use32bitAbi) {
10433                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10434                            pkg.applicationInfo.primaryCpuAbi = abi;
10435                        } else {
10436                            pkg.applicationInfo.secondaryCpuAbi = abi;
10437                        }
10438                    } else {
10439                        pkg.applicationInfo.primaryCpuAbi = abi;
10440                    }
10441                }
10442
10443            } else {
10444                String[] abiList = (cpuAbiOverride != null) ?
10445                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10446
10447                // Enable gross and lame hacks for apps that are built with old
10448                // SDK tools. We must scan their APKs for renderscript bitcode and
10449                // not launch them if it's present. Don't bother checking on devices
10450                // that don't have 64 bit support.
10451                boolean needsRenderScriptOverride = false;
10452                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10453                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10454                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10455                    needsRenderScriptOverride = true;
10456                }
10457
10458                final int copyRet;
10459                if (extractLibs) {
10460                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10461                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10462                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10463                } else {
10464                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10465                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10466                }
10467                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10468
10469                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10470                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10471                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10472                }
10473
10474                if (copyRet >= 0) {
10475                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10476                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10477                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10478                } else if (needsRenderScriptOverride) {
10479                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10480                }
10481            }
10482        } catch (IOException ioe) {
10483            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10484        } finally {
10485            IoUtils.closeQuietly(handle);
10486        }
10487
10488        // Now that we've calculated the ABIs and determined if it's an internal app,
10489        // we will go ahead and populate the nativeLibraryPath.
10490        setNativeLibraryPaths(pkg, appLib32InstallDir);
10491    }
10492
10493    /**
10494     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10495     * i.e, so that all packages can be run inside a single process if required.
10496     *
10497     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10498     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10499     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10500     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10501     * updating a package that belongs to a shared user.
10502     *
10503     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10504     * adds unnecessary complexity.
10505     */
10506    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10507            PackageParser.Package scannedPackage) {
10508        String requiredInstructionSet = null;
10509        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10510            requiredInstructionSet = VMRuntime.getInstructionSet(
10511                     scannedPackage.applicationInfo.primaryCpuAbi);
10512        }
10513
10514        PackageSetting requirer = null;
10515        for (PackageSetting ps : packagesForUser) {
10516            // If packagesForUser contains scannedPackage, we skip it. This will happen
10517            // when scannedPackage is an update of an existing package. Without this check,
10518            // we will never be able to change the ABI of any package belonging to a shared
10519            // user, even if it's compatible with other packages.
10520            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10521                if (ps.primaryCpuAbiString == null) {
10522                    continue;
10523                }
10524
10525                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10526                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10527                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10528                    // this but there's not much we can do.
10529                    String errorMessage = "Instruction set mismatch, "
10530                            + ((requirer == null) ? "[caller]" : requirer)
10531                            + " requires " + requiredInstructionSet + " whereas " + ps
10532                            + " requires " + instructionSet;
10533                    Slog.w(TAG, errorMessage);
10534                }
10535
10536                if (requiredInstructionSet == null) {
10537                    requiredInstructionSet = instructionSet;
10538                    requirer = ps;
10539                }
10540            }
10541        }
10542
10543        if (requiredInstructionSet != null) {
10544            String adjustedAbi;
10545            if (requirer != null) {
10546                // requirer != null implies that either scannedPackage was null or that scannedPackage
10547                // did not require an ABI, in which case we have to adjust scannedPackage to match
10548                // the ABI of the set (which is the same as requirer's ABI)
10549                adjustedAbi = requirer.primaryCpuAbiString;
10550                if (scannedPackage != null) {
10551                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10552                }
10553            } else {
10554                // requirer == null implies that we're updating all ABIs in the set to
10555                // match scannedPackage.
10556                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10557            }
10558
10559            for (PackageSetting ps : packagesForUser) {
10560                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10561                    if (ps.primaryCpuAbiString != null) {
10562                        continue;
10563                    }
10564
10565                    ps.primaryCpuAbiString = adjustedAbi;
10566                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10567                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10568                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10569                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10570                                + " (requirer="
10571                                + (requirer == null ? "null" : requirer.pkg.packageName)
10572                                + ", scannedPackage="
10573                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10574                                + ")");
10575                        try {
10576                            mInstaller.rmdex(ps.codePathString,
10577                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10578                        } catch (InstallerException ignored) {
10579                        }
10580                    }
10581                }
10582            }
10583        }
10584    }
10585
10586    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10587        synchronized (mPackages) {
10588            mResolverReplaced = true;
10589            // Set up information for custom user intent resolution activity.
10590            mResolveActivity.applicationInfo = pkg.applicationInfo;
10591            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10592            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10593            mResolveActivity.processName = pkg.applicationInfo.packageName;
10594            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10595            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10596                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10597            mResolveActivity.theme = 0;
10598            mResolveActivity.exported = true;
10599            mResolveActivity.enabled = true;
10600            mResolveInfo.activityInfo = mResolveActivity;
10601            mResolveInfo.priority = 0;
10602            mResolveInfo.preferredOrder = 0;
10603            mResolveInfo.match = 0;
10604            mResolveComponentName = mCustomResolverComponentName;
10605            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10606                    mResolveComponentName);
10607        }
10608    }
10609
10610    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10611        if (installerComponent == null) {
10612            if (DEBUG_EPHEMERAL) {
10613                Slog.d(TAG, "Clear ephemeral installer activity");
10614            }
10615            mInstantAppInstallerActivity.applicationInfo = null;
10616            return;
10617        }
10618
10619        if (DEBUG_EPHEMERAL) {
10620            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10621        }
10622        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10623        // Set up information for ephemeral installer activity
10624        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10625        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10626        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10627        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10628        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10629        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10630                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10631        mInstantAppInstallerActivity.theme = 0;
10632        mInstantAppInstallerActivity.exported = true;
10633        mInstantAppInstallerActivity.enabled = true;
10634        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10635        mInstantAppInstallerInfo.priority = 0;
10636        mInstantAppInstallerInfo.preferredOrder = 1;
10637        mInstantAppInstallerInfo.isDefault = true;
10638        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10639                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10640    }
10641
10642    private static String calculateBundledApkRoot(final String codePathString) {
10643        final File codePath = new File(codePathString);
10644        final File codeRoot;
10645        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10646            codeRoot = Environment.getRootDirectory();
10647        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10648            codeRoot = Environment.getOemDirectory();
10649        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10650            codeRoot = Environment.getVendorDirectory();
10651        } else {
10652            // Unrecognized code path; take its top real segment as the apk root:
10653            // e.g. /something/app/blah.apk => /something
10654            try {
10655                File f = codePath.getCanonicalFile();
10656                File parent = f.getParentFile();    // non-null because codePath is a file
10657                File tmp;
10658                while ((tmp = parent.getParentFile()) != null) {
10659                    f = parent;
10660                    parent = tmp;
10661                }
10662                codeRoot = f;
10663                Slog.w(TAG, "Unrecognized code path "
10664                        + codePath + " - using " + codeRoot);
10665            } catch (IOException e) {
10666                // Can't canonicalize the code path -- shenanigans?
10667                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10668                return Environment.getRootDirectory().getPath();
10669            }
10670        }
10671        return codeRoot.getPath();
10672    }
10673
10674    /**
10675     * Derive and set the location of native libraries for the given package,
10676     * which varies depending on where and how the package was installed.
10677     */
10678    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10679        final ApplicationInfo info = pkg.applicationInfo;
10680        final String codePath = pkg.codePath;
10681        final File codeFile = new File(codePath);
10682        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10683        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10684
10685        info.nativeLibraryRootDir = null;
10686        info.nativeLibraryRootRequiresIsa = false;
10687        info.nativeLibraryDir = null;
10688        info.secondaryNativeLibraryDir = null;
10689
10690        if (isApkFile(codeFile)) {
10691            // Monolithic install
10692            if (bundledApp) {
10693                // If "/system/lib64/apkname" exists, assume that is the per-package
10694                // native library directory to use; otherwise use "/system/lib/apkname".
10695                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10696                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10697                        getPrimaryInstructionSet(info));
10698
10699                // This is a bundled system app so choose the path based on the ABI.
10700                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10701                // is just the default path.
10702                final String apkName = deriveCodePathName(codePath);
10703                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10704                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10705                        apkName).getAbsolutePath();
10706
10707                if (info.secondaryCpuAbi != null) {
10708                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10709                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10710                            secondaryLibDir, apkName).getAbsolutePath();
10711                }
10712            } else if (asecApp) {
10713                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10714                        .getAbsolutePath();
10715            } else {
10716                final String apkName = deriveCodePathName(codePath);
10717                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10718                        .getAbsolutePath();
10719            }
10720
10721            info.nativeLibraryRootRequiresIsa = false;
10722            info.nativeLibraryDir = info.nativeLibraryRootDir;
10723        } else {
10724            // Cluster install
10725            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10726            info.nativeLibraryRootRequiresIsa = true;
10727
10728            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10729                    getPrimaryInstructionSet(info)).getAbsolutePath();
10730
10731            if (info.secondaryCpuAbi != null) {
10732                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10733                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10734            }
10735        }
10736    }
10737
10738    /**
10739     * Calculate the abis and roots for a bundled app. These can uniquely
10740     * be determined from the contents of the system partition, i.e whether
10741     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10742     * of this information, and instead assume that the system was built
10743     * sensibly.
10744     */
10745    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10746                                           PackageSetting pkgSetting) {
10747        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10748
10749        // If "/system/lib64/apkname" exists, assume that is the per-package
10750        // native library directory to use; otherwise use "/system/lib/apkname".
10751        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10752        setBundledAppAbi(pkg, apkRoot, apkName);
10753        // pkgSetting might be null during rescan following uninstall of updates
10754        // to a bundled app, so accommodate that possibility.  The settings in
10755        // that case will be established later from the parsed package.
10756        //
10757        // If the settings aren't null, sync them up with what we've just derived.
10758        // note that apkRoot isn't stored in the package settings.
10759        if (pkgSetting != null) {
10760            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10761            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10762        }
10763    }
10764
10765    /**
10766     * Deduces the ABI of a bundled app and sets the relevant fields on the
10767     * parsed pkg object.
10768     *
10769     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10770     *        under which system libraries are installed.
10771     * @param apkName the name of the installed package.
10772     */
10773    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10774        final File codeFile = new File(pkg.codePath);
10775
10776        final boolean has64BitLibs;
10777        final boolean has32BitLibs;
10778        if (isApkFile(codeFile)) {
10779            // Monolithic install
10780            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10781            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10782        } else {
10783            // Cluster install
10784            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10785            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10786                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10787                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10788                has64BitLibs = (new File(rootDir, isa)).exists();
10789            } else {
10790                has64BitLibs = false;
10791            }
10792            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10793                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10794                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10795                has32BitLibs = (new File(rootDir, isa)).exists();
10796            } else {
10797                has32BitLibs = false;
10798            }
10799        }
10800
10801        if (has64BitLibs && !has32BitLibs) {
10802            // The package has 64 bit libs, but not 32 bit libs. Its primary
10803            // ABI should be 64 bit. We can safely assume here that the bundled
10804            // native libraries correspond to the most preferred ABI in the list.
10805
10806            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10807            pkg.applicationInfo.secondaryCpuAbi = null;
10808        } else if (has32BitLibs && !has64BitLibs) {
10809            // The package has 32 bit libs but not 64 bit libs. Its primary
10810            // ABI should be 32 bit.
10811
10812            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10813            pkg.applicationInfo.secondaryCpuAbi = null;
10814        } else if (has32BitLibs && has64BitLibs) {
10815            // The application has both 64 and 32 bit bundled libraries. We check
10816            // here that the app declares multiArch support, and warn if it doesn't.
10817            //
10818            // We will be lenient here and record both ABIs. The primary will be the
10819            // ABI that's higher on the list, i.e, a device that's configured to prefer
10820            // 64 bit apps will see a 64 bit primary ABI,
10821
10822            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10823                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10824            }
10825
10826            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10827                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10828                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10829            } else {
10830                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10831                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10832            }
10833        } else {
10834            pkg.applicationInfo.primaryCpuAbi = null;
10835            pkg.applicationInfo.secondaryCpuAbi = null;
10836        }
10837    }
10838
10839    private void killApplication(String pkgName, int appId, String reason) {
10840        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10841    }
10842
10843    private void killApplication(String pkgName, int appId, int userId, String reason) {
10844        // Request the ActivityManager to kill the process(only for existing packages)
10845        // so that we do not end up in a confused state while the user is still using the older
10846        // version of the application while the new one gets installed.
10847        final long token = Binder.clearCallingIdentity();
10848        try {
10849            IActivityManager am = ActivityManager.getService();
10850            if (am != null) {
10851                try {
10852                    am.killApplication(pkgName, appId, userId, reason);
10853                } catch (RemoteException e) {
10854                }
10855            }
10856        } finally {
10857            Binder.restoreCallingIdentity(token);
10858        }
10859    }
10860
10861    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10862        // Remove the parent package setting
10863        PackageSetting ps = (PackageSetting) pkg.mExtras;
10864        if (ps != null) {
10865            removePackageLI(ps, chatty);
10866        }
10867        // Remove the child package setting
10868        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10869        for (int i = 0; i < childCount; i++) {
10870            PackageParser.Package childPkg = pkg.childPackages.get(i);
10871            ps = (PackageSetting) childPkg.mExtras;
10872            if (ps != null) {
10873                removePackageLI(ps, chatty);
10874            }
10875        }
10876    }
10877
10878    void removePackageLI(PackageSetting ps, boolean chatty) {
10879        if (DEBUG_INSTALL) {
10880            if (chatty)
10881                Log.d(TAG, "Removing package " + ps.name);
10882        }
10883
10884        // writer
10885        synchronized (mPackages) {
10886            mPackages.remove(ps.name);
10887            final PackageParser.Package pkg = ps.pkg;
10888            if (pkg != null) {
10889                cleanPackageDataStructuresLILPw(pkg, chatty);
10890            }
10891        }
10892    }
10893
10894    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10895        if (DEBUG_INSTALL) {
10896            if (chatty)
10897                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10898        }
10899
10900        // writer
10901        synchronized (mPackages) {
10902            // Remove the parent package
10903            mPackages.remove(pkg.applicationInfo.packageName);
10904            cleanPackageDataStructuresLILPw(pkg, chatty);
10905
10906            // Remove the child packages
10907            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10908            for (int i = 0; i < childCount; i++) {
10909                PackageParser.Package childPkg = pkg.childPackages.get(i);
10910                mPackages.remove(childPkg.applicationInfo.packageName);
10911                cleanPackageDataStructuresLILPw(childPkg, chatty);
10912            }
10913        }
10914    }
10915
10916    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10917        int N = pkg.providers.size();
10918        StringBuilder r = null;
10919        int i;
10920        for (i=0; i<N; i++) {
10921            PackageParser.Provider p = pkg.providers.get(i);
10922            mProviders.removeProvider(p);
10923            if (p.info.authority == null) {
10924
10925                /* There was another ContentProvider with this authority when
10926                 * this app was installed so this authority is null,
10927                 * Ignore it as we don't have to unregister the provider.
10928                 */
10929                continue;
10930            }
10931            String names[] = p.info.authority.split(";");
10932            for (int j = 0; j < names.length; j++) {
10933                if (mProvidersByAuthority.get(names[j]) == p) {
10934                    mProvidersByAuthority.remove(names[j]);
10935                    if (DEBUG_REMOVE) {
10936                        if (chatty)
10937                            Log.d(TAG, "Unregistered content provider: " + names[j]
10938                                    + ", className = " + p.info.name + ", isSyncable = "
10939                                    + p.info.isSyncable);
10940                    }
10941                }
10942            }
10943            if (DEBUG_REMOVE && chatty) {
10944                if (r == null) {
10945                    r = new StringBuilder(256);
10946                } else {
10947                    r.append(' ');
10948                }
10949                r.append(p.info.name);
10950            }
10951        }
10952        if (r != null) {
10953            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10954        }
10955
10956        N = pkg.services.size();
10957        r = null;
10958        for (i=0; i<N; i++) {
10959            PackageParser.Service s = pkg.services.get(i);
10960            mServices.removeService(s);
10961            if (chatty) {
10962                if (r == null) {
10963                    r = new StringBuilder(256);
10964                } else {
10965                    r.append(' ');
10966                }
10967                r.append(s.info.name);
10968            }
10969        }
10970        if (r != null) {
10971            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10972        }
10973
10974        N = pkg.receivers.size();
10975        r = null;
10976        for (i=0; i<N; i++) {
10977            PackageParser.Activity a = pkg.receivers.get(i);
10978            mReceivers.removeActivity(a, "receiver");
10979            if (DEBUG_REMOVE && chatty) {
10980                if (r == null) {
10981                    r = new StringBuilder(256);
10982                } else {
10983                    r.append(' ');
10984                }
10985                r.append(a.info.name);
10986            }
10987        }
10988        if (r != null) {
10989            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10990        }
10991
10992        N = pkg.activities.size();
10993        r = null;
10994        for (i=0; i<N; i++) {
10995            PackageParser.Activity a = pkg.activities.get(i);
10996            mActivities.removeActivity(a, "activity");
10997            if (DEBUG_REMOVE && chatty) {
10998                if (r == null) {
10999                    r = new StringBuilder(256);
11000                } else {
11001                    r.append(' ');
11002                }
11003                r.append(a.info.name);
11004            }
11005        }
11006        if (r != null) {
11007            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11008        }
11009
11010        N = pkg.permissions.size();
11011        r = null;
11012        for (i=0; i<N; i++) {
11013            PackageParser.Permission p = pkg.permissions.get(i);
11014            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11015            if (bp == null) {
11016                bp = mSettings.mPermissionTrees.get(p.info.name);
11017            }
11018            if (bp != null && bp.perm == p) {
11019                bp.perm = null;
11020                if (DEBUG_REMOVE && chatty) {
11021                    if (r == null) {
11022                        r = new StringBuilder(256);
11023                    } else {
11024                        r.append(' ');
11025                    }
11026                    r.append(p.info.name);
11027                }
11028            }
11029            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11030                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11031                if (appOpPkgs != null) {
11032                    appOpPkgs.remove(pkg.packageName);
11033                }
11034            }
11035        }
11036        if (r != null) {
11037            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11038        }
11039
11040        N = pkg.requestedPermissions.size();
11041        r = null;
11042        for (i=0; i<N; i++) {
11043            String perm = pkg.requestedPermissions.get(i);
11044            BasePermission bp = mSettings.mPermissions.get(perm);
11045            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11046                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11047                if (appOpPkgs != null) {
11048                    appOpPkgs.remove(pkg.packageName);
11049                    if (appOpPkgs.isEmpty()) {
11050                        mAppOpPermissionPackages.remove(perm);
11051                    }
11052                }
11053            }
11054        }
11055        if (r != null) {
11056            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11057        }
11058
11059        N = pkg.instrumentation.size();
11060        r = null;
11061        for (i=0; i<N; i++) {
11062            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11063            mInstrumentation.remove(a.getComponentName());
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, "  Instrumentation: " + r);
11075        }
11076
11077        r = null;
11078        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11079            // Only system apps can hold shared libraries.
11080            if (pkg.libraryNames != null) {
11081                for (i = 0; i < pkg.libraryNames.size(); i++) {
11082                    String name = pkg.libraryNames.get(i);
11083                    if (removeSharedLibraryLPw(name, 0)) {
11084                        if (DEBUG_REMOVE && chatty) {
11085                            if (r == null) {
11086                                r = new StringBuilder(256);
11087                            } else {
11088                                r.append(' ');
11089                            }
11090                            r.append(name);
11091                        }
11092                    }
11093                }
11094            }
11095        }
11096
11097        r = null;
11098
11099        // Any package can hold static shared libraries.
11100        if (pkg.staticSharedLibName != null) {
11101            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11102                if (DEBUG_REMOVE && chatty) {
11103                    if (r == null) {
11104                        r = new StringBuilder(256);
11105                    } else {
11106                        r.append(' ');
11107                    }
11108                    r.append(pkg.staticSharedLibName);
11109                }
11110            }
11111        }
11112
11113        if (r != null) {
11114            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11115        }
11116    }
11117
11118    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11119        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11120            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11121                return true;
11122            }
11123        }
11124        return false;
11125    }
11126
11127    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11128    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11129    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11130
11131    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11132        // Update the parent permissions
11133        updatePermissionsLPw(pkg.packageName, pkg, flags);
11134        // Update the child permissions
11135        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11136        for (int i = 0; i < childCount; i++) {
11137            PackageParser.Package childPkg = pkg.childPackages.get(i);
11138            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11139        }
11140    }
11141
11142    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11143            int flags) {
11144        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11145        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11146    }
11147
11148    private void updatePermissionsLPw(String changingPkg,
11149            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11150        // Make sure there are no dangling permission trees.
11151        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11152        while (it.hasNext()) {
11153            final BasePermission bp = it.next();
11154            if (bp.packageSetting == null) {
11155                // We may not yet have parsed the package, so just see if
11156                // we still know about its settings.
11157                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11158            }
11159            if (bp.packageSetting == null) {
11160                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11161                        + " from package " + bp.sourcePackage);
11162                it.remove();
11163            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11164                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11165                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11166                            + " from package " + bp.sourcePackage);
11167                    flags |= UPDATE_PERMISSIONS_ALL;
11168                    it.remove();
11169                }
11170            }
11171        }
11172
11173        // Make sure all dynamic permissions have been assigned to a package,
11174        // and make sure there are no dangling permissions.
11175        it = mSettings.mPermissions.values().iterator();
11176        while (it.hasNext()) {
11177            final BasePermission bp = it.next();
11178            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11179                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11180                        + bp.name + " pkg=" + bp.sourcePackage
11181                        + " info=" + bp.pendingInfo);
11182                if (bp.packageSetting == null && bp.pendingInfo != null) {
11183                    final BasePermission tree = findPermissionTreeLP(bp.name);
11184                    if (tree != null && tree.perm != null) {
11185                        bp.packageSetting = tree.packageSetting;
11186                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11187                                new PermissionInfo(bp.pendingInfo));
11188                        bp.perm.info.packageName = tree.perm.info.packageName;
11189                        bp.perm.info.name = bp.name;
11190                        bp.uid = tree.uid;
11191                    }
11192                }
11193            }
11194            if (bp.packageSetting == null) {
11195                // We may not yet have parsed the package, so just see if
11196                // we still know about its settings.
11197                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11198            }
11199            if (bp.packageSetting == null) {
11200                Slog.w(TAG, "Removing dangling permission: " + bp.name
11201                        + " from package " + bp.sourcePackage);
11202                it.remove();
11203            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11204                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11205                    Slog.i(TAG, "Removing old permission: " + bp.name
11206                            + " from package " + bp.sourcePackage);
11207                    flags |= UPDATE_PERMISSIONS_ALL;
11208                    it.remove();
11209                }
11210            }
11211        }
11212
11213        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11214        // Now update the permissions for all packages, in particular
11215        // replace the granted permissions of the system packages.
11216        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11217            for (PackageParser.Package pkg : mPackages.values()) {
11218                if (pkg != pkgInfo) {
11219                    // Only replace for packages on requested volume
11220                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11221                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11222                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11223                    grantPermissionsLPw(pkg, replace, changingPkg);
11224                }
11225            }
11226        }
11227
11228        if (pkgInfo != null) {
11229            // Only replace for packages on requested volume
11230            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11231            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11232                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11233            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11234        }
11235        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11236    }
11237
11238    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11239            String packageOfInterest) {
11240        // IMPORTANT: There are two types of permissions: install and runtime.
11241        // Install time permissions are granted when the app is installed to
11242        // all device users and users added in the future. Runtime permissions
11243        // are granted at runtime explicitly to specific users. Normal and signature
11244        // protected permissions are install time permissions. Dangerous permissions
11245        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11246        // otherwise they are runtime permissions. This function does not manage
11247        // runtime permissions except for the case an app targeting Lollipop MR1
11248        // being upgraded to target a newer SDK, in which case dangerous permissions
11249        // are transformed from install time to runtime ones.
11250
11251        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11252        if (ps == null) {
11253            return;
11254        }
11255
11256        PermissionsState permissionsState = ps.getPermissionsState();
11257        PermissionsState origPermissions = permissionsState;
11258
11259        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11260
11261        boolean runtimePermissionsRevoked = false;
11262        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11263
11264        boolean changedInstallPermission = false;
11265
11266        if (replace) {
11267            ps.installPermissionsFixed = false;
11268            if (!ps.isSharedUser()) {
11269                origPermissions = new PermissionsState(permissionsState);
11270                permissionsState.reset();
11271            } else {
11272                // We need to know only about runtime permission changes since the
11273                // calling code always writes the install permissions state but
11274                // the runtime ones are written only if changed. The only cases of
11275                // changed runtime permissions here are promotion of an install to
11276                // runtime and revocation of a runtime from a shared user.
11277                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11278                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11279                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11280                    runtimePermissionsRevoked = true;
11281                }
11282            }
11283        }
11284
11285        permissionsState.setGlobalGids(mGlobalGids);
11286
11287        final int N = pkg.requestedPermissions.size();
11288        for (int i=0; i<N; i++) {
11289            final String name = pkg.requestedPermissions.get(i);
11290            final BasePermission bp = mSettings.mPermissions.get(name);
11291
11292            if (DEBUG_INSTALL) {
11293                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11294            }
11295
11296            if (bp == null || bp.packageSetting == null) {
11297                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11298                    Slog.w(TAG, "Unknown permission " + name
11299                            + " in package " + pkg.packageName);
11300                }
11301                continue;
11302            }
11303
11304
11305            // Limit ephemeral apps to ephemeral allowed permissions.
11306            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11307                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11308                        + pkg.packageName);
11309                continue;
11310            }
11311
11312            final String perm = bp.name;
11313            boolean allowedSig = false;
11314            int grant = GRANT_DENIED;
11315
11316            // Keep track of app op permissions.
11317            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11318                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11319                if (pkgs == null) {
11320                    pkgs = new ArraySet<>();
11321                    mAppOpPermissionPackages.put(bp.name, pkgs);
11322                }
11323                pkgs.add(pkg.packageName);
11324            }
11325
11326            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11327            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11328                    >= Build.VERSION_CODES.M;
11329            switch (level) {
11330                case PermissionInfo.PROTECTION_NORMAL: {
11331                    // For all apps normal permissions are install time ones.
11332                    grant = GRANT_INSTALL;
11333                } break;
11334
11335                case PermissionInfo.PROTECTION_DANGEROUS: {
11336                    // If a permission review is required for legacy apps we represent
11337                    // their permissions as always granted runtime ones since we need
11338                    // to keep the review required permission flag per user while an
11339                    // install permission's state is shared across all users.
11340                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11341                        // For legacy apps dangerous permissions are install time ones.
11342                        grant = GRANT_INSTALL;
11343                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11344                        // For legacy apps that became modern, install becomes runtime.
11345                        grant = GRANT_UPGRADE;
11346                    } else if (mPromoteSystemApps
11347                            && isSystemApp(ps)
11348                            && mExistingSystemPackages.contains(ps.name)) {
11349                        // For legacy system apps, install becomes runtime.
11350                        // We cannot check hasInstallPermission() for system apps since those
11351                        // permissions were granted implicitly and not persisted pre-M.
11352                        grant = GRANT_UPGRADE;
11353                    } else {
11354                        // For modern apps keep runtime permissions unchanged.
11355                        grant = GRANT_RUNTIME;
11356                    }
11357                } break;
11358
11359                case PermissionInfo.PROTECTION_SIGNATURE: {
11360                    // For all apps signature permissions are install time ones.
11361                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11362                    if (allowedSig) {
11363                        grant = GRANT_INSTALL;
11364                    }
11365                } break;
11366            }
11367
11368            if (DEBUG_INSTALL) {
11369                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11370            }
11371
11372            if (grant != GRANT_DENIED) {
11373                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11374                    // If this is an existing, non-system package, then
11375                    // we can't add any new permissions to it.
11376                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11377                        // Except...  if this is a permission that was added
11378                        // to the platform (note: need to only do this when
11379                        // updating the platform).
11380                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11381                            grant = GRANT_DENIED;
11382                        }
11383                    }
11384                }
11385
11386                switch (grant) {
11387                    case GRANT_INSTALL: {
11388                        // Revoke this as runtime permission to handle the case of
11389                        // a runtime permission being downgraded to an install one.
11390                        // Also in permission review mode we keep dangerous permissions
11391                        // for legacy apps
11392                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11393                            if (origPermissions.getRuntimePermissionState(
11394                                    bp.name, userId) != null) {
11395                                // Revoke the runtime permission and clear the flags.
11396                                origPermissions.revokeRuntimePermission(bp, userId);
11397                                origPermissions.updatePermissionFlags(bp, userId,
11398                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11399                                // If we revoked a permission permission, we have to write.
11400                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11401                                        changedRuntimePermissionUserIds, userId);
11402                            }
11403                        }
11404                        // Grant an install permission.
11405                        if (permissionsState.grantInstallPermission(bp) !=
11406                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11407                            changedInstallPermission = true;
11408                        }
11409                    } break;
11410
11411                    case GRANT_RUNTIME: {
11412                        // Grant previously granted runtime permissions.
11413                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11414                            PermissionState permissionState = origPermissions
11415                                    .getRuntimePermissionState(bp.name, userId);
11416                            int flags = permissionState != null
11417                                    ? permissionState.getFlags() : 0;
11418                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11419                                // Don't propagate the permission in a permission review mode if
11420                                // the former was revoked, i.e. marked to not propagate on upgrade.
11421                                // Note that in a permission review mode install permissions are
11422                                // represented as constantly granted runtime ones since we need to
11423                                // keep a per user state associated with the permission. Also the
11424                                // revoke on upgrade flag is no longer applicable and is reset.
11425                                final boolean revokeOnUpgrade = (flags & PackageManager
11426                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11427                                if (revokeOnUpgrade) {
11428                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11429                                    // Since we changed the flags, we have to write.
11430                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11431                                            changedRuntimePermissionUserIds, userId);
11432                                }
11433                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11434                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11435                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11436                                        // If we cannot put the permission as it was,
11437                                        // we have to write.
11438                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11439                                                changedRuntimePermissionUserIds, userId);
11440                                    }
11441                                }
11442
11443                                // If the app supports runtime permissions no need for a review.
11444                                if (mPermissionReviewRequired
11445                                        && appSupportsRuntimePermissions
11446                                        && (flags & PackageManager
11447                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11448                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11449                                    // Since we changed the flags, we have to write.
11450                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11451                                            changedRuntimePermissionUserIds, userId);
11452                                }
11453                            } else if (mPermissionReviewRequired
11454                                    && !appSupportsRuntimePermissions) {
11455                                // For legacy apps that need a permission review, every new
11456                                // runtime permission is granted but it is pending a review.
11457                                // We also need to review only platform defined runtime
11458                                // permissions as these are the only ones the platform knows
11459                                // how to disable the API to simulate revocation as legacy
11460                                // apps don't expect to run with revoked permissions.
11461                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11462                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11463                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11464                                        // We changed the flags, hence have to write.
11465                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11466                                                changedRuntimePermissionUserIds, userId);
11467                                    }
11468                                }
11469                                if (permissionsState.grantRuntimePermission(bp, userId)
11470                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11471                                    // We changed the permission, hence have to write.
11472                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11473                                            changedRuntimePermissionUserIds, userId);
11474                                }
11475                            }
11476                            // Propagate the permission flags.
11477                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11478                        }
11479                    } break;
11480
11481                    case GRANT_UPGRADE: {
11482                        // Grant runtime permissions for a previously held install permission.
11483                        PermissionState permissionState = origPermissions
11484                                .getInstallPermissionState(bp.name);
11485                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11486
11487                        if (origPermissions.revokeInstallPermission(bp)
11488                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11489                            // We will be transferring the permission flags, so clear them.
11490                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11491                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11492                            changedInstallPermission = true;
11493                        }
11494
11495                        // If the permission is not to be promoted to runtime we ignore it and
11496                        // also its other flags as they are not applicable to install permissions.
11497                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11498                            for (int userId : currentUserIds) {
11499                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11500                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11501                                    // Transfer the permission flags.
11502                                    permissionsState.updatePermissionFlags(bp, userId,
11503                                            flags, flags);
11504                                    // If we granted the permission, we have to write.
11505                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11506                                            changedRuntimePermissionUserIds, userId);
11507                                }
11508                            }
11509                        }
11510                    } break;
11511
11512                    default: {
11513                        if (packageOfInterest == null
11514                                || packageOfInterest.equals(pkg.packageName)) {
11515                            Slog.w(TAG, "Not granting permission " + perm
11516                                    + " to package " + pkg.packageName
11517                                    + " because it was previously installed without");
11518                        }
11519                    } break;
11520                }
11521            } else {
11522                if (permissionsState.revokeInstallPermission(bp) !=
11523                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11524                    // Also drop the permission flags.
11525                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11526                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11527                    changedInstallPermission = true;
11528                    Slog.i(TAG, "Un-granting permission " + perm
11529                            + " from package " + pkg.packageName
11530                            + " (protectionLevel=" + bp.protectionLevel
11531                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11532                            + ")");
11533                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11534                    // Don't print warning for app op permissions, since it is fine for them
11535                    // not to be granted, there is a UI for the user to decide.
11536                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11537                        Slog.w(TAG, "Not granting permission " + perm
11538                                + " to package " + pkg.packageName
11539                                + " (protectionLevel=" + bp.protectionLevel
11540                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11541                                + ")");
11542                    }
11543                }
11544            }
11545        }
11546
11547        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11548                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11549            // This is the first that we have heard about this package, so the
11550            // permissions we have now selected are fixed until explicitly
11551            // changed.
11552            ps.installPermissionsFixed = true;
11553        }
11554
11555        // Persist the runtime permissions state for users with changes. If permissions
11556        // were revoked because no app in the shared user declares them we have to
11557        // write synchronously to avoid losing runtime permissions state.
11558        for (int userId : changedRuntimePermissionUserIds) {
11559            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11560        }
11561    }
11562
11563    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11564        boolean allowed = false;
11565        final int NP = PackageParser.NEW_PERMISSIONS.length;
11566        for (int ip=0; ip<NP; ip++) {
11567            final PackageParser.NewPermissionInfo npi
11568                    = PackageParser.NEW_PERMISSIONS[ip];
11569            if (npi.name.equals(perm)
11570                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11571                allowed = true;
11572                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11573                        + pkg.packageName);
11574                break;
11575            }
11576        }
11577        return allowed;
11578    }
11579
11580    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11581            BasePermission bp, PermissionsState origPermissions) {
11582        boolean privilegedPermission = (bp.protectionLevel
11583                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11584        boolean privappPermissionsDisable =
11585                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11586        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11587        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11588        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11589                && !platformPackage && platformPermission) {
11590            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11591                    .getPrivAppPermissions(pkg.packageName);
11592            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11593            if (!whitelisted) {
11594                Slog.w(TAG, "Privileged permission " + perm + " for package "
11595                        + pkg.packageName + " - not in privapp-permissions whitelist");
11596                // Only report violations for apps on system image
11597                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11598                    if (mPrivappPermissionsViolations == null) {
11599                        mPrivappPermissionsViolations = new ArraySet<>();
11600                    }
11601                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11602                }
11603                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11604                    return false;
11605                }
11606            }
11607        }
11608        boolean allowed = (compareSignatures(
11609                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11610                        == PackageManager.SIGNATURE_MATCH)
11611                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11612                        == PackageManager.SIGNATURE_MATCH);
11613        if (!allowed && privilegedPermission) {
11614            if (isSystemApp(pkg)) {
11615                // For updated system applications, a system permission
11616                // is granted only if it had been defined by the original application.
11617                if (pkg.isUpdatedSystemApp()) {
11618                    final PackageSetting sysPs = mSettings
11619                            .getDisabledSystemPkgLPr(pkg.packageName);
11620                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11621                        // If the original was granted this permission, we take
11622                        // that grant decision as read and propagate it to the
11623                        // update.
11624                        if (sysPs.isPrivileged()) {
11625                            allowed = true;
11626                        }
11627                    } else {
11628                        // The system apk may have been updated with an older
11629                        // version of the one on the data partition, but which
11630                        // granted a new system permission that it didn't have
11631                        // before.  In this case we do want to allow the app to
11632                        // now get the new permission if the ancestral apk is
11633                        // privileged to get it.
11634                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11635                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11636                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11637                                    allowed = true;
11638                                    break;
11639                                }
11640                            }
11641                        }
11642                        // Also if a privileged parent package on the system image or any of
11643                        // its children requested a privileged permission, the updated child
11644                        // packages can also get the permission.
11645                        if (pkg.parentPackage != null) {
11646                            final PackageSetting disabledSysParentPs = mSettings
11647                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11648                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11649                                    && disabledSysParentPs.isPrivileged()) {
11650                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11651                                    allowed = true;
11652                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11653                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11654                                    for (int i = 0; i < count; i++) {
11655                                        PackageParser.Package disabledSysChildPkg =
11656                                                disabledSysParentPs.pkg.childPackages.get(i);
11657                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11658                                                perm)) {
11659                                            allowed = true;
11660                                            break;
11661                                        }
11662                                    }
11663                                }
11664                            }
11665                        }
11666                    }
11667                } else {
11668                    allowed = isPrivilegedApp(pkg);
11669                }
11670            }
11671        }
11672        if (!allowed) {
11673            if (!allowed && (bp.protectionLevel
11674                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11675                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11676                // If this was a previously normal/dangerous permission that got moved
11677                // to a system permission as part of the runtime permission redesign, then
11678                // we still want to blindly grant it to old apps.
11679                allowed = true;
11680            }
11681            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11682                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11683                // If this permission is to be granted to the system installer and
11684                // this app is an installer, then it gets the permission.
11685                allowed = true;
11686            }
11687            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11688                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11689                // If this permission is to be granted to the system verifier and
11690                // this app is a verifier, then it gets the permission.
11691                allowed = true;
11692            }
11693            if (!allowed && (bp.protectionLevel
11694                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11695                    && isSystemApp(pkg)) {
11696                // Any pre-installed system app is allowed to get this permission.
11697                allowed = true;
11698            }
11699            if (!allowed && (bp.protectionLevel
11700                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11701                // For development permissions, a development permission
11702                // is granted only if it was already granted.
11703                allowed = origPermissions.hasInstallPermission(perm);
11704            }
11705            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11706                    && pkg.packageName.equals(mSetupWizardPackage)) {
11707                // If this permission is to be granted to the system setup wizard and
11708                // this app is a setup wizard, then it gets the permission.
11709                allowed = true;
11710            }
11711        }
11712        return allowed;
11713    }
11714
11715    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11716        final int permCount = pkg.requestedPermissions.size();
11717        for (int j = 0; j < permCount; j++) {
11718            String requestedPermission = pkg.requestedPermissions.get(j);
11719            if (permission.equals(requestedPermission)) {
11720                return true;
11721            }
11722        }
11723        return false;
11724    }
11725
11726    final class ActivityIntentResolver
11727            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11728        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11729                boolean defaultOnly, int userId) {
11730            if (!sUserManager.exists(userId)) return null;
11731            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11732            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11733        }
11734
11735        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11736                int userId) {
11737            if (!sUserManager.exists(userId)) return null;
11738            mFlags = flags;
11739            return super.queryIntent(intent, resolvedType,
11740                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11741                    userId);
11742        }
11743
11744        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11745                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11746            if (!sUserManager.exists(userId)) return null;
11747            if (packageActivities == null) {
11748                return null;
11749            }
11750            mFlags = flags;
11751            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11752            final int N = packageActivities.size();
11753            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11754                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11755
11756            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11757            for (int i = 0; i < N; ++i) {
11758                intentFilters = packageActivities.get(i).intents;
11759                if (intentFilters != null && intentFilters.size() > 0) {
11760                    PackageParser.ActivityIntentInfo[] array =
11761                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11762                    intentFilters.toArray(array);
11763                    listCut.add(array);
11764                }
11765            }
11766            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11767        }
11768
11769        /**
11770         * Finds a privileged activity that matches the specified activity names.
11771         */
11772        private PackageParser.Activity findMatchingActivity(
11773                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11774            for (PackageParser.Activity sysActivity : activityList) {
11775                if (sysActivity.info.name.equals(activityInfo.name)) {
11776                    return sysActivity;
11777                }
11778                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11779                    return sysActivity;
11780                }
11781                if (sysActivity.info.targetActivity != null) {
11782                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11783                        return sysActivity;
11784                    }
11785                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11786                        return sysActivity;
11787                    }
11788                }
11789            }
11790            return null;
11791        }
11792
11793        public class IterGenerator<E> {
11794            public Iterator<E> generate(ActivityIntentInfo info) {
11795                return null;
11796            }
11797        }
11798
11799        public class ActionIterGenerator extends IterGenerator<String> {
11800            @Override
11801            public Iterator<String> generate(ActivityIntentInfo info) {
11802                return info.actionsIterator();
11803            }
11804        }
11805
11806        public class CategoriesIterGenerator extends IterGenerator<String> {
11807            @Override
11808            public Iterator<String> generate(ActivityIntentInfo info) {
11809                return info.categoriesIterator();
11810            }
11811        }
11812
11813        public class SchemesIterGenerator extends IterGenerator<String> {
11814            @Override
11815            public Iterator<String> generate(ActivityIntentInfo info) {
11816                return info.schemesIterator();
11817            }
11818        }
11819
11820        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11821            @Override
11822            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11823                return info.authoritiesIterator();
11824            }
11825        }
11826
11827        /**
11828         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11829         * MODIFIED. Do not pass in a list that should not be changed.
11830         */
11831        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11832                IterGenerator<T> generator, Iterator<T> searchIterator) {
11833            // loop through the set of actions; every one must be found in the intent filter
11834            while (searchIterator.hasNext()) {
11835                // we must have at least one filter in the list to consider a match
11836                if (intentList.size() == 0) {
11837                    break;
11838                }
11839
11840                final T searchAction = searchIterator.next();
11841
11842                // loop through the set of intent filters
11843                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11844                while (intentIter.hasNext()) {
11845                    final ActivityIntentInfo intentInfo = intentIter.next();
11846                    boolean selectionFound = false;
11847
11848                    // loop through the intent filter's selection criteria; at least one
11849                    // of them must match the searched criteria
11850                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11851                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11852                        final T intentSelection = intentSelectionIter.next();
11853                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11854                            selectionFound = true;
11855                            break;
11856                        }
11857                    }
11858
11859                    // the selection criteria wasn't found in this filter's set; this filter
11860                    // is not a potential match
11861                    if (!selectionFound) {
11862                        intentIter.remove();
11863                    }
11864                }
11865            }
11866        }
11867
11868        private boolean isProtectedAction(ActivityIntentInfo filter) {
11869            final Iterator<String> actionsIter = filter.actionsIterator();
11870            while (actionsIter != null && actionsIter.hasNext()) {
11871                final String filterAction = actionsIter.next();
11872                if (PROTECTED_ACTIONS.contains(filterAction)) {
11873                    return true;
11874                }
11875            }
11876            return false;
11877        }
11878
11879        /**
11880         * Adjusts the priority of the given intent filter according to policy.
11881         * <p>
11882         * <ul>
11883         * <li>The priority for non privileged applications is capped to '0'</li>
11884         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11885         * <li>The priority for unbundled updates to privileged applications is capped to the
11886         *      priority defined on the system partition</li>
11887         * </ul>
11888         * <p>
11889         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11890         * allowed to obtain any priority on any action.
11891         */
11892        private void adjustPriority(
11893                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11894            // nothing to do; priority is fine as-is
11895            if (intent.getPriority() <= 0) {
11896                return;
11897            }
11898
11899            final ActivityInfo activityInfo = intent.activity.info;
11900            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11901
11902            final boolean privilegedApp =
11903                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11904            if (!privilegedApp) {
11905                // non-privileged applications can never define a priority >0
11906                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11907                        + " package: " + applicationInfo.packageName
11908                        + " activity: " + intent.activity.className
11909                        + " origPrio: " + intent.getPriority());
11910                intent.setPriority(0);
11911                return;
11912            }
11913
11914            if (systemActivities == null) {
11915                // the system package is not disabled; we're parsing the system partition
11916                if (isProtectedAction(intent)) {
11917                    if (mDeferProtectedFilters) {
11918                        // We can't deal with these just yet. No component should ever obtain a
11919                        // >0 priority for a protected actions, with ONE exception -- the setup
11920                        // wizard. The setup wizard, however, cannot be known until we're able to
11921                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11922                        // until all intent filters have been processed. Chicken, meet egg.
11923                        // Let the filter temporarily have a high priority and rectify the
11924                        // priorities after all system packages have been scanned.
11925                        mProtectedFilters.add(intent);
11926                        if (DEBUG_FILTERS) {
11927                            Slog.i(TAG, "Protected action; save for later;"
11928                                    + " package: " + applicationInfo.packageName
11929                                    + " activity: " + intent.activity.className
11930                                    + " origPrio: " + intent.getPriority());
11931                        }
11932                        return;
11933                    } else {
11934                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11935                            Slog.i(TAG, "No setup wizard;"
11936                                + " All protected intents capped to priority 0");
11937                        }
11938                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11939                            if (DEBUG_FILTERS) {
11940                                Slog.i(TAG, "Found setup wizard;"
11941                                    + " allow priority " + intent.getPriority() + ";"
11942                                    + " package: " + intent.activity.info.packageName
11943                                    + " activity: " + intent.activity.className
11944                                    + " priority: " + intent.getPriority());
11945                            }
11946                            // setup wizard gets whatever it wants
11947                            return;
11948                        }
11949                        Slog.w(TAG, "Protected action; cap priority to 0;"
11950                                + " package: " + intent.activity.info.packageName
11951                                + " activity: " + intent.activity.className
11952                                + " origPrio: " + intent.getPriority());
11953                        intent.setPriority(0);
11954                        return;
11955                    }
11956                }
11957                // privileged apps on the system image get whatever priority they request
11958                return;
11959            }
11960
11961            // privileged app unbundled update ... try to find the same activity
11962            final PackageParser.Activity foundActivity =
11963                    findMatchingActivity(systemActivities, activityInfo);
11964            if (foundActivity == null) {
11965                // this is a new activity; it cannot obtain >0 priority
11966                if (DEBUG_FILTERS) {
11967                    Slog.i(TAG, "New activity; cap priority to 0;"
11968                            + " package: " + applicationInfo.packageName
11969                            + " activity: " + intent.activity.className
11970                            + " origPrio: " + intent.getPriority());
11971                }
11972                intent.setPriority(0);
11973                return;
11974            }
11975
11976            // found activity, now check for filter equivalence
11977
11978            // a shallow copy is enough; we modify the list, not its contents
11979            final List<ActivityIntentInfo> intentListCopy =
11980                    new ArrayList<>(foundActivity.intents);
11981            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11982
11983            // find matching action subsets
11984            final Iterator<String> actionsIterator = intent.actionsIterator();
11985            if (actionsIterator != null) {
11986                getIntentListSubset(
11987                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11988                if (intentListCopy.size() == 0) {
11989                    // no more intents to match; we're not equivalent
11990                    if (DEBUG_FILTERS) {
11991                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11992                                + " package: " + applicationInfo.packageName
11993                                + " activity: " + intent.activity.className
11994                                + " origPrio: " + intent.getPriority());
11995                    }
11996                    intent.setPriority(0);
11997                    return;
11998                }
11999            }
12000
12001            // find matching category subsets
12002            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12003            if (categoriesIterator != null) {
12004                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12005                        categoriesIterator);
12006                if (intentListCopy.size() == 0) {
12007                    // no more intents to match; we're not equivalent
12008                    if (DEBUG_FILTERS) {
12009                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12010                                + " package: " + applicationInfo.packageName
12011                                + " activity: " + intent.activity.className
12012                                + " origPrio: " + intent.getPriority());
12013                    }
12014                    intent.setPriority(0);
12015                    return;
12016                }
12017            }
12018
12019            // find matching schemes subsets
12020            final Iterator<String> schemesIterator = intent.schemesIterator();
12021            if (schemesIterator != null) {
12022                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12023                        schemesIterator);
12024                if (intentListCopy.size() == 0) {
12025                    // no more intents to match; we're not equivalent
12026                    if (DEBUG_FILTERS) {
12027                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12028                                + " package: " + applicationInfo.packageName
12029                                + " activity: " + intent.activity.className
12030                                + " origPrio: " + intent.getPriority());
12031                    }
12032                    intent.setPriority(0);
12033                    return;
12034                }
12035            }
12036
12037            // find matching authorities subsets
12038            final Iterator<IntentFilter.AuthorityEntry>
12039                    authoritiesIterator = intent.authoritiesIterator();
12040            if (authoritiesIterator != null) {
12041                getIntentListSubset(intentListCopy,
12042                        new AuthoritiesIterGenerator(),
12043                        authoritiesIterator);
12044                if (intentListCopy.size() == 0) {
12045                    // no more intents to match; we're not equivalent
12046                    if (DEBUG_FILTERS) {
12047                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12048                                + " package: " + applicationInfo.packageName
12049                                + " activity: " + intent.activity.className
12050                                + " origPrio: " + intent.getPriority());
12051                    }
12052                    intent.setPriority(0);
12053                    return;
12054                }
12055            }
12056
12057            // we found matching filter(s); app gets the max priority of all intents
12058            int cappedPriority = 0;
12059            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12060                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12061            }
12062            if (intent.getPriority() > cappedPriority) {
12063                if (DEBUG_FILTERS) {
12064                    Slog.i(TAG, "Found matching filter(s);"
12065                            + " cap priority to " + cappedPriority + ";"
12066                            + " package: " + applicationInfo.packageName
12067                            + " activity: " + intent.activity.className
12068                            + " origPrio: " + intent.getPriority());
12069                }
12070                intent.setPriority(cappedPriority);
12071                return;
12072            }
12073            // all this for nothing; the requested priority was <= what was on the system
12074        }
12075
12076        public final void addActivity(PackageParser.Activity a, String type) {
12077            mActivities.put(a.getComponentName(), a);
12078            if (DEBUG_SHOW_INFO)
12079                Log.v(
12080                TAG, "  " + type + " " +
12081                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12082            if (DEBUG_SHOW_INFO)
12083                Log.v(TAG, "    Class=" + a.info.name);
12084            final int NI = a.intents.size();
12085            for (int j=0; j<NI; j++) {
12086                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12087                if ("activity".equals(type)) {
12088                    final PackageSetting ps =
12089                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12090                    final List<PackageParser.Activity> systemActivities =
12091                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12092                    adjustPriority(systemActivities, intent);
12093                }
12094                if (DEBUG_SHOW_INFO) {
12095                    Log.v(TAG, "    IntentFilter:");
12096                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12097                }
12098                if (!intent.debugCheck()) {
12099                    Log.w(TAG, "==> For Activity " + a.info.name);
12100                }
12101                addFilter(intent);
12102            }
12103        }
12104
12105        public final void removeActivity(PackageParser.Activity a, String type) {
12106            mActivities.remove(a.getComponentName());
12107            if (DEBUG_SHOW_INFO) {
12108                Log.v(TAG, "  " + type + " "
12109                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12110                                : a.info.name) + ":");
12111                Log.v(TAG, "    Class=" + a.info.name);
12112            }
12113            final int NI = a.intents.size();
12114            for (int j=0; j<NI; j++) {
12115                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12116                if (DEBUG_SHOW_INFO) {
12117                    Log.v(TAG, "    IntentFilter:");
12118                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12119                }
12120                removeFilter(intent);
12121            }
12122        }
12123
12124        @Override
12125        protected boolean allowFilterResult(
12126                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12127            ActivityInfo filterAi = filter.activity.info;
12128            for (int i=dest.size()-1; i>=0; i--) {
12129                ActivityInfo destAi = dest.get(i).activityInfo;
12130                if (destAi.name == filterAi.name
12131                        && destAi.packageName == filterAi.packageName) {
12132                    return false;
12133                }
12134            }
12135            return true;
12136        }
12137
12138        @Override
12139        protected ActivityIntentInfo[] newArray(int size) {
12140            return new ActivityIntentInfo[size];
12141        }
12142
12143        @Override
12144        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12145            if (!sUserManager.exists(userId)) return true;
12146            PackageParser.Package p = filter.activity.owner;
12147            if (p != null) {
12148                PackageSetting ps = (PackageSetting)p.mExtras;
12149                if (ps != null) {
12150                    // System apps are never considered stopped for purposes of
12151                    // filtering, because there may be no way for the user to
12152                    // actually re-launch them.
12153                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12154                            && ps.getStopped(userId);
12155                }
12156            }
12157            return false;
12158        }
12159
12160        @Override
12161        protected boolean isPackageForFilter(String packageName,
12162                PackageParser.ActivityIntentInfo info) {
12163            return packageName.equals(info.activity.owner.packageName);
12164        }
12165
12166        @Override
12167        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12168                int match, int userId) {
12169            if (!sUserManager.exists(userId)) return null;
12170            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12171                return null;
12172            }
12173            final PackageParser.Activity activity = info.activity;
12174            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12175            if (ps == null) {
12176                return null;
12177            }
12178            final PackageUserState userState = ps.readUserState(userId);
12179            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12180                    userState, userId);
12181            if (ai == null) {
12182                return null;
12183            }
12184            final boolean matchVisibleToInstantApp =
12185                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12186            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12187            // throw out filters that aren't visible to ephemeral apps
12188            if (matchVisibleToInstantApp
12189                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12190                return null;
12191            }
12192            // throw out ephemeral filters if we're not explicitly requesting them
12193            if (!isInstantApp && userState.instantApp) {
12194                return null;
12195            }
12196            // throw out instant app filters if updates are available; will trigger
12197            // instant app resolution
12198            if (userState.instantApp && ps.isUpdateAvailable()) {
12199                return null;
12200            }
12201            final ResolveInfo res = new ResolveInfo();
12202            res.activityInfo = ai;
12203            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12204                res.filter = info;
12205            }
12206            if (info != null) {
12207                res.handleAllWebDataURI = info.handleAllWebDataURI();
12208            }
12209            res.priority = info.getPriority();
12210            res.preferredOrder = activity.owner.mPreferredOrder;
12211            //System.out.println("Result: " + res.activityInfo.className +
12212            //                   " = " + res.priority);
12213            res.match = match;
12214            res.isDefault = info.hasDefault;
12215            res.labelRes = info.labelRes;
12216            res.nonLocalizedLabel = info.nonLocalizedLabel;
12217            if (userNeedsBadging(userId)) {
12218                res.noResourceId = true;
12219            } else {
12220                res.icon = info.icon;
12221            }
12222            res.iconResourceId = info.icon;
12223            res.system = res.activityInfo.applicationInfo.isSystemApp();
12224            res.instantAppAvailable = userState.instantApp;
12225            return res;
12226        }
12227
12228        @Override
12229        protected void sortResults(List<ResolveInfo> results) {
12230            Collections.sort(results, mResolvePrioritySorter);
12231        }
12232
12233        @Override
12234        protected void dumpFilter(PrintWriter out, String prefix,
12235                PackageParser.ActivityIntentInfo filter) {
12236            out.print(prefix); out.print(
12237                    Integer.toHexString(System.identityHashCode(filter.activity)));
12238                    out.print(' ');
12239                    filter.activity.printComponentShortName(out);
12240                    out.print(" filter ");
12241                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12242        }
12243
12244        @Override
12245        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12246            return filter.activity;
12247        }
12248
12249        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12250            PackageParser.Activity activity = (PackageParser.Activity)label;
12251            out.print(prefix); out.print(
12252                    Integer.toHexString(System.identityHashCode(activity)));
12253                    out.print(' ');
12254                    activity.printComponentShortName(out);
12255            if (count > 1) {
12256                out.print(" ("); out.print(count); out.print(" filters)");
12257            }
12258            out.println();
12259        }
12260
12261        // Keys are String (activity class name), values are Activity.
12262        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12263                = new ArrayMap<ComponentName, PackageParser.Activity>();
12264        private int mFlags;
12265    }
12266
12267    private final class ServiceIntentResolver
12268            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12269        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12270                boolean defaultOnly, int userId) {
12271            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12272            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12273        }
12274
12275        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12276                int userId) {
12277            if (!sUserManager.exists(userId)) return null;
12278            mFlags = flags;
12279            return super.queryIntent(intent, resolvedType,
12280                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12281                    userId);
12282        }
12283
12284        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12285                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12286            if (!sUserManager.exists(userId)) return null;
12287            if (packageServices == null) {
12288                return null;
12289            }
12290            mFlags = flags;
12291            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12292            final int N = packageServices.size();
12293            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12294                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12295
12296            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12297            for (int i = 0; i < N; ++i) {
12298                intentFilters = packageServices.get(i).intents;
12299                if (intentFilters != null && intentFilters.size() > 0) {
12300                    PackageParser.ServiceIntentInfo[] array =
12301                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12302                    intentFilters.toArray(array);
12303                    listCut.add(array);
12304                }
12305            }
12306            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12307        }
12308
12309        public final void addService(PackageParser.Service s) {
12310            mServices.put(s.getComponentName(), s);
12311            if (DEBUG_SHOW_INFO) {
12312                Log.v(TAG, "  "
12313                        + (s.info.nonLocalizedLabel != null
12314                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12315                Log.v(TAG, "    Class=" + s.info.name);
12316            }
12317            final int NI = s.intents.size();
12318            int j;
12319            for (j=0; j<NI; j++) {
12320                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12321                if (DEBUG_SHOW_INFO) {
12322                    Log.v(TAG, "    IntentFilter:");
12323                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12324                }
12325                if (!intent.debugCheck()) {
12326                    Log.w(TAG, "==> For Service " + s.info.name);
12327                }
12328                addFilter(intent);
12329            }
12330        }
12331
12332        public final void removeService(PackageParser.Service s) {
12333            mServices.remove(s.getComponentName());
12334            if (DEBUG_SHOW_INFO) {
12335                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12336                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12337                Log.v(TAG, "    Class=" + s.info.name);
12338            }
12339            final int NI = s.intents.size();
12340            int j;
12341            for (j=0; j<NI; j++) {
12342                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12343                if (DEBUG_SHOW_INFO) {
12344                    Log.v(TAG, "    IntentFilter:");
12345                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12346                }
12347                removeFilter(intent);
12348            }
12349        }
12350
12351        @Override
12352        protected boolean allowFilterResult(
12353                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12354            ServiceInfo filterSi = filter.service.info;
12355            for (int i=dest.size()-1; i>=0; i--) {
12356                ServiceInfo destAi = dest.get(i).serviceInfo;
12357                if (destAi.name == filterSi.name
12358                        && destAi.packageName == filterSi.packageName) {
12359                    return false;
12360                }
12361            }
12362            return true;
12363        }
12364
12365        @Override
12366        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12367            return new PackageParser.ServiceIntentInfo[size];
12368        }
12369
12370        @Override
12371        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12372            if (!sUserManager.exists(userId)) return true;
12373            PackageParser.Package p = filter.service.owner;
12374            if (p != null) {
12375                PackageSetting ps = (PackageSetting)p.mExtras;
12376                if (ps != null) {
12377                    // System apps are never considered stopped for purposes of
12378                    // filtering, because there may be no way for the user to
12379                    // actually re-launch them.
12380                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12381                            && ps.getStopped(userId);
12382                }
12383            }
12384            return false;
12385        }
12386
12387        @Override
12388        protected boolean isPackageForFilter(String packageName,
12389                PackageParser.ServiceIntentInfo info) {
12390            return packageName.equals(info.service.owner.packageName);
12391        }
12392
12393        @Override
12394        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12395                int match, int userId) {
12396            if (!sUserManager.exists(userId)) return null;
12397            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12398            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12399                return null;
12400            }
12401            final PackageParser.Service service = info.service;
12402            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12403            if (ps == null) {
12404                return null;
12405            }
12406            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12407                    ps.readUserState(userId), userId);
12408            if (si == null) {
12409                return null;
12410            }
12411            final ResolveInfo res = new ResolveInfo();
12412            res.serviceInfo = si;
12413            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12414                res.filter = filter;
12415            }
12416            res.priority = info.getPriority();
12417            res.preferredOrder = service.owner.mPreferredOrder;
12418            res.match = match;
12419            res.isDefault = info.hasDefault;
12420            res.labelRes = info.labelRes;
12421            res.nonLocalizedLabel = info.nonLocalizedLabel;
12422            res.icon = info.icon;
12423            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12424            return res;
12425        }
12426
12427        @Override
12428        protected void sortResults(List<ResolveInfo> results) {
12429            Collections.sort(results, mResolvePrioritySorter);
12430        }
12431
12432        @Override
12433        protected void dumpFilter(PrintWriter out, String prefix,
12434                PackageParser.ServiceIntentInfo filter) {
12435            out.print(prefix); out.print(
12436                    Integer.toHexString(System.identityHashCode(filter.service)));
12437                    out.print(' ');
12438                    filter.service.printComponentShortName(out);
12439                    out.print(" filter ");
12440                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12441        }
12442
12443        @Override
12444        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12445            return filter.service;
12446        }
12447
12448        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12449            PackageParser.Service service = (PackageParser.Service)label;
12450            out.print(prefix); out.print(
12451                    Integer.toHexString(System.identityHashCode(service)));
12452                    out.print(' ');
12453                    service.printComponentShortName(out);
12454            if (count > 1) {
12455                out.print(" ("); out.print(count); out.print(" filters)");
12456            }
12457            out.println();
12458        }
12459
12460//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12461//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12462//            final List<ResolveInfo> retList = Lists.newArrayList();
12463//            while (i.hasNext()) {
12464//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12465//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12466//                    retList.add(resolveInfo);
12467//                }
12468//            }
12469//            return retList;
12470//        }
12471
12472        // Keys are String (activity class name), values are Activity.
12473        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12474                = new ArrayMap<ComponentName, PackageParser.Service>();
12475        private int mFlags;
12476    }
12477
12478    private final class ProviderIntentResolver
12479            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12480        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12481                boolean defaultOnly, int userId) {
12482            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12483            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12484        }
12485
12486        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12487                int userId) {
12488            if (!sUserManager.exists(userId))
12489                return null;
12490            mFlags = flags;
12491            return super.queryIntent(intent, resolvedType,
12492                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12493                    userId);
12494        }
12495
12496        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12497                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12498            if (!sUserManager.exists(userId))
12499                return null;
12500            if (packageProviders == null) {
12501                return null;
12502            }
12503            mFlags = flags;
12504            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12505            final int N = packageProviders.size();
12506            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12507                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12508
12509            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12510            for (int i = 0; i < N; ++i) {
12511                intentFilters = packageProviders.get(i).intents;
12512                if (intentFilters != null && intentFilters.size() > 0) {
12513                    PackageParser.ProviderIntentInfo[] array =
12514                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12515                    intentFilters.toArray(array);
12516                    listCut.add(array);
12517                }
12518            }
12519            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12520        }
12521
12522        public final void addProvider(PackageParser.Provider p) {
12523            if (mProviders.containsKey(p.getComponentName())) {
12524                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12525                return;
12526            }
12527
12528            mProviders.put(p.getComponentName(), p);
12529            if (DEBUG_SHOW_INFO) {
12530                Log.v(TAG, "  "
12531                        + (p.info.nonLocalizedLabel != null
12532                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12533                Log.v(TAG, "    Class=" + p.info.name);
12534            }
12535            final int NI = p.intents.size();
12536            int j;
12537            for (j = 0; j < NI; j++) {
12538                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12539                if (DEBUG_SHOW_INFO) {
12540                    Log.v(TAG, "    IntentFilter:");
12541                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12542                }
12543                if (!intent.debugCheck()) {
12544                    Log.w(TAG, "==> For Provider " + p.info.name);
12545                }
12546                addFilter(intent);
12547            }
12548        }
12549
12550        public final void removeProvider(PackageParser.Provider p) {
12551            mProviders.remove(p.getComponentName());
12552            if (DEBUG_SHOW_INFO) {
12553                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12554                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12555                Log.v(TAG, "    Class=" + p.info.name);
12556            }
12557            final int NI = p.intents.size();
12558            int j;
12559            for (j = 0; j < NI; j++) {
12560                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12561                if (DEBUG_SHOW_INFO) {
12562                    Log.v(TAG, "    IntentFilter:");
12563                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12564                }
12565                removeFilter(intent);
12566            }
12567        }
12568
12569        @Override
12570        protected boolean allowFilterResult(
12571                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12572            ProviderInfo filterPi = filter.provider.info;
12573            for (int i = dest.size() - 1; i >= 0; i--) {
12574                ProviderInfo destPi = dest.get(i).providerInfo;
12575                if (destPi.name == filterPi.name
12576                        && destPi.packageName == filterPi.packageName) {
12577                    return false;
12578                }
12579            }
12580            return true;
12581        }
12582
12583        @Override
12584        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12585            return new PackageParser.ProviderIntentInfo[size];
12586        }
12587
12588        @Override
12589        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12590            if (!sUserManager.exists(userId))
12591                return true;
12592            PackageParser.Package p = filter.provider.owner;
12593            if (p != null) {
12594                PackageSetting ps = (PackageSetting) p.mExtras;
12595                if (ps != null) {
12596                    // System apps are never considered stopped for purposes of
12597                    // filtering, because there may be no way for the user to
12598                    // actually re-launch them.
12599                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12600                            && ps.getStopped(userId);
12601                }
12602            }
12603            return false;
12604        }
12605
12606        @Override
12607        protected boolean isPackageForFilter(String packageName,
12608                PackageParser.ProviderIntentInfo info) {
12609            return packageName.equals(info.provider.owner.packageName);
12610        }
12611
12612        @Override
12613        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12614                int match, int userId) {
12615            if (!sUserManager.exists(userId))
12616                return null;
12617            final PackageParser.ProviderIntentInfo info = filter;
12618            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12619                return null;
12620            }
12621            final PackageParser.Provider provider = info.provider;
12622            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12623            if (ps == null) {
12624                return null;
12625            }
12626            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12627                    ps.readUserState(userId), userId);
12628            if (pi == null) {
12629                return null;
12630            }
12631            final ResolveInfo res = new ResolveInfo();
12632            res.providerInfo = pi;
12633            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12634                res.filter = filter;
12635            }
12636            res.priority = info.getPriority();
12637            res.preferredOrder = provider.owner.mPreferredOrder;
12638            res.match = match;
12639            res.isDefault = info.hasDefault;
12640            res.labelRes = info.labelRes;
12641            res.nonLocalizedLabel = info.nonLocalizedLabel;
12642            res.icon = info.icon;
12643            res.system = res.providerInfo.applicationInfo.isSystemApp();
12644            return res;
12645        }
12646
12647        @Override
12648        protected void sortResults(List<ResolveInfo> results) {
12649            Collections.sort(results, mResolvePrioritySorter);
12650        }
12651
12652        @Override
12653        protected void dumpFilter(PrintWriter out, String prefix,
12654                PackageParser.ProviderIntentInfo filter) {
12655            out.print(prefix);
12656            out.print(
12657                    Integer.toHexString(System.identityHashCode(filter.provider)));
12658            out.print(' ');
12659            filter.provider.printComponentShortName(out);
12660            out.print(" filter ");
12661            out.println(Integer.toHexString(System.identityHashCode(filter)));
12662        }
12663
12664        @Override
12665        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12666            return filter.provider;
12667        }
12668
12669        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12670            PackageParser.Provider provider = (PackageParser.Provider)label;
12671            out.print(prefix); out.print(
12672                    Integer.toHexString(System.identityHashCode(provider)));
12673                    out.print(' ');
12674                    provider.printComponentShortName(out);
12675            if (count > 1) {
12676                out.print(" ("); out.print(count); out.print(" filters)");
12677            }
12678            out.println();
12679        }
12680
12681        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12682                = new ArrayMap<ComponentName, PackageParser.Provider>();
12683        private int mFlags;
12684    }
12685
12686    static final class EphemeralIntentResolver
12687            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12688        /**
12689         * The result that has the highest defined order. Ordering applies on a
12690         * per-package basis. Mapping is from package name to Pair of order and
12691         * EphemeralResolveInfo.
12692         * <p>
12693         * NOTE: This is implemented as a field variable for convenience and efficiency.
12694         * By having a field variable, we're able to track filter ordering as soon as
12695         * a non-zero order is defined. Otherwise, multiple loops across the result set
12696         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12697         * this needs to be contained entirely within {@link #filterResults}.
12698         */
12699        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12700
12701        @Override
12702        protected AuxiliaryResolveInfo[] newArray(int size) {
12703            return new AuxiliaryResolveInfo[size];
12704        }
12705
12706        @Override
12707        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12708            return true;
12709        }
12710
12711        @Override
12712        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12713                int userId) {
12714            if (!sUserManager.exists(userId)) {
12715                return null;
12716            }
12717            final String packageName = responseObj.resolveInfo.getPackageName();
12718            final Integer order = responseObj.getOrder();
12719            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12720                    mOrderResult.get(packageName);
12721            // ordering is enabled and this item's order isn't high enough
12722            if (lastOrderResult != null && lastOrderResult.first >= order) {
12723                return null;
12724            }
12725            final InstantAppResolveInfo res = responseObj.resolveInfo;
12726            if (order > 0) {
12727                // non-zero order, enable ordering
12728                mOrderResult.put(packageName, new Pair<>(order, res));
12729            }
12730            return responseObj;
12731        }
12732
12733        @Override
12734        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12735            // only do work if ordering is enabled [most of the time it won't be]
12736            if (mOrderResult.size() == 0) {
12737                return;
12738            }
12739            int resultSize = results.size();
12740            for (int i = 0; i < resultSize; i++) {
12741                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12742                final String packageName = info.getPackageName();
12743                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12744                if (savedInfo == null) {
12745                    // package doesn't having ordering
12746                    continue;
12747                }
12748                if (savedInfo.second == info) {
12749                    // circled back to the highest ordered item; remove from order list
12750                    mOrderResult.remove(savedInfo);
12751                    if (mOrderResult.size() == 0) {
12752                        // no more ordered items
12753                        break;
12754                    }
12755                    continue;
12756                }
12757                // item has a worse order, remove it from the result list
12758                results.remove(i);
12759                resultSize--;
12760                i--;
12761            }
12762        }
12763    }
12764
12765    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12766            new Comparator<ResolveInfo>() {
12767        public int compare(ResolveInfo r1, ResolveInfo r2) {
12768            int v1 = r1.priority;
12769            int v2 = r2.priority;
12770            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12771            if (v1 != v2) {
12772                return (v1 > v2) ? -1 : 1;
12773            }
12774            v1 = r1.preferredOrder;
12775            v2 = r2.preferredOrder;
12776            if (v1 != v2) {
12777                return (v1 > v2) ? -1 : 1;
12778            }
12779            if (r1.isDefault != r2.isDefault) {
12780                return r1.isDefault ? -1 : 1;
12781            }
12782            v1 = r1.match;
12783            v2 = r2.match;
12784            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12785            if (v1 != v2) {
12786                return (v1 > v2) ? -1 : 1;
12787            }
12788            if (r1.system != r2.system) {
12789                return r1.system ? -1 : 1;
12790            }
12791            if (r1.activityInfo != null) {
12792                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12793            }
12794            if (r1.serviceInfo != null) {
12795                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12796            }
12797            if (r1.providerInfo != null) {
12798                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12799            }
12800            return 0;
12801        }
12802    };
12803
12804    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12805            new Comparator<ProviderInfo>() {
12806        public int compare(ProviderInfo p1, ProviderInfo p2) {
12807            final int v1 = p1.initOrder;
12808            final int v2 = p2.initOrder;
12809            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12810        }
12811    };
12812
12813    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12814            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12815            final int[] userIds) {
12816        mHandler.post(new Runnable() {
12817            @Override
12818            public void run() {
12819                try {
12820                    final IActivityManager am = ActivityManager.getService();
12821                    if (am == null) return;
12822                    final int[] resolvedUserIds;
12823                    if (userIds == null) {
12824                        resolvedUserIds = am.getRunningUserIds();
12825                    } else {
12826                        resolvedUserIds = userIds;
12827                    }
12828                    for (int id : resolvedUserIds) {
12829                        final Intent intent = new Intent(action,
12830                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12831                        if (extras != null) {
12832                            intent.putExtras(extras);
12833                        }
12834                        if (targetPkg != null) {
12835                            intent.setPackage(targetPkg);
12836                        }
12837                        // Modify the UID when posting to other users
12838                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12839                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12840                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12841                            intent.putExtra(Intent.EXTRA_UID, uid);
12842                        }
12843                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12844                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12845                        if (DEBUG_BROADCASTS) {
12846                            RuntimeException here = new RuntimeException("here");
12847                            here.fillInStackTrace();
12848                            Slog.d(TAG, "Sending to user " + id + ": "
12849                                    + intent.toShortString(false, true, false, false)
12850                                    + " " + intent.getExtras(), here);
12851                        }
12852                        am.broadcastIntent(null, intent, null, finishedReceiver,
12853                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12854                                null, finishedReceiver != null, false, id);
12855                    }
12856                } catch (RemoteException ex) {
12857                }
12858            }
12859        });
12860    }
12861
12862    /**
12863     * Check if the external storage media is available. This is true if there
12864     * is a mounted external storage medium or if the external storage is
12865     * emulated.
12866     */
12867    private boolean isExternalMediaAvailable() {
12868        return mMediaMounted || Environment.isExternalStorageEmulated();
12869    }
12870
12871    @Override
12872    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12873        // writer
12874        synchronized (mPackages) {
12875            if (!isExternalMediaAvailable()) {
12876                // If the external storage is no longer mounted at this point,
12877                // the caller may not have been able to delete all of this
12878                // packages files and can not delete any more.  Bail.
12879                return null;
12880            }
12881            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12882            if (lastPackage != null) {
12883                pkgs.remove(lastPackage);
12884            }
12885            if (pkgs.size() > 0) {
12886                return pkgs.get(0);
12887            }
12888        }
12889        return null;
12890    }
12891
12892    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12893        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12894                userId, andCode ? 1 : 0, packageName);
12895        if (mSystemReady) {
12896            msg.sendToTarget();
12897        } else {
12898            if (mPostSystemReadyMessages == null) {
12899                mPostSystemReadyMessages = new ArrayList<>();
12900            }
12901            mPostSystemReadyMessages.add(msg);
12902        }
12903    }
12904
12905    void startCleaningPackages() {
12906        // reader
12907        if (!isExternalMediaAvailable()) {
12908            return;
12909        }
12910        synchronized (mPackages) {
12911            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12912                return;
12913            }
12914        }
12915        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12916        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12917        IActivityManager am = ActivityManager.getService();
12918        if (am != null) {
12919            try {
12920                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12921                        UserHandle.USER_SYSTEM);
12922            } catch (RemoteException e) {
12923            }
12924        }
12925    }
12926
12927    @Override
12928    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12929            int installFlags, String installerPackageName, int userId) {
12930        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12931
12932        final int callingUid = Binder.getCallingUid();
12933        enforceCrossUserPermission(callingUid, userId,
12934                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12935
12936        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12937            try {
12938                if (observer != null) {
12939                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12940                }
12941            } catch (RemoteException re) {
12942            }
12943            return;
12944        }
12945
12946        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12947            installFlags |= PackageManager.INSTALL_FROM_ADB;
12948
12949        } else {
12950            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12951            // about installerPackageName.
12952
12953            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12954            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12955        }
12956
12957        UserHandle user;
12958        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12959            user = UserHandle.ALL;
12960        } else {
12961            user = new UserHandle(userId);
12962        }
12963
12964        // Only system components can circumvent runtime permissions when installing.
12965        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12966                && mContext.checkCallingOrSelfPermission(Manifest.permission
12967                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12968            throw new SecurityException("You need the "
12969                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12970                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12971        }
12972
12973        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12974                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12975            throw new IllegalArgumentException(
12976                    "New installs into ASEC containers no longer supported");
12977        }
12978
12979        final File originFile = new File(originPath);
12980        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12981
12982        final Message msg = mHandler.obtainMessage(INIT_COPY);
12983        final VerificationInfo verificationInfo = new VerificationInfo(
12984                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12985        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12986                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12987                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12988                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12989        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12990        msg.obj = params;
12991
12992        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12993                System.identityHashCode(msg.obj));
12994        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12995                System.identityHashCode(msg.obj));
12996
12997        mHandler.sendMessage(msg);
12998    }
12999
13000
13001    /**
13002     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13003     * it is acting on behalf on an enterprise or the user).
13004     *
13005     * Note that the ordering of the conditionals in this method is important. The checks we perform
13006     * are as follows, in this order:
13007     *
13008     * 1) If the install is being performed by a system app, we can trust the app to have set the
13009     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13010     *    what it is.
13011     * 2) If the install is being performed by a device or profile owner app, the install reason
13012     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13013     *    set the install reason correctly. If the app targets an older SDK version where install
13014     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13015     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13016     * 3) In all other cases, the install is being performed by a regular app that is neither part
13017     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13018     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13019     *    set to enterprise policy and if so, change it to unknown instead.
13020     */
13021    private int fixUpInstallReason(String installerPackageName, int installerUid,
13022            int installReason) {
13023        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13024                == PERMISSION_GRANTED) {
13025            // If the install is being performed by a system app, we trust that app to have set the
13026            // install reason correctly.
13027            return installReason;
13028        }
13029
13030        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13031            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13032        if (dpm != null) {
13033            ComponentName owner = null;
13034            try {
13035                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13036                if (owner == null) {
13037                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13038                }
13039            } catch (RemoteException e) {
13040            }
13041            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13042                // If the install is being performed by a device or profile owner, the install
13043                // reason should be enterprise policy.
13044                return PackageManager.INSTALL_REASON_POLICY;
13045            }
13046        }
13047
13048        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13049            // If the install is being performed by a regular app (i.e. neither system app nor
13050            // device or profile owner), we have no reason to believe that the app is acting on
13051            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13052            // change it to unknown instead.
13053            return PackageManager.INSTALL_REASON_UNKNOWN;
13054        }
13055
13056        // If the install is being performed by a regular app and the install reason was set to any
13057        // value but enterprise policy, leave the install reason unchanged.
13058        return installReason;
13059    }
13060
13061    void installStage(String packageName, File stagedDir, String stagedCid,
13062            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13063            String installerPackageName, int installerUid, UserHandle user,
13064            Certificate[][] certificates) {
13065        if (DEBUG_EPHEMERAL) {
13066            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13067                Slog.d(TAG, "Ephemeral install of " + packageName);
13068            }
13069        }
13070        final VerificationInfo verificationInfo = new VerificationInfo(
13071                sessionParams.originatingUri, sessionParams.referrerUri,
13072                sessionParams.originatingUid, installerUid);
13073
13074        final OriginInfo origin;
13075        if (stagedDir != null) {
13076            origin = OriginInfo.fromStagedFile(stagedDir);
13077        } else {
13078            origin = OriginInfo.fromStagedContainer(stagedCid);
13079        }
13080
13081        final Message msg = mHandler.obtainMessage(INIT_COPY);
13082        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13083                sessionParams.installReason);
13084        final InstallParams params = new InstallParams(origin, null, observer,
13085                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13086                verificationInfo, user, sessionParams.abiOverride,
13087                sessionParams.grantedRuntimePermissions, certificates, installReason);
13088        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13089        msg.obj = params;
13090
13091        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13092                System.identityHashCode(msg.obj));
13093        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13094                System.identityHashCode(msg.obj));
13095
13096        mHandler.sendMessage(msg);
13097    }
13098
13099    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13100            int userId) {
13101        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13102        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13103    }
13104
13105    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13106            int appId, int... userIds) {
13107        if (ArrayUtils.isEmpty(userIds)) {
13108            return;
13109        }
13110        Bundle extras = new Bundle(1);
13111        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13112        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13113
13114        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13115                packageName, extras, 0, null, null, userIds);
13116        if (isSystem) {
13117            mHandler.post(() -> {
13118                        for (int userId : userIds) {
13119                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13120                        }
13121                    }
13122            );
13123        }
13124    }
13125
13126    /**
13127     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13128     * automatically without needing an explicit launch.
13129     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13130     */
13131    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13132        // If user is not running, the app didn't miss any broadcast
13133        if (!mUserManagerInternal.isUserRunning(userId)) {
13134            return;
13135        }
13136        final IActivityManager am = ActivityManager.getService();
13137        try {
13138            // Deliver LOCKED_BOOT_COMPLETED first
13139            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13140                    .setPackage(packageName);
13141            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13142            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13143                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13144
13145            // Deliver BOOT_COMPLETED only if user is unlocked
13146            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13147                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13148                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13149                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13150            }
13151        } catch (RemoteException e) {
13152            throw e.rethrowFromSystemServer();
13153        }
13154    }
13155
13156    @Override
13157    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13158            int userId) {
13159        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13160        PackageSetting pkgSetting;
13161        final int uid = Binder.getCallingUid();
13162        enforceCrossUserPermission(uid, userId,
13163                true /* requireFullPermission */, true /* checkShell */,
13164                "setApplicationHiddenSetting for user " + userId);
13165
13166        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13167            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13168            return false;
13169        }
13170
13171        long callingId = Binder.clearCallingIdentity();
13172        try {
13173            boolean sendAdded = false;
13174            boolean sendRemoved = false;
13175            // writer
13176            synchronized (mPackages) {
13177                pkgSetting = mSettings.mPackages.get(packageName);
13178                if (pkgSetting == null) {
13179                    return false;
13180                }
13181                // Do not allow "android" is being disabled
13182                if ("android".equals(packageName)) {
13183                    Slog.w(TAG, "Cannot hide package: android");
13184                    return false;
13185                }
13186                // Cannot hide static shared libs as they are considered
13187                // a part of the using app (emulating static linking). Also
13188                // static libs are installed always on internal storage.
13189                PackageParser.Package pkg = mPackages.get(packageName);
13190                if (pkg != null && pkg.staticSharedLibName != null) {
13191                    Slog.w(TAG, "Cannot hide package: " + packageName
13192                            + " providing static shared library: "
13193                            + pkg.staticSharedLibName);
13194                    return false;
13195                }
13196                // Only allow protected packages to hide themselves.
13197                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13198                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13199                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13200                    return false;
13201                }
13202
13203                if (pkgSetting.getHidden(userId) != hidden) {
13204                    pkgSetting.setHidden(hidden, userId);
13205                    mSettings.writePackageRestrictionsLPr(userId);
13206                    if (hidden) {
13207                        sendRemoved = true;
13208                    } else {
13209                        sendAdded = true;
13210                    }
13211                }
13212            }
13213            if (sendAdded) {
13214                sendPackageAddedForUser(packageName, pkgSetting, userId);
13215                return true;
13216            }
13217            if (sendRemoved) {
13218                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13219                        "hiding pkg");
13220                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13221                return true;
13222            }
13223        } finally {
13224            Binder.restoreCallingIdentity(callingId);
13225        }
13226        return false;
13227    }
13228
13229    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13230            int userId) {
13231        final PackageRemovedInfo info = new PackageRemovedInfo();
13232        info.removedPackage = packageName;
13233        info.removedUsers = new int[] {userId};
13234        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13235        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13236    }
13237
13238    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13239        if (pkgList.length > 0) {
13240            Bundle extras = new Bundle(1);
13241            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13242
13243            sendPackageBroadcast(
13244                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13245                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13246                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13247                    new int[] {userId});
13248        }
13249    }
13250
13251    /**
13252     * Returns true if application is not found or there was an error. Otherwise it returns
13253     * the hidden state of the package for the given user.
13254     */
13255    @Override
13256    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13257        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13258        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13259                true /* requireFullPermission */, false /* checkShell */,
13260                "getApplicationHidden for user " + userId);
13261        PackageSetting pkgSetting;
13262        long callingId = Binder.clearCallingIdentity();
13263        try {
13264            // writer
13265            synchronized (mPackages) {
13266                pkgSetting = mSettings.mPackages.get(packageName);
13267                if (pkgSetting == null) {
13268                    return true;
13269                }
13270                return pkgSetting.getHidden(userId);
13271            }
13272        } finally {
13273            Binder.restoreCallingIdentity(callingId);
13274        }
13275    }
13276
13277    /**
13278     * @hide
13279     */
13280    @Override
13281    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13282            int installReason) {
13283        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13284                null);
13285        PackageSetting pkgSetting;
13286        final int uid = Binder.getCallingUid();
13287        enforceCrossUserPermission(uid, userId,
13288                true /* requireFullPermission */, true /* checkShell */,
13289                "installExistingPackage for user " + userId);
13290        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13291            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13292        }
13293
13294        long callingId = Binder.clearCallingIdentity();
13295        try {
13296            boolean installed = false;
13297            final boolean instantApp =
13298                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13299            final boolean fullApp =
13300                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13301
13302            // writer
13303            synchronized (mPackages) {
13304                pkgSetting = mSettings.mPackages.get(packageName);
13305                if (pkgSetting == null) {
13306                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13307                }
13308                if (!pkgSetting.getInstalled(userId)) {
13309                    pkgSetting.setInstalled(true, userId);
13310                    pkgSetting.setHidden(false, userId);
13311                    pkgSetting.setInstallReason(installReason, userId);
13312                    mSettings.writePackageRestrictionsLPr(userId);
13313                    mSettings.writeKernelMappingLPr(pkgSetting);
13314                    installed = true;
13315                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13316                    // upgrade app from instant to full; we don't allow app downgrade
13317                    installed = true;
13318                }
13319                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13320            }
13321
13322            if (installed) {
13323                if (pkgSetting.pkg != null) {
13324                    synchronized (mInstallLock) {
13325                        // We don't need to freeze for a brand new install
13326                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13327                    }
13328                }
13329                sendPackageAddedForUser(packageName, pkgSetting, userId);
13330                synchronized (mPackages) {
13331                    updateSequenceNumberLP(packageName, new int[]{ userId });
13332                }
13333            }
13334        } finally {
13335            Binder.restoreCallingIdentity(callingId);
13336        }
13337
13338        return PackageManager.INSTALL_SUCCEEDED;
13339    }
13340
13341    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13342            boolean instantApp, boolean fullApp) {
13343        // no state specified; do nothing
13344        if (!instantApp && !fullApp) {
13345            return;
13346        }
13347        if (userId != UserHandle.USER_ALL) {
13348            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13349                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13350            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13351                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13352            }
13353        } else {
13354            for (int currentUserId : sUserManager.getUserIds()) {
13355                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13356                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13357                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13358                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13359                }
13360            }
13361        }
13362    }
13363
13364    boolean isUserRestricted(int userId, String restrictionKey) {
13365        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13366        if (restrictions.getBoolean(restrictionKey, false)) {
13367            Log.w(TAG, "User is restricted: " + restrictionKey);
13368            return true;
13369        }
13370        return false;
13371    }
13372
13373    @Override
13374    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13375            int userId) {
13376        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13377        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13378                true /* requireFullPermission */, true /* checkShell */,
13379                "setPackagesSuspended for user " + userId);
13380
13381        if (ArrayUtils.isEmpty(packageNames)) {
13382            return packageNames;
13383        }
13384
13385        // List of package names for whom the suspended state has changed.
13386        List<String> changedPackages = new ArrayList<>(packageNames.length);
13387        // List of package names for whom the suspended state is not set as requested in this
13388        // method.
13389        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13390        long callingId = Binder.clearCallingIdentity();
13391        try {
13392            for (int i = 0; i < packageNames.length; i++) {
13393                String packageName = packageNames[i];
13394                boolean changed = false;
13395                final int appId;
13396                synchronized (mPackages) {
13397                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13398                    if (pkgSetting == null) {
13399                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13400                                + "\". Skipping suspending/un-suspending.");
13401                        unactionedPackages.add(packageName);
13402                        continue;
13403                    }
13404                    appId = pkgSetting.appId;
13405                    if (pkgSetting.getSuspended(userId) != suspended) {
13406                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13407                            unactionedPackages.add(packageName);
13408                            continue;
13409                        }
13410                        pkgSetting.setSuspended(suspended, userId);
13411                        mSettings.writePackageRestrictionsLPr(userId);
13412                        changed = true;
13413                        changedPackages.add(packageName);
13414                    }
13415                }
13416
13417                if (changed && suspended) {
13418                    killApplication(packageName, UserHandle.getUid(userId, appId),
13419                            "suspending package");
13420                }
13421            }
13422        } finally {
13423            Binder.restoreCallingIdentity(callingId);
13424        }
13425
13426        if (!changedPackages.isEmpty()) {
13427            sendPackagesSuspendedForUser(changedPackages.toArray(
13428                    new String[changedPackages.size()]), userId, suspended);
13429        }
13430
13431        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13432    }
13433
13434    @Override
13435    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13436        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13437                true /* requireFullPermission */, false /* checkShell */,
13438                "isPackageSuspendedForUser for user " + userId);
13439        synchronized (mPackages) {
13440            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13441            if (pkgSetting == null) {
13442                throw new IllegalArgumentException("Unknown target package: " + packageName);
13443            }
13444            return pkgSetting.getSuspended(userId);
13445        }
13446    }
13447
13448    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13449        if (isPackageDeviceAdmin(packageName, userId)) {
13450            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13451                    + "\": has an active device admin");
13452            return false;
13453        }
13454
13455        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13456        if (packageName.equals(activeLauncherPackageName)) {
13457            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13458                    + "\": contains the active launcher");
13459            return false;
13460        }
13461
13462        if (packageName.equals(mRequiredInstallerPackage)) {
13463            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13464                    + "\": required for package installation");
13465            return false;
13466        }
13467
13468        if (packageName.equals(mRequiredUninstallerPackage)) {
13469            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13470                    + "\": required for package uninstallation");
13471            return false;
13472        }
13473
13474        if (packageName.equals(mRequiredVerifierPackage)) {
13475            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13476                    + "\": required for package verification");
13477            return false;
13478        }
13479
13480        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13481            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13482                    + "\": is the default dialer");
13483            return false;
13484        }
13485
13486        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13487            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13488                    + "\": protected package");
13489            return false;
13490        }
13491
13492        // Cannot suspend static shared libs as they are considered
13493        // a part of the using app (emulating static linking). Also
13494        // static libs are installed always on internal storage.
13495        PackageParser.Package pkg = mPackages.get(packageName);
13496        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13497            Slog.w(TAG, "Cannot suspend package: " + packageName
13498                    + " providing static shared library: "
13499                    + pkg.staticSharedLibName);
13500            return false;
13501        }
13502
13503        return true;
13504    }
13505
13506    private String getActiveLauncherPackageName(int userId) {
13507        Intent intent = new Intent(Intent.ACTION_MAIN);
13508        intent.addCategory(Intent.CATEGORY_HOME);
13509        ResolveInfo resolveInfo = resolveIntent(
13510                intent,
13511                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13512                PackageManager.MATCH_DEFAULT_ONLY,
13513                userId);
13514
13515        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13516    }
13517
13518    private String getDefaultDialerPackageName(int userId) {
13519        synchronized (mPackages) {
13520            return mSettings.getDefaultDialerPackageNameLPw(userId);
13521        }
13522    }
13523
13524    @Override
13525    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13526        mContext.enforceCallingOrSelfPermission(
13527                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13528                "Only package verification agents can verify applications");
13529
13530        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13531        final PackageVerificationResponse response = new PackageVerificationResponse(
13532                verificationCode, Binder.getCallingUid());
13533        msg.arg1 = id;
13534        msg.obj = response;
13535        mHandler.sendMessage(msg);
13536    }
13537
13538    @Override
13539    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13540            long millisecondsToDelay) {
13541        mContext.enforceCallingOrSelfPermission(
13542                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13543                "Only package verification agents can extend verification timeouts");
13544
13545        final PackageVerificationState state = mPendingVerification.get(id);
13546        final PackageVerificationResponse response = new PackageVerificationResponse(
13547                verificationCodeAtTimeout, Binder.getCallingUid());
13548
13549        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13550            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13551        }
13552        if (millisecondsToDelay < 0) {
13553            millisecondsToDelay = 0;
13554        }
13555        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13556                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13557            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13558        }
13559
13560        if ((state != null) && !state.timeoutExtended()) {
13561            state.extendTimeout();
13562
13563            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13564            msg.arg1 = id;
13565            msg.obj = response;
13566            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13567        }
13568    }
13569
13570    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13571            int verificationCode, UserHandle user) {
13572        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13573        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13574        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13575        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13576        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13577
13578        mContext.sendBroadcastAsUser(intent, user,
13579                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13580    }
13581
13582    private ComponentName matchComponentForVerifier(String packageName,
13583            List<ResolveInfo> receivers) {
13584        ActivityInfo targetReceiver = null;
13585
13586        final int NR = receivers.size();
13587        for (int i = 0; i < NR; i++) {
13588            final ResolveInfo info = receivers.get(i);
13589            if (info.activityInfo == null) {
13590                continue;
13591            }
13592
13593            if (packageName.equals(info.activityInfo.packageName)) {
13594                targetReceiver = info.activityInfo;
13595                break;
13596            }
13597        }
13598
13599        if (targetReceiver == null) {
13600            return null;
13601        }
13602
13603        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13604    }
13605
13606    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13607            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13608        if (pkgInfo.verifiers.length == 0) {
13609            return null;
13610        }
13611
13612        final int N = pkgInfo.verifiers.length;
13613        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13614        for (int i = 0; i < N; i++) {
13615            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13616
13617            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13618                    receivers);
13619            if (comp == null) {
13620                continue;
13621            }
13622
13623            final int verifierUid = getUidForVerifier(verifierInfo);
13624            if (verifierUid == -1) {
13625                continue;
13626            }
13627
13628            if (DEBUG_VERIFY) {
13629                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13630                        + " with the correct signature");
13631            }
13632            sufficientVerifiers.add(comp);
13633            verificationState.addSufficientVerifier(verifierUid);
13634        }
13635
13636        return sufficientVerifiers;
13637    }
13638
13639    private int getUidForVerifier(VerifierInfo verifierInfo) {
13640        synchronized (mPackages) {
13641            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13642            if (pkg == null) {
13643                return -1;
13644            } else if (pkg.mSignatures.length != 1) {
13645                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13646                        + " has more than one signature; ignoring");
13647                return -1;
13648            }
13649
13650            /*
13651             * If the public key of the package's signature does not match
13652             * our expected public key, then this is a different package and
13653             * we should skip.
13654             */
13655
13656            final byte[] expectedPublicKey;
13657            try {
13658                final Signature verifierSig = pkg.mSignatures[0];
13659                final PublicKey publicKey = verifierSig.getPublicKey();
13660                expectedPublicKey = publicKey.getEncoded();
13661            } catch (CertificateException e) {
13662                return -1;
13663            }
13664
13665            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13666
13667            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13668                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13669                        + " does not have the expected public key; ignoring");
13670                return -1;
13671            }
13672
13673            return pkg.applicationInfo.uid;
13674        }
13675    }
13676
13677    @Override
13678    public void finishPackageInstall(int token, boolean didLaunch) {
13679        enforceSystemOrRoot("Only the system is allowed to finish installs");
13680
13681        if (DEBUG_INSTALL) {
13682            Slog.v(TAG, "BM finishing package install for " + token);
13683        }
13684        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13685
13686        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13687        mHandler.sendMessage(msg);
13688    }
13689
13690    /**
13691     * Get the verification agent timeout.
13692     *
13693     * @return verification timeout in milliseconds
13694     */
13695    private long getVerificationTimeout() {
13696        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13697                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13698                DEFAULT_VERIFICATION_TIMEOUT);
13699    }
13700
13701    /**
13702     * Get the default verification agent response code.
13703     *
13704     * @return default verification response code
13705     */
13706    private int getDefaultVerificationResponse() {
13707        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13708                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13709                DEFAULT_VERIFICATION_RESPONSE);
13710    }
13711
13712    /**
13713     * Check whether or not package verification has been enabled.
13714     *
13715     * @return true if verification should be performed
13716     */
13717    private boolean isVerificationEnabled(int userId, int installFlags) {
13718        if (!DEFAULT_VERIFY_ENABLE) {
13719            return false;
13720        }
13721
13722        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13723
13724        // Check if installing from ADB
13725        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13726            // Do not run verification in a test harness environment
13727            if (ActivityManager.isRunningInTestHarness()) {
13728                return false;
13729            }
13730            if (ensureVerifyAppsEnabled) {
13731                return true;
13732            }
13733            // Check if the developer does not want package verification for ADB installs
13734            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13735                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13736                return false;
13737            }
13738        }
13739
13740        if (ensureVerifyAppsEnabled) {
13741            return true;
13742        }
13743
13744        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13745                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13746    }
13747
13748    @Override
13749    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13750            throws RemoteException {
13751        mContext.enforceCallingOrSelfPermission(
13752                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13753                "Only intentfilter verification agents can verify applications");
13754
13755        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13756        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13757                Binder.getCallingUid(), verificationCode, failedDomains);
13758        msg.arg1 = id;
13759        msg.obj = response;
13760        mHandler.sendMessage(msg);
13761    }
13762
13763    @Override
13764    public int getIntentVerificationStatus(String packageName, int userId) {
13765        synchronized (mPackages) {
13766            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13767        }
13768    }
13769
13770    @Override
13771    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13772        mContext.enforceCallingOrSelfPermission(
13773                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13774
13775        boolean result = false;
13776        synchronized (mPackages) {
13777            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13778        }
13779        if (result) {
13780            scheduleWritePackageRestrictionsLocked(userId);
13781        }
13782        return result;
13783    }
13784
13785    @Override
13786    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13787            String packageName) {
13788        synchronized (mPackages) {
13789            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13790        }
13791    }
13792
13793    @Override
13794    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13795        if (TextUtils.isEmpty(packageName)) {
13796            return ParceledListSlice.emptyList();
13797        }
13798        synchronized (mPackages) {
13799            PackageParser.Package pkg = mPackages.get(packageName);
13800            if (pkg == null || pkg.activities == null) {
13801                return ParceledListSlice.emptyList();
13802            }
13803            final int count = pkg.activities.size();
13804            ArrayList<IntentFilter> result = new ArrayList<>();
13805            for (int n=0; n<count; n++) {
13806                PackageParser.Activity activity = pkg.activities.get(n);
13807                if (activity.intents != null && activity.intents.size() > 0) {
13808                    result.addAll(activity.intents);
13809                }
13810            }
13811            return new ParceledListSlice<>(result);
13812        }
13813    }
13814
13815    @Override
13816    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13817        mContext.enforceCallingOrSelfPermission(
13818                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13819
13820        synchronized (mPackages) {
13821            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13822            if (packageName != null) {
13823                result |= updateIntentVerificationStatus(packageName,
13824                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13825                        userId);
13826                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13827                        packageName, userId);
13828            }
13829            return result;
13830        }
13831    }
13832
13833    @Override
13834    public String getDefaultBrowserPackageName(int userId) {
13835        synchronized (mPackages) {
13836            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13837        }
13838    }
13839
13840    /**
13841     * Get the "allow unknown sources" setting.
13842     *
13843     * @return the current "allow unknown sources" setting
13844     */
13845    private int getUnknownSourcesSettings() {
13846        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13847                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13848                -1);
13849    }
13850
13851    @Override
13852    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13853        final int uid = Binder.getCallingUid();
13854        // writer
13855        synchronized (mPackages) {
13856            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13857            if (targetPackageSetting == null) {
13858                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13859            }
13860
13861            PackageSetting installerPackageSetting;
13862            if (installerPackageName != null) {
13863                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13864                if (installerPackageSetting == null) {
13865                    throw new IllegalArgumentException("Unknown installer package: "
13866                            + installerPackageName);
13867                }
13868            } else {
13869                installerPackageSetting = null;
13870            }
13871
13872            Signature[] callerSignature;
13873            Object obj = mSettings.getUserIdLPr(uid);
13874            if (obj != null) {
13875                if (obj instanceof SharedUserSetting) {
13876                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13877                } else if (obj instanceof PackageSetting) {
13878                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13879                } else {
13880                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13881                }
13882            } else {
13883                throw new SecurityException("Unknown calling UID: " + uid);
13884            }
13885
13886            // Verify: can't set installerPackageName to a package that is
13887            // not signed with the same cert as the caller.
13888            if (installerPackageSetting != null) {
13889                if (compareSignatures(callerSignature,
13890                        installerPackageSetting.signatures.mSignatures)
13891                        != PackageManager.SIGNATURE_MATCH) {
13892                    throw new SecurityException(
13893                            "Caller does not have same cert as new installer package "
13894                            + installerPackageName);
13895                }
13896            }
13897
13898            // Verify: if target already has an installer package, it must
13899            // be signed with the same cert as the caller.
13900            if (targetPackageSetting.installerPackageName != null) {
13901                PackageSetting setting = mSettings.mPackages.get(
13902                        targetPackageSetting.installerPackageName);
13903                // If the currently set package isn't valid, then it's always
13904                // okay to change it.
13905                if (setting != null) {
13906                    if (compareSignatures(callerSignature,
13907                            setting.signatures.mSignatures)
13908                            != PackageManager.SIGNATURE_MATCH) {
13909                        throw new SecurityException(
13910                                "Caller does not have same cert as old installer package "
13911                                + targetPackageSetting.installerPackageName);
13912                    }
13913                }
13914            }
13915
13916            // Okay!
13917            targetPackageSetting.installerPackageName = installerPackageName;
13918            if (installerPackageName != null) {
13919                mSettings.mInstallerPackages.add(installerPackageName);
13920            }
13921            scheduleWriteSettingsLocked();
13922        }
13923    }
13924
13925    @Override
13926    public void setApplicationCategoryHint(String packageName, int categoryHint,
13927            String callerPackageName) {
13928        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13929                callerPackageName);
13930        synchronized (mPackages) {
13931            PackageSetting ps = mSettings.mPackages.get(packageName);
13932            if (ps == null) {
13933                throw new IllegalArgumentException("Unknown target package " + packageName);
13934            }
13935
13936            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13937                throw new IllegalArgumentException("Calling package " + callerPackageName
13938                        + " is not installer for " + packageName);
13939            }
13940
13941            if (ps.categoryHint != categoryHint) {
13942                ps.categoryHint = categoryHint;
13943                scheduleWriteSettingsLocked();
13944            }
13945        }
13946    }
13947
13948    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13949        // Queue up an async operation since the package installation may take a little while.
13950        mHandler.post(new Runnable() {
13951            public void run() {
13952                mHandler.removeCallbacks(this);
13953                 // Result object to be returned
13954                PackageInstalledInfo res = new PackageInstalledInfo();
13955                res.setReturnCode(currentStatus);
13956                res.uid = -1;
13957                res.pkg = null;
13958                res.removedInfo = null;
13959                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13960                    args.doPreInstall(res.returnCode);
13961                    synchronized (mInstallLock) {
13962                        installPackageTracedLI(args, res);
13963                    }
13964                    args.doPostInstall(res.returnCode, res.uid);
13965                }
13966
13967                // A restore should be performed at this point if (a) the install
13968                // succeeded, (b) the operation is not an update, and (c) the new
13969                // package has not opted out of backup participation.
13970                final boolean update = res.removedInfo != null
13971                        && res.removedInfo.removedPackage != null;
13972                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13973                boolean doRestore = !update
13974                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13975
13976                // Set up the post-install work request bookkeeping.  This will be used
13977                // and cleaned up by the post-install event handling regardless of whether
13978                // there's a restore pass performed.  Token values are >= 1.
13979                int token;
13980                if (mNextInstallToken < 0) mNextInstallToken = 1;
13981                token = mNextInstallToken++;
13982
13983                PostInstallData data = new PostInstallData(args, res);
13984                mRunningInstalls.put(token, data);
13985                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13986
13987                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13988                    // Pass responsibility to the Backup Manager.  It will perform a
13989                    // restore if appropriate, then pass responsibility back to the
13990                    // Package Manager to run the post-install observer callbacks
13991                    // and broadcasts.
13992                    IBackupManager bm = IBackupManager.Stub.asInterface(
13993                            ServiceManager.getService(Context.BACKUP_SERVICE));
13994                    if (bm != null) {
13995                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13996                                + " to BM for possible restore");
13997                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13998                        try {
13999                            // TODO: http://b/22388012
14000                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14001                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14002                            } else {
14003                                doRestore = false;
14004                            }
14005                        } catch (RemoteException e) {
14006                            // can't happen; the backup manager is local
14007                        } catch (Exception e) {
14008                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14009                            doRestore = false;
14010                        }
14011                    } else {
14012                        Slog.e(TAG, "Backup Manager not found!");
14013                        doRestore = false;
14014                    }
14015                }
14016
14017                if (!doRestore) {
14018                    // No restore possible, or the Backup Manager was mysteriously not
14019                    // available -- just fire the post-install work request directly.
14020                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14021
14022                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14023
14024                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14025                    mHandler.sendMessage(msg);
14026                }
14027            }
14028        });
14029    }
14030
14031    /**
14032     * Callback from PackageSettings whenever an app is first transitioned out of the
14033     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14034     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14035     * here whether the app is the target of an ongoing install, and only send the
14036     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14037     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14038     * handling.
14039     */
14040    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14041        // Serialize this with the rest of the install-process message chain.  In the
14042        // restore-at-install case, this Runnable will necessarily run before the
14043        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14044        // are coherent.  In the non-restore case, the app has already completed install
14045        // and been launched through some other means, so it is not in a problematic
14046        // state for observers to see the FIRST_LAUNCH signal.
14047        mHandler.post(new Runnable() {
14048            @Override
14049            public void run() {
14050                for (int i = 0; i < mRunningInstalls.size(); i++) {
14051                    final PostInstallData data = mRunningInstalls.valueAt(i);
14052                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14053                        continue;
14054                    }
14055                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14056                        // right package; but is it for the right user?
14057                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14058                            if (userId == data.res.newUsers[uIndex]) {
14059                                if (DEBUG_BACKUP) {
14060                                    Slog.i(TAG, "Package " + pkgName
14061                                            + " being restored so deferring FIRST_LAUNCH");
14062                                }
14063                                return;
14064                            }
14065                        }
14066                    }
14067                }
14068                // didn't find it, so not being restored
14069                if (DEBUG_BACKUP) {
14070                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14071                }
14072                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14073            }
14074        });
14075    }
14076
14077    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14078        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14079                installerPkg, null, userIds);
14080    }
14081
14082    private abstract class HandlerParams {
14083        private static final int MAX_RETRIES = 4;
14084
14085        /**
14086         * Number of times startCopy() has been attempted and had a non-fatal
14087         * error.
14088         */
14089        private int mRetries = 0;
14090
14091        /** User handle for the user requesting the information or installation. */
14092        private final UserHandle mUser;
14093        String traceMethod;
14094        int traceCookie;
14095
14096        HandlerParams(UserHandle user) {
14097            mUser = user;
14098        }
14099
14100        UserHandle getUser() {
14101            return mUser;
14102        }
14103
14104        HandlerParams setTraceMethod(String traceMethod) {
14105            this.traceMethod = traceMethod;
14106            return this;
14107        }
14108
14109        HandlerParams setTraceCookie(int traceCookie) {
14110            this.traceCookie = traceCookie;
14111            return this;
14112        }
14113
14114        final boolean startCopy() {
14115            boolean res;
14116            try {
14117                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14118
14119                if (++mRetries > MAX_RETRIES) {
14120                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14121                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14122                    handleServiceError();
14123                    return false;
14124                } else {
14125                    handleStartCopy();
14126                    res = true;
14127                }
14128            } catch (RemoteException e) {
14129                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14130                mHandler.sendEmptyMessage(MCS_RECONNECT);
14131                res = false;
14132            }
14133            handleReturnCode();
14134            return res;
14135        }
14136
14137        final void serviceError() {
14138            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14139            handleServiceError();
14140            handleReturnCode();
14141        }
14142
14143        abstract void handleStartCopy() throws RemoteException;
14144        abstract void handleServiceError();
14145        abstract void handleReturnCode();
14146    }
14147
14148    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14149        for (File path : paths) {
14150            try {
14151                mcs.clearDirectory(path.getAbsolutePath());
14152            } catch (RemoteException e) {
14153            }
14154        }
14155    }
14156
14157    static class OriginInfo {
14158        /**
14159         * Location where install is coming from, before it has been
14160         * copied/renamed into place. This could be a single monolithic APK
14161         * file, or a cluster directory. This location may be untrusted.
14162         */
14163        final File file;
14164        final String cid;
14165
14166        /**
14167         * Flag indicating that {@link #file} or {@link #cid} has already been
14168         * staged, meaning downstream users don't need to defensively copy the
14169         * contents.
14170         */
14171        final boolean staged;
14172
14173        /**
14174         * Flag indicating that {@link #file} or {@link #cid} is an already
14175         * installed app that is being moved.
14176         */
14177        final boolean existing;
14178
14179        final String resolvedPath;
14180        final File resolvedFile;
14181
14182        static OriginInfo fromNothing() {
14183            return new OriginInfo(null, null, false, false);
14184        }
14185
14186        static OriginInfo fromUntrustedFile(File file) {
14187            return new OriginInfo(file, null, false, false);
14188        }
14189
14190        static OriginInfo fromExistingFile(File file) {
14191            return new OriginInfo(file, null, false, true);
14192        }
14193
14194        static OriginInfo fromStagedFile(File file) {
14195            return new OriginInfo(file, null, true, false);
14196        }
14197
14198        static OriginInfo fromStagedContainer(String cid) {
14199            return new OriginInfo(null, cid, true, false);
14200        }
14201
14202        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14203            this.file = file;
14204            this.cid = cid;
14205            this.staged = staged;
14206            this.existing = existing;
14207
14208            if (cid != null) {
14209                resolvedPath = PackageHelper.getSdDir(cid);
14210                resolvedFile = new File(resolvedPath);
14211            } else if (file != null) {
14212                resolvedPath = file.getAbsolutePath();
14213                resolvedFile = file;
14214            } else {
14215                resolvedPath = null;
14216                resolvedFile = null;
14217            }
14218        }
14219    }
14220
14221    static class MoveInfo {
14222        final int moveId;
14223        final String fromUuid;
14224        final String toUuid;
14225        final String packageName;
14226        final String dataAppName;
14227        final int appId;
14228        final String seinfo;
14229        final int targetSdkVersion;
14230
14231        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14232                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14233            this.moveId = moveId;
14234            this.fromUuid = fromUuid;
14235            this.toUuid = toUuid;
14236            this.packageName = packageName;
14237            this.dataAppName = dataAppName;
14238            this.appId = appId;
14239            this.seinfo = seinfo;
14240            this.targetSdkVersion = targetSdkVersion;
14241        }
14242    }
14243
14244    static class VerificationInfo {
14245        /** A constant used to indicate that a uid value is not present. */
14246        public static final int NO_UID = -1;
14247
14248        /** URI referencing where the package was downloaded from. */
14249        final Uri originatingUri;
14250
14251        /** HTTP referrer URI associated with the originatingURI. */
14252        final Uri referrer;
14253
14254        /** UID of the application that the install request originated from. */
14255        final int originatingUid;
14256
14257        /** UID of application requesting the install */
14258        final int installerUid;
14259
14260        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14261            this.originatingUri = originatingUri;
14262            this.referrer = referrer;
14263            this.originatingUid = originatingUid;
14264            this.installerUid = installerUid;
14265        }
14266    }
14267
14268    class InstallParams extends HandlerParams {
14269        final OriginInfo origin;
14270        final MoveInfo move;
14271        final IPackageInstallObserver2 observer;
14272        int installFlags;
14273        final String installerPackageName;
14274        final String volumeUuid;
14275        private InstallArgs mArgs;
14276        private int mRet;
14277        final String packageAbiOverride;
14278        final String[] grantedRuntimePermissions;
14279        final VerificationInfo verificationInfo;
14280        final Certificate[][] certificates;
14281        final int installReason;
14282
14283        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14284                int installFlags, String installerPackageName, String volumeUuid,
14285                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14286                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14287            super(user);
14288            this.origin = origin;
14289            this.move = move;
14290            this.observer = observer;
14291            this.installFlags = installFlags;
14292            this.installerPackageName = installerPackageName;
14293            this.volumeUuid = volumeUuid;
14294            this.verificationInfo = verificationInfo;
14295            this.packageAbiOverride = packageAbiOverride;
14296            this.grantedRuntimePermissions = grantedPermissions;
14297            this.certificates = certificates;
14298            this.installReason = installReason;
14299        }
14300
14301        @Override
14302        public String toString() {
14303            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14304                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14305        }
14306
14307        private int installLocationPolicy(PackageInfoLite pkgLite) {
14308            String packageName = pkgLite.packageName;
14309            int installLocation = pkgLite.installLocation;
14310            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14311            // reader
14312            synchronized (mPackages) {
14313                // Currently installed package which the new package is attempting to replace or
14314                // null if no such package is installed.
14315                PackageParser.Package installedPkg = mPackages.get(packageName);
14316                // Package which currently owns the data which the new package will own if installed.
14317                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14318                // will be null whereas dataOwnerPkg will contain information about the package
14319                // which was uninstalled while keeping its data.
14320                PackageParser.Package dataOwnerPkg = installedPkg;
14321                if (dataOwnerPkg  == null) {
14322                    PackageSetting ps = mSettings.mPackages.get(packageName);
14323                    if (ps != null) {
14324                        dataOwnerPkg = ps.pkg;
14325                    }
14326                }
14327
14328                if (dataOwnerPkg != null) {
14329                    // If installed, the package will get access to data left on the device by its
14330                    // predecessor. As a security measure, this is permited only if this is not a
14331                    // version downgrade or if the predecessor package is marked as debuggable and
14332                    // a downgrade is explicitly requested.
14333                    //
14334                    // On debuggable platform builds, downgrades are permitted even for
14335                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14336                    // not offer security guarantees and thus it's OK to disable some security
14337                    // mechanisms to make debugging/testing easier on those builds. However, even on
14338                    // debuggable builds downgrades of packages are permitted only if requested via
14339                    // installFlags. This is because we aim to keep the behavior of debuggable
14340                    // platform builds as close as possible to the behavior of non-debuggable
14341                    // platform builds.
14342                    final boolean downgradeRequested =
14343                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14344                    final boolean packageDebuggable =
14345                                (dataOwnerPkg.applicationInfo.flags
14346                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14347                    final boolean downgradePermitted =
14348                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14349                    if (!downgradePermitted) {
14350                        try {
14351                            checkDowngrade(dataOwnerPkg, pkgLite);
14352                        } catch (PackageManagerException e) {
14353                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14354                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14355                        }
14356                    }
14357                }
14358
14359                if (installedPkg != null) {
14360                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14361                        // Check for updated system application.
14362                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14363                            if (onSd) {
14364                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14365                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14366                            }
14367                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14368                        } else {
14369                            if (onSd) {
14370                                // Install flag overrides everything.
14371                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14372                            }
14373                            // If current upgrade specifies particular preference
14374                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14375                                // Application explicitly specified internal.
14376                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14377                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14378                                // App explictly prefers external. Let policy decide
14379                            } else {
14380                                // Prefer previous location
14381                                if (isExternal(installedPkg)) {
14382                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14383                                }
14384                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14385                            }
14386                        }
14387                    } else {
14388                        // Invalid install. Return error code
14389                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14390                    }
14391                }
14392            }
14393            // All the special cases have been taken care of.
14394            // Return result based on recommended install location.
14395            if (onSd) {
14396                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14397            }
14398            return pkgLite.recommendedInstallLocation;
14399        }
14400
14401        /*
14402         * Invoke remote method to get package information and install
14403         * location values. Override install location based on default
14404         * policy if needed and then create install arguments based
14405         * on the install location.
14406         */
14407        public void handleStartCopy() throws RemoteException {
14408            int ret = PackageManager.INSTALL_SUCCEEDED;
14409
14410            // If we're already staged, we've firmly committed to an install location
14411            if (origin.staged) {
14412                if (origin.file != null) {
14413                    installFlags |= PackageManager.INSTALL_INTERNAL;
14414                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14415                } else if (origin.cid != null) {
14416                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14417                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14418                } else {
14419                    throw new IllegalStateException("Invalid stage location");
14420                }
14421            }
14422
14423            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14424            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14425            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14426            PackageInfoLite pkgLite = null;
14427
14428            if (onInt && onSd) {
14429                // Check if both bits are set.
14430                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14431                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14432            } else if (onSd && ephemeral) {
14433                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14434                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14435            } else {
14436                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14437                        packageAbiOverride);
14438
14439                if (DEBUG_EPHEMERAL && ephemeral) {
14440                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14441                }
14442
14443                /*
14444                 * If we have too little free space, try to free cache
14445                 * before giving up.
14446                 */
14447                if (!origin.staged && pkgLite.recommendedInstallLocation
14448                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14449                    // TODO: focus freeing disk space on the target device
14450                    final StorageManager storage = StorageManager.from(mContext);
14451                    final long lowThreshold = storage.getStorageLowBytes(
14452                            Environment.getDataDirectory());
14453
14454                    final long sizeBytes = mContainerService.calculateInstalledSize(
14455                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14456
14457                    try {
14458                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14459                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14460                                installFlags, packageAbiOverride);
14461                    } catch (InstallerException e) {
14462                        Slog.w(TAG, "Failed to free cache", e);
14463                    }
14464
14465                    /*
14466                     * The cache free must have deleted the file we
14467                     * downloaded to install.
14468                     *
14469                     * TODO: fix the "freeCache" call to not delete
14470                     *       the file we care about.
14471                     */
14472                    if (pkgLite.recommendedInstallLocation
14473                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14474                        pkgLite.recommendedInstallLocation
14475                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14476                    }
14477                }
14478            }
14479
14480            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14481                int loc = pkgLite.recommendedInstallLocation;
14482                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14483                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14484                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14485                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14486                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14487                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14488                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14489                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14490                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14491                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14492                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14493                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14494                } else {
14495                    // Override with defaults if needed.
14496                    loc = installLocationPolicy(pkgLite);
14497                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14498                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14499                    } else if (!onSd && !onInt) {
14500                        // Override install location with flags
14501                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14502                            // Set the flag to install on external media.
14503                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14504                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14505                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14506                            if (DEBUG_EPHEMERAL) {
14507                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14508                            }
14509                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14510                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14511                                    |PackageManager.INSTALL_INTERNAL);
14512                        } else {
14513                            // Make sure the flag for installing on external
14514                            // media is unset
14515                            installFlags |= PackageManager.INSTALL_INTERNAL;
14516                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14517                        }
14518                    }
14519                }
14520            }
14521
14522            final InstallArgs args = createInstallArgs(this);
14523            mArgs = args;
14524
14525            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14526                // TODO: http://b/22976637
14527                // Apps installed for "all" users use the device owner to verify the app
14528                UserHandle verifierUser = getUser();
14529                if (verifierUser == UserHandle.ALL) {
14530                    verifierUser = UserHandle.SYSTEM;
14531                }
14532
14533                /*
14534                 * Determine if we have any installed package verifiers. If we
14535                 * do, then we'll defer to them to verify the packages.
14536                 */
14537                final int requiredUid = mRequiredVerifierPackage == null ? -1
14538                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14539                                verifierUser.getIdentifier());
14540                if (!origin.existing && requiredUid != -1
14541                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14542                    final Intent verification = new Intent(
14543                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14544                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14545                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14546                            PACKAGE_MIME_TYPE);
14547                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14548
14549                    // Query all live verifiers based on current user state
14550                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14551                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14552
14553                    if (DEBUG_VERIFY) {
14554                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14555                                + verification.toString() + " with " + pkgLite.verifiers.length
14556                                + " optional verifiers");
14557                    }
14558
14559                    final int verificationId = mPendingVerificationToken++;
14560
14561                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14562
14563                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14564                            installerPackageName);
14565
14566                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14567                            installFlags);
14568
14569                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14570                            pkgLite.packageName);
14571
14572                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14573                            pkgLite.versionCode);
14574
14575                    if (verificationInfo != null) {
14576                        if (verificationInfo.originatingUri != null) {
14577                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14578                                    verificationInfo.originatingUri);
14579                        }
14580                        if (verificationInfo.referrer != null) {
14581                            verification.putExtra(Intent.EXTRA_REFERRER,
14582                                    verificationInfo.referrer);
14583                        }
14584                        if (verificationInfo.originatingUid >= 0) {
14585                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14586                                    verificationInfo.originatingUid);
14587                        }
14588                        if (verificationInfo.installerUid >= 0) {
14589                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14590                                    verificationInfo.installerUid);
14591                        }
14592                    }
14593
14594                    final PackageVerificationState verificationState = new PackageVerificationState(
14595                            requiredUid, args);
14596
14597                    mPendingVerification.append(verificationId, verificationState);
14598
14599                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14600                            receivers, verificationState);
14601
14602                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14603                    final long idleDuration = getVerificationTimeout();
14604
14605                    /*
14606                     * If any sufficient verifiers were listed in the package
14607                     * manifest, attempt to ask them.
14608                     */
14609                    if (sufficientVerifiers != null) {
14610                        final int N = sufficientVerifiers.size();
14611                        if (N == 0) {
14612                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14613                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14614                        } else {
14615                            for (int i = 0; i < N; i++) {
14616                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14617                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14618                                        verifierComponent.getPackageName(), idleDuration,
14619                                        verifierUser.getIdentifier(), false, "package verifier");
14620
14621                                final Intent sufficientIntent = new Intent(verification);
14622                                sufficientIntent.setComponent(verifierComponent);
14623                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14624                            }
14625                        }
14626                    }
14627
14628                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14629                            mRequiredVerifierPackage, receivers);
14630                    if (ret == PackageManager.INSTALL_SUCCEEDED
14631                            && mRequiredVerifierPackage != null) {
14632                        Trace.asyncTraceBegin(
14633                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14634                        /*
14635                         * Send the intent to the required verification agent,
14636                         * but only start the verification timeout after the
14637                         * target BroadcastReceivers have run.
14638                         */
14639                        verification.setComponent(requiredVerifierComponent);
14640                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14641                                mRequiredVerifierPackage, idleDuration,
14642                                verifierUser.getIdentifier(), false, "package verifier");
14643                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14644                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14645                                new BroadcastReceiver() {
14646                                    @Override
14647                                    public void onReceive(Context context, Intent intent) {
14648                                        final Message msg = mHandler
14649                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14650                                        msg.arg1 = verificationId;
14651                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14652                                    }
14653                                }, null, 0, null, null);
14654
14655                        /*
14656                         * We don't want the copy to proceed until verification
14657                         * succeeds, so null out this field.
14658                         */
14659                        mArgs = null;
14660                    }
14661                } else {
14662                    /*
14663                     * No package verification is enabled, so immediately start
14664                     * the remote call to initiate copy using temporary file.
14665                     */
14666                    ret = args.copyApk(mContainerService, true);
14667                }
14668            }
14669
14670            mRet = ret;
14671        }
14672
14673        @Override
14674        void handleReturnCode() {
14675            // If mArgs is null, then MCS couldn't be reached. When it
14676            // reconnects, it will try again to install. At that point, this
14677            // will succeed.
14678            if (mArgs != null) {
14679                processPendingInstall(mArgs, mRet);
14680            }
14681        }
14682
14683        @Override
14684        void handleServiceError() {
14685            mArgs = createInstallArgs(this);
14686            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14687        }
14688
14689        public boolean isForwardLocked() {
14690            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14691        }
14692    }
14693
14694    /**
14695     * Used during creation of InstallArgs
14696     *
14697     * @param installFlags package installation flags
14698     * @return true if should be installed on external storage
14699     */
14700    private static boolean installOnExternalAsec(int installFlags) {
14701        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14702            return false;
14703        }
14704        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14705            return true;
14706        }
14707        return false;
14708    }
14709
14710    /**
14711     * Used during creation of InstallArgs
14712     *
14713     * @param installFlags package installation flags
14714     * @return true if should be installed as forward locked
14715     */
14716    private static boolean installForwardLocked(int installFlags) {
14717        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14718    }
14719
14720    private InstallArgs createInstallArgs(InstallParams params) {
14721        if (params.move != null) {
14722            return new MoveInstallArgs(params);
14723        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14724            return new AsecInstallArgs(params);
14725        } else {
14726            return new FileInstallArgs(params);
14727        }
14728    }
14729
14730    /**
14731     * Create args that describe an existing installed package. Typically used
14732     * when cleaning up old installs, or used as a move source.
14733     */
14734    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14735            String resourcePath, String[] instructionSets) {
14736        final boolean isInAsec;
14737        if (installOnExternalAsec(installFlags)) {
14738            /* Apps on SD card are always in ASEC containers. */
14739            isInAsec = true;
14740        } else if (installForwardLocked(installFlags)
14741                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14742            /*
14743             * Forward-locked apps are only in ASEC containers if they're the
14744             * new style
14745             */
14746            isInAsec = true;
14747        } else {
14748            isInAsec = false;
14749        }
14750
14751        if (isInAsec) {
14752            return new AsecInstallArgs(codePath, instructionSets,
14753                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14754        } else {
14755            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14756        }
14757    }
14758
14759    static abstract class InstallArgs {
14760        /** @see InstallParams#origin */
14761        final OriginInfo origin;
14762        /** @see InstallParams#move */
14763        final MoveInfo move;
14764
14765        final IPackageInstallObserver2 observer;
14766        // Always refers to PackageManager flags only
14767        final int installFlags;
14768        final String installerPackageName;
14769        final String volumeUuid;
14770        final UserHandle user;
14771        final String abiOverride;
14772        final String[] installGrantPermissions;
14773        /** If non-null, drop an async trace when the install completes */
14774        final String traceMethod;
14775        final int traceCookie;
14776        final Certificate[][] certificates;
14777        final int installReason;
14778
14779        // The list of instruction sets supported by this app. This is currently
14780        // only used during the rmdex() phase to clean up resources. We can get rid of this
14781        // if we move dex files under the common app path.
14782        /* nullable */ String[] instructionSets;
14783
14784        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14785                int installFlags, String installerPackageName, String volumeUuid,
14786                UserHandle user, String[] instructionSets,
14787                String abiOverride, String[] installGrantPermissions,
14788                String traceMethod, int traceCookie, Certificate[][] certificates,
14789                int installReason) {
14790            this.origin = origin;
14791            this.move = move;
14792            this.installFlags = installFlags;
14793            this.observer = observer;
14794            this.installerPackageName = installerPackageName;
14795            this.volumeUuid = volumeUuid;
14796            this.user = user;
14797            this.instructionSets = instructionSets;
14798            this.abiOverride = abiOverride;
14799            this.installGrantPermissions = installGrantPermissions;
14800            this.traceMethod = traceMethod;
14801            this.traceCookie = traceCookie;
14802            this.certificates = certificates;
14803            this.installReason = installReason;
14804        }
14805
14806        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14807        abstract int doPreInstall(int status);
14808
14809        /**
14810         * Rename package into final resting place. All paths on the given
14811         * scanned package should be updated to reflect the rename.
14812         */
14813        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14814        abstract int doPostInstall(int status, int uid);
14815
14816        /** @see PackageSettingBase#codePathString */
14817        abstract String getCodePath();
14818        /** @see PackageSettingBase#resourcePathString */
14819        abstract String getResourcePath();
14820
14821        // Need installer lock especially for dex file removal.
14822        abstract void cleanUpResourcesLI();
14823        abstract boolean doPostDeleteLI(boolean delete);
14824
14825        /**
14826         * Called before the source arguments are copied. This is used mostly
14827         * for MoveParams when it needs to read the source file to put it in the
14828         * destination.
14829         */
14830        int doPreCopy() {
14831            return PackageManager.INSTALL_SUCCEEDED;
14832        }
14833
14834        /**
14835         * Called after the source arguments are copied. This is used mostly for
14836         * MoveParams when it needs to read the source file to put it in the
14837         * destination.
14838         */
14839        int doPostCopy(int uid) {
14840            return PackageManager.INSTALL_SUCCEEDED;
14841        }
14842
14843        protected boolean isFwdLocked() {
14844            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14845        }
14846
14847        protected boolean isExternalAsec() {
14848            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14849        }
14850
14851        protected boolean isEphemeral() {
14852            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14853        }
14854
14855        UserHandle getUser() {
14856            return user;
14857        }
14858    }
14859
14860    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14861        if (!allCodePaths.isEmpty()) {
14862            if (instructionSets == null) {
14863                throw new IllegalStateException("instructionSet == null");
14864            }
14865            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14866            for (String codePath : allCodePaths) {
14867                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14868                    try {
14869                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14870                    } catch (InstallerException ignored) {
14871                    }
14872                }
14873            }
14874        }
14875    }
14876
14877    /**
14878     * Logic to handle installation of non-ASEC applications, including copying
14879     * and renaming logic.
14880     */
14881    class FileInstallArgs extends InstallArgs {
14882        private File codeFile;
14883        private File resourceFile;
14884
14885        // Example topology:
14886        // /data/app/com.example/base.apk
14887        // /data/app/com.example/split_foo.apk
14888        // /data/app/com.example/lib/arm/libfoo.so
14889        // /data/app/com.example/lib/arm64/libfoo.so
14890        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14891
14892        /** New install */
14893        FileInstallArgs(InstallParams params) {
14894            super(params.origin, params.move, params.observer, params.installFlags,
14895                    params.installerPackageName, params.volumeUuid,
14896                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14897                    params.grantedRuntimePermissions,
14898                    params.traceMethod, params.traceCookie, params.certificates,
14899                    params.installReason);
14900            if (isFwdLocked()) {
14901                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14902            }
14903        }
14904
14905        /** Existing install */
14906        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14907            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14908                    null, null, null, 0, null /*certificates*/,
14909                    PackageManager.INSTALL_REASON_UNKNOWN);
14910            this.codeFile = (codePath != null) ? new File(codePath) : null;
14911            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14912        }
14913
14914        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14915            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14916            try {
14917                return doCopyApk(imcs, temp);
14918            } finally {
14919                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14920            }
14921        }
14922
14923        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14924            if (origin.staged) {
14925                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14926                codeFile = origin.file;
14927                resourceFile = origin.file;
14928                return PackageManager.INSTALL_SUCCEEDED;
14929            }
14930
14931            try {
14932                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14933                final File tempDir =
14934                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14935                codeFile = tempDir;
14936                resourceFile = tempDir;
14937            } catch (IOException e) {
14938                Slog.w(TAG, "Failed to create copy file: " + e);
14939                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14940            }
14941
14942            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14943                @Override
14944                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14945                    if (!FileUtils.isValidExtFilename(name)) {
14946                        throw new IllegalArgumentException("Invalid filename: " + name);
14947                    }
14948                    try {
14949                        final File file = new File(codeFile, name);
14950                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14951                                O_RDWR | O_CREAT, 0644);
14952                        Os.chmod(file.getAbsolutePath(), 0644);
14953                        return new ParcelFileDescriptor(fd);
14954                    } catch (ErrnoException e) {
14955                        throw new RemoteException("Failed to open: " + e.getMessage());
14956                    }
14957                }
14958            };
14959
14960            int ret = PackageManager.INSTALL_SUCCEEDED;
14961            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14962            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14963                Slog.e(TAG, "Failed to copy package");
14964                return ret;
14965            }
14966
14967            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14968            NativeLibraryHelper.Handle handle = null;
14969            try {
14970                handle = NativeLibraryHelper.Handle.create(codeFile);
14971                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14972                        abiOverride);
14973            } catch (IOException e) {
14974                Slog.e(TAG, "Copying native libraries failed", e);
14975                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14976            } finally {
14977                IoUtils.closeQuietly(handle);
14978            }
14979
14980            return ret;
14981        }
14982
14983        int doPreInstall(int status) {
14984            if (status != PackageManager.INSTALL_SUCCEEDED) {
14985                cleanUp();
14986            }
14987            return status;
14988        }
14989
14990        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14991            if (status != PackageManager.INSTALL_SUCCEEDED) {
14992                cleanUp();
14993                return false;
14994            }
14995
14996            final File targetDir = codeFile.getParentFile();
14997            final File beforeCodeFile = codeFile;
14998            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14999
15000            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15001            try {
15002                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15003            } catch (ErrnoException e) {
15004                Slog.w(TAG, "Failed to rename", e);
15005                return false;
15006            }
15007
15008            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15009                Slog.w(TAG, "Failed to restorecon");
15010                return false;
15011            }
15012
15013            // Reflect the rename internally
15014            codeFile = afterCodeFile;
15015            resourceFile = afterCodeFile;
15016
15017            // Reflect the rename in scanned details
15018            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15019            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15020                    afterCodeFile, pkg.baseCodePath));
15021            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15022                    afterCodeFile, pkg.splitCodePaths));
15023
15024            // Reflect the rename in app info
15025            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15026            pkg.setApplicationInfoCodePath(pkg.codePath);
15027            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15028            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15029            pkg.setApplicationInfoResourcePath(pkg.codePath);
15030            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15031            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15032
15033            return true;
15034        }
15035
15036        int doPostInstall(int status, int uid) {
15037            if (status != PackageManager.INSTALL_SUCCEEDED) {
15038                cleanUp();
15039            }
15040            return status;
15041        }
15042
15043        @Override
15044        String getCodePath() {
15045            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15046        }
15047
15048        @Override
15049        String getResourcePath() {
15050            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15051        }
15052
15053        private boolean cleanUp() {
15054            if (codeFile == null || !codeFile.exists()) {
15055                return false;
15056            }
15057
15058            removeCodePathLI(codeFile);
15059
15060            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15061                resourceFile.delete();
15062            }
15063
15064            return true;
15065        }
15066
15067        void cleanUpResourcesLI() {
15068            // Try enumerating all code paths before deleting
15069            List<String> allCodePaths = Collections.EMPTY_LIST;
15070            if (codeFile != null && codeFile.exists()) {
15071                try {
15072                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15073                    allCodePaths = pkg.getAllCodePaths();
15074                } catch (PackageParserException e) {
15075                    // Ignored; we tried our best
15076                }
15077            }
15078
15079            cleanUp();
15080            removeDexFiles(allCodePaths, instructionSets);
15081        }
15082
15083        boolean doPostDeleteLI(boolean delete) {
15084            // XXX err, shouldn't we respect the delete flag?
15085            cleanUpResourcesLI();
15086            return true;
15087        }
15088    }
15089
15090    private boolean isAsecExternal(String cid) {
15091        final String asecPath = PackageHelper.getSdFilesystem(cid);
15092        return !asecPath.startsWith(mAsecInternalPath);
15093    }
15094
15095    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15096            PackageManagerException {
15097        if (copyRet < 0) {
15098            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15099                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15100                throw new PackageManagerException(copyRet, message);
15101            }
15102        }
15103    }
15104
15105    /**
15106     * Extract the StorageManagerService "container ID" from the full code path of an
15107     * .apk.
15108     */
15109    static String cidFromCodePath(String fullCodePath) {
15110        int eidx = fullCodePath.lastIndexOf("/");
15111        String subStr1 = fullCodePath.substring(0, eidx);
15112        int sidx = subStr1.lastIndexOf("/");
15113        return subStr1.substring(sidx+1, eidx);
15114    }
15115
15116    /**
15117     * Logic to handle installation of ASEC applications, including copying and
15118     * renaming logic.
15119     */
15120    class AsecInstallArgs extends InstallArgs {
15121        static final String RES_FILE_NAME = "pkg.apk";
15122        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15123
15124        String cid;
15125        String packagePath;
15126        String resourcePath;
15127
15128        /** New install */
15129        AsecInstallArgs(InstallParams params) {
15130            super(params.origin, params.move, params.observer, params.installFlags,
15131                    params.installerPackageName, params.volumeUuid,
15132                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15133                    params.grantedRuntimePermissions,
15134                    params.traceMethod, params.traceCookie, params.certificates,
15135                    params.installReason);
15136        }
15137
15138        /** Existing install */
15139        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15140                        boolean isExternal, boolean isForwardLocked) {
15141            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15142                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15143                    instructionSets, null, null, null, 0, null /*certificates*/,
15144                    PackageManager.INSTALL_REASON_UNKNOWN);
15145            // Hackily pretend we're still looking at a full code path
15146            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15147                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15148            }
15149
15150            // Extract cid from fullCodePath
15151            int eidx = fullCodePath.lastIndexOf("/");
15152            String subStr1 = fullCodePath.substring(0, eidx);
15153            int sidx = subStr1.lastIndexOf("/");
15154            cid = subStr1.substring(sidx+1, eidx);
15155            setMountPath(subStr1);
15156        }
15157
15158        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15159            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15160                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15161                    instructionSets, null, null, null, 0, null /*certificates*/,
15162                    PackageManager.INSTALL_REASON_UNKNOWN);
15163            this.cid = cid;
15164            setMountPath(PackageHelper.getSdDir(cid));
15165        }
15166
15167        void createCopyFile() {
15168            cid = mInstallerService.allocateExternalStageCidLegacy();
15169        }
15170
15171        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15172            if (origin.staged && origin.cid != null) {
15173                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15174                cid = origin.cid;
15175                setMountPath(PackageHelper.getSdDir(cid));
15176                return PackageManager.INSTALL_SUCCEEDED;
15177            }
15178
15179            if (temp) {
15180                createCopyFile();
15181            } else {
15182                /*
15183                 * Pre-emptively destroy the container since it's destroyed if
15184                 * copying fails due to it existing anyway.
15185                 */
15186                PackageHelper.destroySdDir(cid);
15187            }
15188
15189            final String newMountPath = imcs.copyPackageToContainer(
15190                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15191                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15192
15193            if (newMountPath != null) {
15194                setMountPath(newMountPath);
15195                return PackageManager.INSTALL_SUCCEEDED;
15196            } else {
15197                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15198            }
15199        }
15200
15201        @Override
15202        String getCodePath() {
15203            return packagePath;
15204        }
15205
15206        @Override
15207        String getResourcePath() {
15208            return resourcePath;
15209        }
15210
15211        int doPreInstall(int status) {
15212            if (status != PackageManager.INSTALL_SUCCEEDED) {
15213                // Destroy container
15214                PackageHelper.destroySdDir(cid);
15215            } else {
15216                boolean mounted = PackageHelper.isContainerMounted(cid);
15217                if (!mounted) {
15218                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15219                            Process.SYSTEM_UID);
15220                    if (newMountPath != null) {
15221                        setMountPath(newMountPath);
15222                    } else {
15223                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15224                    }
15225                }
15226            }
15227            return status;
15228        }
15229
15230        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15231            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15232            String newMountPath = null;
15233            if (PackageHelper.isContainerMounted(cid)) {
15234                // Unmount the container
15235                if (!PackageHelper.unMountSdDir(cid)) {
15236                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15237                    return false;
15238                }
15239            }
15240            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15241                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15242                        " which might be stale. Will try to clean up.");
15243                // Clean up the stale container and proceed to recreate.
15244                if (!PackageHelper.destroySdDir(newCacheId)) {
15245                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15246                    return false;
15247                }
15248                // Successfully cleaned up stale container. Try to rename again.
15249                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15250                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15251                            + " inspite of cleaning it up.");
15252                    return false;
15253                }
15254            }
15255            if (!PackageHelper.isContainerMounted(newCacheId)) {
15256                Slog.w(TAG, "Mounting container " + newCacheId);
15257                newMountPath = PackageHelper.mountSdDir(newCacheId,
15258                        getEncryptKey(), Process.SYSTEM_UID);
15259            } else {
15260                newMountPath = PackageHelper.getSdDir(newCacheId);
15261            }
15262            if (newMountPath == null) {
15263                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15264                return false;
15265            }
15266            Log.i(TAG, "Succesfully renamed " + cid +
15267                    " to " + newCacheId +
15268                    " at new path: " + newMountPath);
15269            cid = newCacheId;
15270
15271            final File beforeCodeFile = new File(packagePath);
15272            setMountPath(newMountPath);
15273            final File afterCodeFile = new File(packagePath);
15274
15275            // Reflect the rename in scanned details
15276            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15277            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15278                    afterCodeFile, pkg.baseCodePath));
15279            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15280                    afterCodeFile, pkg.splitCodePaths));
15281
15282            // Reflect the rename in app info
15283            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15284            pkg.setApplicationInfoCodePath(pkg.codePath);
15285            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15286            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15287            pkg.setApplicationInfoResourcePath(pkg.codePath);
15288            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15289            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15290
15291            return true;
15292        }
15293
15294        private void setMountPath(String mountPath) {
15295            final File mountFile = new File(mountPath);
15296
15297            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15298            if (monolithicFile.exists()) {
15299                packagePath = monolithicFile.getAbsolutePath();
15300                if (isFwdLocked()) {
15301                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15302                } else {
15303                    resourcePath = packagePath;
15304                }
15305            } else {
15306                packagePath = mountFile.getAbsolutePath();
15307                resourcePath = packagePath;
15308            }
15309        }
15310
15311        int doPostInstall(int status, int uid) {
15312            if (status != PackageManager.INSTALL_SUCCEEDED) {
15313                cleanUp();
15314            } else {
15315                final int groupOwner;
15316                final String protectedFile;
15317                if (isFwdLocked()) {
15318                    groupOwner = UserHandle.getSharedAppGid(uid);
15319                    protectedFile = RES_FILE_NAME;
15320                } else {
15321                    groupOwner = -1;
15322                    protectedFile = null;
15323                }
15324
15325                if (uid < Process.FIRST_APPLICATION_UID
15326                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15327                    Slog.e(TAG, "Failed to finalize " + cid);
15328                    PackageHelper.destroySdDir(cid);
15329                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15330                }
15331
15332                boolean mounted = PackageHelper.isContainerMounted(cid);
15333                if (!mounted) {
15334                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15335                }
15336            }
15337            return status;
15338        }
15339
15340        private void cleanUp() {
15341            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15342
15343            // Destroy secure container
15344            PackageHelper.destroySdDir(cid);
15345        }
15346
15347        private List<String> getAllCodePaths() {
15348            final File codeFile = new File(getCodePath());
15349            if (codeFile != null && codeFile.exists()) {
15350                try {
15351                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15352                    return pkg.getAllCodePaths();
15353                } catch (PackageParserException e) {
15354                    // Ignored; we tried our best
15355                }
15356            }
15357            return Collections.EMPTY_LIST;
15358        }
15359
15360        void cleanUpResourcesLI() {
15361            // Enumerate all code paths before deleting
15362            cleanUpResourcesLI(getAllCodePaths());
15363        }
15364
15365        private void cleanUpResourcesLI(List<String> allCodePaths) {
15366            cleanUp();
15367            removeDexFiles(allCodePaths, instructionSets);
15368        }
15369
15370        String getPackageName() {
15371            return getAsecPackageName(cid);
15372        }
15373
15374        boolean doPostDeleteLI(boolean delete) {
15375            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15376            final List<String> allCodePaths = getAllCodePaths();
15377            boolean mounted = PackageHelper.isContainerMounted(cid);
15378            if (mounted) {
15379                // Unmount first
15380                if (PackageHelper.unMountSdDir(cid)) {
15381                    mounted = false;
15382                }
15383            }
15384            if (!mounted && delete) {
15385                cleanUpResourcesLI(allCodePaths);
15386            }
15387            return !mounted;
15388        }
15389
15390        @Override
15391        int doPreCopy() {
15392            if (isFwdLocked()) {
15393                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15394                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15395                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15396                }
15397            }
15398
15399            return PackageManager.INSTALL_SUCCEEDED;
15400        }
15401
15402        @Override
15403        int doPostCopy(int uid) {
15404            if (isFwdLocked()) {
15405                if (uid < Process.FIRST_APPLICATION_UID
15406                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15407                                RES_FILE_NAME)) {
15408                    Slog.e(TAG, "Failed to finalize " + cid);
15409                    PackageHelper.destroySdDir(cid);
15410                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15411                }
15412            }
15413
15414            return PackageManager.INSTALL_SUCCEEDED;
15415        }
15416    }
15417
15418    /**
15419     * Logic to handle movement of existing installed applications.
15420     */
15421    class MoveInstallArgs extends InstallArgs {
15422        private File codeFile;
15423        private File resourceFile;
15424
15425        /** New install */
15426        MoveInstallArgs(InstallParams params) {
15427            super(params.origin, params.move, params.observer, params.installFlags,
15428                    params.installerPackageName, params.volumeUuid,
15429                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15430                    params.grantedRuntimePermissions,
15431                    params.traceMethod, params.traceCookie, params.certificates,
15432                    params.installReason);
15433        }
15434
15435        int copyApk(IMediaContainerService imcs, boolean temp) {
15436            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15437                    + move.fromUuid + " to " + move.toUuid);
15438            synchronized (mInstaller) {
15439                try {
15440                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15441                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15442                } catch (InstallerException e) {
15443                    Slog.w(TAG, "Failed to move app", e);
15444                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15445                }
15446            }
15447
15448            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15449            resourceFile = codeFile;
15450            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15451
15452            return PackageManager.INSTALL_SUCCEEDED;
15453        }
15454
15455        int doPreInstall(int status) {
15456            if (status != PackageManager.INSTALL_SUCCEEDED) {
15457                cleanUp(move.toUuid);
15458            }
15459            return status;
15460        }
15461
15462        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15463            if (status != PackageManager.INSTALL_SUCCEEDED) {
15464                cleanUp(move.toUuid);
15465                return false;
15466            }
15467
15468            // Reflect the move in app info
15469            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15470            pkg.setApplicationInfoCodePath(pkg.codePath);
15471            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15472            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15473            pkg.setApplicationInfoResourcePath(pkg.codePath);
15474            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15475            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15476
15477            return true;
15478        }
15479
15480        int doPostInstall(int status, int uid) {
15481            if (status == PackageManager.INSTALL_SUCCEEDED) {
15482                cleanUp(move.fromUuid);
15483            } else {
15484                cleanUp(move.toUuid);
15485            }
15486            return status;
15487        }
15488
15489        @Override
15490        String getCodePath() {
15491            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15492        }
15493
15494        @Override
15495        String getResourcePath() {
15496            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15497        }
15498
15499        private boolean cleanUp(String volumeUuid) {
15500            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15501                    move.dataAppName);
15502            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15503            final int[] userIds = sUserManager.getUserIds();
15504            synchronized (mInstallLock) {
15505                // Clean up both app data and code
15506                // All package moves are frozen until finished
15507                for (int userId : userIds) {
15508                    try {
15509                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15510                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15511                    } catch (InstallerException e) {
15512                        Slog.w(TAG, String.valueOf(e));
15513                    }
15514                }
15515                removeCodePathLI(codeFile);
15516            }
15517            return true;
15518        }
15519
15520        void cleanUpResourcesLI() {
15521            throw new UnsupportedOperationException();
15522        }
15523
15524        boolean doPostDeleteLI(boolean delete) {
15525            throw new UnsupportedOperationException();
15526        }
15527    }
15528
15529    static String getAsecPackageName(String packageCid) {
15530        int idx = packageCid.lastIndexOf("-");
15531        if (idx == -1) {
15532            return packageCid;
15533        }
15534        return packageCid.substring(0, idx);
15535    }
15536
15537    // Utility method used to create code paths based on package name and available index.
15538    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15539        String idxStr = "";
15540        int idx = 1;
15541        // Fall back to default value of idx=1 if prefix is not
15542        // part of oldCodePath
15543        if (oldCodePath != null) {
15544            String subStr = oldCodePath;
15545            // Drop the suffix right away
15546            if (suffix != null && subStr.endsWith(suffix)) {
15547                subStr = subStr.substring(0, subStr.length() - suffix.length());
15548            }
15549            // If oldCodePath already contains prefix find out the
15550            // ending index to either increment or decrement.
15551            int sidx = subStr.lastIndexOf(prefix);
15552            if (sidx != -1) {
15553                subStr = subStr.substring(sidx + prefix.length());
15554                if (subStr != null) {
15555                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15556                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15557                    }
15558                    try {
15559                        idx = Integer.parseInt(subStr);
15560                        if (idx <= 1) {
15561                            idx++;
15562                        } else {
15563                            idx--;
15564                        }
15565                    } catch(NumberFormatException e) {
15566                    }
15567                }
15568            }
15569        }
15570        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15571        return prefix + idxStr;
15572    }
15573
15574    private File getNextCodePath(File targetDir, String packageName) {
15575        File result;
15576        SecureRandom random = new SecureRandom();
15577        byte[] bytes = new byte[16];
15578        do {
15579            random.nextBytes(bytes);
15580            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15581            result = new File(targetDir, packageName + "-" + suffix);
15582        } while (result.exists());
15583        return result;
15584    }
15585
15586    // Utility method that returns the relative package path with respect
15587    // to the installation directory. Like say for /data/data/com.test-1.apk
15588    // string com.test-1 is returned.
15589    static String deriveCodePathName(String codePath) {
15590        if (codePath == null) {
15591            return null;
15592        }
15593        final File codeFile = new File(codePath);
15594        final String name = codeFile.getName();
15595        if (codeFile.isDirectory()) {
15596            return name;
15597        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15598            final int lastDot = name.lastIndexOf('.');
15599            return name.substring(0, lastDot);
15600        } else {
15601            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15602            return null;
15603        }
15604    }
15605
15606    static class PackageInstalledInfo {
15607        String name;
15608        int uid;
15609        // The set of users that originally had this package installed.
15610        int[] origUsers;
15611        // The set of users that now have this package installed.
15612        int[] newUsers;
15613        PackageParser.Package pkg;
15614        int returnCode;
15615        String returnMsg;
15616        PackageRemovedInfo removedInfo;
15617        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15618
15619        public void setError(int code, String msg) {
15620            setReturnCode(code);
15621            setReturnMessage(msg);
15622            Slog.w(TAG, msg);
15623        }
15624
15625        public void setError(String msg, PackageParserException e) {
15626            setReturnCode(e.error);
15627            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15628            Slog.w(TAG, msg, e);
15629        }
15630
15631        public void setError(String msg, PackageManagerException e) {
15632            returnCode = e.error;
15633            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15634            Slog.w(TAG, msg, e);
15635        }
15636
15637        public void setReturnCode(int returnCode) {
15638            this.returnCode = returnCode;
15639            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15640            for (int i = 0; i < childCount; i++) {
15641                addedChildPackages.valueAt(i).returnCode = returnCode;
15642            }
15643        }
15644
15645        private void setReturnMessage(String returnMsg) {
15646            this.returnMsg = returnMsg;
15647            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15648            for (int i = 0; i < childCount; i++) {
15649                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15650            }
15651        }
15652
15653        // In some error cases we want to convey more info back to the observer
15654        String origPackage;
15655        String origPermission;
15656    }
15657
15658    /*
15659     * Install a non-existing package.
15660     */
15661    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15662            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15663            PackageInstalledInfo res, int installReason) {
15664        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15665
15666        // Remember this for later, in case we need to rollback this install
15667        String pkgName = pkg.packageName;
15668
15669        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15670
15671        synchronized(mPackages) {
15672            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15673            if (renamedPackage != null) {
15674                // A package with the same name is already installed, though
15675                // it has been renamed to an older name.  The package we
15676                // are trying to install should be installed as an update to
15677                // the existing one, but that has not been requested, so bail.
15678                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15679                        + " without first uninstalling package running as "
15680                        + renamedPackage);
15681                return;
15682            }
15683            if (mPackages.containsKey(pkgName)) {
15684                // Don't allow installation over an existing package with the same name.
15685                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15686                        + " without first uninstalling.");
15687                return;
15688            }
15689        }
15690
15691        try {
15692            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15693                    System.currentTimeMillis(), user);
15694
15695            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15696
15697            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15698                prepareAppDataAfterInstallLIF(newPackage);
15699
15700            } else {
15701                // Remove package from internal structures, but keep around any
15702                // data that might have already existed
15703                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15704                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15705            }
15706        } catch (PackageManagerException e) {
15707            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15708        }
15709
15710        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15711    }
15712
15713    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15714        // Can't rotate keys during boot or if sharedUser.
15715        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15716                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15717            return false;
15718        }
15719        // app is using upgradeKeySets; make sure all are valid
15720        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15721        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15722        for (int i = 0; i < upgradeKeySets.length; i++) {
15723            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15724                Slog.wtf(TAG, "Package "
15725                         + (oldPs.name != null ? oldPs.name : "<null>")
15726                         + " contains upgrade-key-set reference to unknown key-set: "
15727                         + upgradeKeySets[i]
15728                         + " reverting to signatures check.");
15729                return false;
15730            }
15731        }
15732        return true;
15733    }
15734
15735    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15736        // Upgrade keysets are being used.  Determine if new package has a superset of the
15737        // required keys.
15738        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15739        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15740        for (int i = 0; i < upgradeKeySets.length; i++) {
15741            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15742            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15743                return true;
15744            }
15745        }
15746        return false;
15747    }
15748
15749    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15750        try (DigestInputStream digestStream =
15751                new DigestInputStream(new FileInputStream(file), digest)) {
15752            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15753        }
15754    }
15755
15756    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15757            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15758            int installReason) {
15759        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15760
15761        final PackageParser.Package oldPackage;
15762        final String pkgName = pkg.packageName;
15763        final int[] allUsers;
15764        final int[] installedUsers;
15765
15766        synchronized(mPackages) {
15767            oldPackage = mPackages.get(pkgName);
15768            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15769
15770            // don't allow upgrade to target a release SDK from a pre-release SDK
15771            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15772                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15773            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15774                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15775            if (oldTargetsPreRelease
15776                    && !newTargetsPreRelease
15777                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15778                Slog.w(TAG, "Can't install package targeting released sdk");
15779                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15780                return;
15781            }
15782
15783            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15784
15785            // verify signatures are valid
15786            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15787                if (!checkUpgradeKeySetLP(ps, pkg)) {
15788                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15789                            "New package not signed by keys specified by upgrade-keysets: "
15790                                    + pkgName);
15791                    return;
15792                }
15793            } else {
15794                // default to original signature matching
15795                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15796                        != PackageManager.SIGNATURE_MATCH) {
15797                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15798                            "New package has a different signature: " + pkgName);
15799                    return;
15800                }
15801            }
15802
15803            // don't allow a system upgrade unless the upgrade hash matches
15804            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15805                byte[] digestBytes = null;
15806                try {
15807                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15808                    updateDigest(digest, new File(pkg.baseCodePath));
15809                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15810                        for (String path : pkg.splitCodePaths) {
15811                            updateDigest(digest, new File(path));
15812                        }
15813                    }
15814                    digestBytes = digest.digest();
15815                } catch (NoSuchAlgorithmException | IOException e) {
15816                    res.setError(INSTALL_FAILED_INVALID_APK,
15817                            "Could not compute hash: " + pkgName);
15818                    return;
15819                }
15820                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15821                    res.setError(INSTALL_FAILED_INVALID_APK,
15822                            "New package fails restrict-update check: " + pkgName);
15823                    return;
15824                }
15825                // retain upgrade restriction
15826                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15827            }
15828
15829            // Check for shared user id changes
15830            String invalidPackageName =
15831                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15832            if (invalidPackageName != null) {
15833                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15834                        "Package " + invalidPackageName + " tried to change user "
15835                                + oldPackage.mSharedUserId);
15836                return;
15837            }
15838
15839            // In case of rollback, remember per-user/profile install state
15840            allUsers = sUserManager.getUserIds();
15841            installedUsers = ps.queryInstalledUsers(allUsers, true);
15842
15843            // don't allow an upgrade from full to ephemeral
15844            if (isInstantApp) {
15845                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15846                    for (int currentUser : allUsers) {
15847                        if (!ps.getInstantApp(currentUser)) {
15848                            // can't downgrade from full to instant
15849                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15850                                    + " for user: " + currentUser);
15851                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15852                            return;
15853                        }
15854                    }
15855                } else if (!ps.getInstantApp(user.getIdentifier())) {
15856                    // can't downgrade from full to instant
15857                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15858                            + " for user: " + user.getIdentifier());
15859                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15860                    return;
15861                }
15862            }
15863        }
15864
15865        // Update what is removed
15866        res.removedInfo = new PackageRemovedInfo();
15867        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15868        res.removedInfo.removedPackage = oldPackage.packageName;
15869        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15870        res.removedInfo.isUpdate = true;
15871        res.removedInfo.origUsers = installedUsers;
15872        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15873        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15874        for (int i = 0; i < installedUsers.length; i++) {
15875            final int userId = installedUsers[i];
15876            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15877        }
15878
15879        final int childCount = (oldPackage.childPackages != null)
15880                ? oldPackage.childPackages.size() : 0;
15881        for (int i = 0; i < childCount; i++) {
15882            boolean childPackageUpdated = false;
15883            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15884            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15885            if (res.addedChildPackages != null) {
15886                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15887                if (childRes != null) {
15888                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15889                    childRes.removedInfo.removedPackage = childPkg.packageName;
15890                    childRes.removedInfo.isUpdate = true;
15891                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15892                    childPackageUpdated = true;
15893                }
15894            }
15895            if (!childPackageUpdated) {
15896                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15897                childRemovedRes.removedPackage = childPkg.packageName;
15898                childRemovedRes.isUpdate = false;
15899                childRemovedRes.dataRemoved = true;
15900                synchronized (mPackages) {
15901                    if (childPs != null) {
15902                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15903                    }
15904                }
15905                if (res.removedInfo.removedChildPackages == null) {
15906                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15907                }
15908                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15909            }
15910        }
15911
15912        boolean sysPkg = (isSystemApp(oldPackage));
15913        if (sysPkg) {
15914            // Set the system/privileged flags as needed
15915            final boolean privileged =
15916                    (oldPackage.applicationInfo.privateFlags
15917                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15918            final int systemPolicyFlags = policyFlags
15919                    | PackageParser.PARSE_IS_SYSTEM
15920                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15921
15922            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15923                    user, allUsers, installerPackageName, res, installReason);
15924        } else {
15925            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15926                    user, allUsers, installerPackageName, res, installReason);
15927        }
15928    }
15929
15930    public List<String> getPreviousCodePaths(String packageName) {
15931        final PackageSetting ps = mSettings.mPackages.get(packageName);
15932        final List<String> result = new ArrayList<String>();
15933        if (ps != null && ps.oldCodePaths != null) {
15934            result.addAll(ps.oldCodePaths);
15935        }
15936        return result;
15937    }
15938
15939    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15940            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15941            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15942            int installReason) {
15943        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15944                + deletedPackage);
15945
15946        String pkgName = deletedPackage.packageName;
15947        boolean deletedPkg = true;
15948        boolean addedPkg = false;
15949        boolean updatedSettings = false;
15950        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15951        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15952                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15953
15954        final long origUpdateTime = (pkg.mExtras != null)
15955                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15956
15957        // First delete the existing package while retaining the data directory
15958        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15959                res.removedInfo, true, pkg)) {
15960            // If the existing package wasn't successfully deleted
15961            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15962            deletedPkg = false;
15963        } else {
15964            // Successfully deleted the old package; proceed with replace.
15965
15966            // If deleted package lived in a container, give users a chance to
15967            // relinquish resources before killing.
15968            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15969                if (DEBUG_INSTALL) {
15970                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15971                }
15972                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15973                final ArrayList<String> pkgList = new ArrayList<String>(1);
15974                pkgList.add(deletedPackage.applicationInfo.packageName);
15975                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15976            }
15977
15978            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15979                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15980            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15981
15982            try {
15983                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15984                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15985                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15986                        installReason);
15987
15988                // Update the in-memory copy of the previous code paths.
15989                PackageSetting ps = mSettings.mPackages.get(pkgName);
15990                if (!killApp) {
15991                    if (ps.oldCodePaths == null) {
15992                        ps.oldCodePaths = new ArraySet<>();
15993                    }
15994                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15995                    if (deletedPackage.splitCodePaths != null) {
15996                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15997                    }
15998                } else {
15999                    ps.oldCodePaths = null;
16000                }
16001                if (ps.childPackageNames != null) {
16002                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16003                        final String childPkgName = ps.childPackageNames.get(i);
16004                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16005                        childPs.oldCodePaths = ps.oldCodePaths;
16006                    }
16007                }
16008                // set instant app status, but, only if it's explicitly specified
16009                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16010                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16011                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16012                prepareAppDataAfterInstallLIF(newPackage);
16013                addedPkg = true;
16014                mDexManager.notifyPackageUpdated(newPackage.packageName,
16015                        newPackage.baseCodePath, newPackage.splitCodePaths);
16016            } catch (PackageManagerException e) {
16017                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16018            }
16019        }
16020
16021        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16022            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16023
16024            // Revert all internal state mutations and added folders for the failed install
16025            if (addedPkg) {
16026                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16027                        res.removedInfo, true, null);
16028            }
16029
16030            // Restore the old package
16031            if (deletedPkg) {
16032                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16033                File restoreFile = new File(deletedPackage.codePath);
16034                // Parse old package
16035                boolean oldExternal = isExternal(deletedPackage);
16036                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16037                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16038                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16039                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16040                try {
16041                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16042                            null);
16043                } catch (PackageManagerException e) {
16044                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16045                            + e.getMessage());
16046                    return;
16047                }
16048
16049                synchronized (mPackages) {
16050                    // Ensure the installer package name up to date
16051                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16052
16053                    // Update permissions for restored package
16054                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16055
16056                    mSettings.writeLPr();
16057                }
16058
16059                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16060            }
16061        } else {
16062            synchronized (mPackages) {
16063                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16064                if (ps != null) {
16065                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16066                    if (res.removedInfo.removedChildPackages != null) {
16067                        final int childCount = res.removedInfo.removedChildPackages.size();
16068                        // Iterate in reverse as we may modify the collection
16069                        for (int i = childCount - 1; i >= 0; i--) {
16070                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16071                            if (res.addedChildPackages.containsKey(childPackageName)) {
16072                                res.removedInfo.removedChildPackages.removeAt(i);
16073                            } else {
16074                                PackageRemovedInfo childInfo = res.removedInfo
16075                                        .removedChildPackages.valueAt(i);
16076                                childInfo.removedForAllUsers = mPackages.get(
16077                                        childInfo.removedPackage) == null;
16078                            }
16079                        }
16080                    }
16081                }
16082            }
16083        }
16084    }
16085
16086    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16087            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16088            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16089            int installReason) {
16090        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16091                + ", old=" + deletedPackage);
16092
16093        final boolean disabledSystem;
16094
16095        // Remove existing system package
16096        removePackageLI(deletedPackage, true);
16097
16098        synchronized (mPackages) {
16099            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16100        }
16101        if (!disabledSystem) {
16102            // We didn't need to disable the .apk as a current system package,
16103            // which means we are replacing another update that is already
16104            // installed.  We need to make sure to delete the older one's .apk.
16105            res.removedInfo.args = createInstallArgsForExisting(0,
16106                    deletedPackage.applicationInfo.getCodePath(),
16107                    deletedPackage.applicationInfo.getResourcePath(),
16108                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16109        } else {
16110            res.removedInfo.args = null;
16111        }
16112
16113        // Successfully disabled the old package. Now proceed with re-installation
16114        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16115                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16116        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16117
16118        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16119        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16120                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16121
16122        PackageParser.Package newPackage = null;
16123        try {
16124            // Add the package to the internal data structures
16125            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16126
16127            // Set the update and install times
16128            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16129            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16130                    System.currentTimeMillis());
16131
16132            // Update the package dynamic state if succeeded
16133            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16134                // Now that the install succeeded make sure we remove data
16135                // directories for any child package the update removed.
16136                final int deletedChildCount = (deletedPackage.childPackages != null)
16137                        ? deletedPackage.childPackages.size() : 0;
16138                final int newChildCount = (newPackage.childPackages != null)
16139                        ? newPackage.childPackages.size() : 0;
16140                for (int i = 0; i < deletedChildCount; i++) {
16141                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16142                    boolean childPackageDeleted = true;
16143                    for (int j = 0; j < newChildCount; j++) {
16144                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16145                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16146                            childPackageDeleted = false;
16147                            break;
16148                        }
16149                    }
16150                    if (childPackageDeleted) {
16151                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16152                                deletedChildPkg.packageName);
16153                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16154                            PackageRemovedInfo removedChildRes = res.removedInfo
16155                                    .removedChildPackages.get(deletedChildPkg.packageName);
16156                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16157                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16158                        }
16159                    }
16160                }
16161
16162                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16163                        installReason);
16164                prepareAppDataAfterInstallLIF(newPackage);
16165
16166                mDexManager.notifyPackageUpdated(newPackage.packageName,
16167                            newPackage.baseCodePath, newPackage.splitCodePaths);
16168            }
16169        } catch (PackageManagerException e) {
16170            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16171            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16172        }
16173
16174        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16175            // Re installation failed. Restore old information
16176            // Remove new pkg information
16177            if (newPackage != null) {
16178                removeInstalledPackageLI(newPackage, true);
16179            }
16180            // Add back the old system package
16181            try {
16182                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16183            } catch (PackageManagerException e) {
16184                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16185            }
16186
16187            synchronized (mPackages) {
16188                if (disabledSystem) {
16189                    enableSystemPackageLPw(deletedPackage);
16190                }
16191
16192                // Ensure the installer package name up to date
16193                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16194
16195                // Update permissions for restored package
16196                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16197
16198                mSettings.writeLPr();
16199            }
16200
16201            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16202                    + " after failed upgrade");
16203        }
16204    }
16205
16206    /**
16207     * Checks whether the parent or any of the child packages have a change shared
16208     * user. For a package to be a valid update the shred users of the parent and
16209     * the children should match. We may later support changing child shared users.
16210     * @param oldPkg The updated package.
16211     * @param newPkg The update package.
16212     * @return The shared user that change between the versions.
16213     */
16214    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16215            PackageParser.Package newPkg) {
16216        // Check parent shared user
16217        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16218            return newPkg.packageName;
16219        }
16220        // Check child shared users
16221        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16222        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16223        for (int i = 0; i < newChildCount; i++) {
16224            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16225            // If this child was present, did it have the same shared user?
16226            for (int j = 0; j < oldChildCount; j++) {
16227                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16228                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16229                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16230                    return newChildPkg.packageName;
16231                }
16232            }
16233        }
16234        return null;
16235    }
16236
16237    private void removeNativeBinariesLI(PackageSetting ps) {
16238        // Remove the lib path for the parent package
16239        if (ps != null) {
16240            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16241            // Remove the lib path for the child packages
16242            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16243            for (int i = 0; i < childCount; i++) {
16244                PackageSetting childPs = null;
16245                synchronized (mPackages) {
16246                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16247                }
16248                if (childPs != null) {
16249                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16250                            .legacyNativeLibraryPathString);
16251                }
16252            }
16253        }
16254    }
16255
16256    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16257        // Enable the parent package
16258        mSettings.enableSystemPackageLPw(pkg.packageName);
16259        // Enable the child packages
16260        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16261        for (int i = 0; i < childCount; i++) {
16262            PackageParser.Package childPkg = pkg.childPackages.get(i);
16263            mSettings.enableSystemPackageLPw(childPkg.packageName);
16264        }
16265    }
16266
16267    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16268            PackageParser.Package newPkg) {
16269        // Disable the parent package (parent always replaced)
16270        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16271        // Disable the child packages
16272        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16273        for (int i = 0; i < childCount; i++) {
16274            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16275            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16276            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16277        }
16278        return disabled;
16279    }
16280
16281    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16282            String installerPackageName) {
16283        // Enable the parent package
16284        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16285        // Enable the child packages
16286        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16287        for (int i = 0; i < childCount; i++) {
16288            PackageParser.Package childPkg = pkg.childPackages.get(i);
16289            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16290        }
16291    }
16292
16293    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16294        // Collect all used permissions in the UID
16295        ArraySet<String> usedPermissions = new ArraySet<>();
16296        final int packageCount = su.packages.size();
16297        for (int i = 0; i < packageCount; i++) {
16298            PackageSetting ps = su.packages.valueAt(i);
16299            if (ps.pkg == null) {
16300                continue;
16301            }
16302            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16303            for (int j = 0; j < requestedPermCount; j++) {
16304                String permission = ps.pkg.requestedPermissions.get(j);
16305                BasePermission bp = mSettings.mPermissions.get(permission);
16306                if (bp != null) {
16307                    usedPermissions.add(permission);
16308                }
16309            }
16310        }
16311
16312        PermissionsState permissionsState = su.getPermissionsState();
16313        // Prune install permissions
16314        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16315        final int installPermCount = installPermStates.size();
16316        for (int i = installPermCount - 1; i >= 0;  i--) {
16317            PermissionState permissionState = installPermStates.get(i);
16318            if (!usedPermissions.contains(permissionState.getName())) {
16319                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16320                if (bp != null) {
16321                    permissionsState.revokeInstallPermission(bp);
16322                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16323                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16324                }
16325            }
16326        }
16327
16328        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16329
16330        // Prune runtime permissions
16331        for (int userId : allUserIds) {
16332            List<PermissionState> runtimePermStates = permissionsState
16333                    .getRuntimePermissionStates(userId);
16334            final int runtimePermCount = runtimePermStates.size();
16335            for (int i = runtimePermCount - 1; i >= 0; i--) {
16336                PermissionState permissionState = runtimePermStates.get(i);
16337                if (!usedPermissions.contains(permissionState.getName())) {
16338                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16339                    if (bp != null) {
16340                        permissionsState.revokeRuntimePermission(bp, userId);
16341                        permissionsState.updatePermissionFlags(bp, userId,
16342                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16343                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16344                                runtimePermissionChangedUserIds, userId);
16345                    }
16346                }
16347            }
16348        }
16349
16350        return runtimePermissionChangedUserIds;
16351    }
16352
16353    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16354            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16355        // Update the parent package setting
16356        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16357                res, user, installReason);
16358        // Update the child packages setting
16359        final int childCount = (newPackage.childPackages != null)
16360                ? newPackage.childPackages.size() : 0;
16361        for (int i = 0; i < childCount; i++) {
16362            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16363            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16364            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16365                    childRes.origUsers, childRes, user, installReason);
16366        }
16367    }
16368
16369    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16370            String installerPackageName, int[] allUsers, int[] installedForUsers,
16371            PackageInstalledInfo res, UserHandle user, int installReason) {
16372        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16373
16374        String pkgName = newPackage.packageName;
16375        synchronized (mPackages) {
16376            //write settings. the installStatus will be incomplete at this stage.
16377            //note that the new package setting would have already been
16378            //added to mPackages. It hasn't been persisted yet.
16379            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16380            // TODO: Remove this write? It's also written at the end of this method
16381            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16382            mSettings.writeLPr();
16383            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16384        }
16385
16386        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16387        synchronized (mPackages) {
16388            updatePermissionsLPw(newPackage.packageName, newPackage,
16389                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16390                            ? UPDATE_PERMISSIONS_ALL : 0));
16391            // For system-bundled packages, we assume that installing an upgraded version
16392            // of the package implies that the user actually wants to run that new code,
16393            // so we enable the package.
16394            PackageSetting ps = mSettings.mPackages.get(pkgName);
16395            final int userId = user.getIdentifier();
16396            if (ps != null) {
16397                if (isSystemApp(newPackage)) {
16398                    if (DEBUG_INSTALL) {
16399                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16400                    }
16401                    // Enable system package for requested users
16402                    if (res.origUsers != null) {
16403                        for (int origUserId : res.origUsers) {
16404                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16405                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16406                                        origUserId, installerPackageName);
16407                            }
16408                        }
16409                    }
16410                    // Also convey the prior install/uninstall state
16411                    if (allUsers != null && installedForUsers != null) {
16412                        for (int currentUserId : allUsers) {
16413                            final boolean installed = ArrayUtils.contains(
16414                                    installedForUsers, currentUserId);
16415                            if (DEBUG_INSTALL) {
16416                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16417                            }
16418                            ps.setInstalled(installed, currentUserId);
16419                        }
16420                        // these install state changes will be persisted in the
16421                        // upcoming call to mSettings.writeLPr().
16422                    }
16423                }
16424                // It's implied that when a user requests installation, they want the app to be
16425                // installed and enabled.
16426                if (userId != UserHandle.USER_ALL) {
16427                    ps.setInstalled(true, userId);
16428                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16429                }
16430
16431                // When replacing an existing package, preserve the original install reason for all
16432                // users that had the package installed before.
16433                final Set<Integer> previousUserIds = new ArraySet<>();
16434                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16435                    final int installReasonCount = res.removedInfo.installReasons.size();
16436                    for (int i = 0; i < installReasonCount; i++) {
16437                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16438                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16439                        ps.setInstallReason(previousInstallReason, previousUserId);
16440                        previousUserIds.add(previousUserId);
16441                    }
16442                }
16443
16444                // Set install reason for users that are having the package newly installed.
16445                if (userId == UserHandle.USER_ALL) {
16446                    for (int currentUserId : sUserManager.getUserIds()) {
16447                        if (!previousUserIds.contains(currentUserId)) {
16448                            ps.setInstallReason(installReason, currentUserId);
16449                        }
16450                    }
16451                } else if (!previousUserIds.contains(userId)) {
16452                    ps.setInstallReason(installReason, userId);
16453                }
16454                mSettings.writeKernelMappingLPr(ps);
16455            }
16456            res.name = pkgName;
16457            res.uid = newPackage.applicationInfo.uid;
16458            res.pkg = newPackage;
16459            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16460            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16461            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16462            //to update install status
16463            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16464            mSettings.writeLPr();
16465            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16466        }
16467
16468        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16469    }
16470
16471    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16472        try {
16473            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16474            installPackageLI(args, res);
16475        } finally {
16476            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16477        }
16478    }
16479
16480    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16481        final int installFlags = args.installFlags;
16482        final String installerPackageName = args.installerPackageName;
16483        final String volumeUuid = args.volumeUuid;
16484        final File tmpPackageFile = new File(args.getCodePath());
16485        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16486        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16487                || (args.volumeUuid != null));
16488        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16489        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16490        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16491        boolean replace = false;
16492        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16493        if (args.move != null) {
16494            // moving a complete application; perform an initial scan on the new install location
16495            scanFlags |= SCAN_INITIAL;
16496        }
16497        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16498            scanFlags |= SCAN_DONT_KILL_APP;
16499        }
16500        if (instantApp) {
16501            scanFlags |= SCAN_AS_INSTANT_APP;
16502        }
16503        if (fullApp) {
16504            scanFlags |= SCAN_AS_FULL_APP;
16505        }
16506
16507        // Result object to be returned
16508        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16509
16510        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16511
16512        // Sanity check
16513        if (instantApp && (forwardLocked || onExternal)) {
16514            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16515                    + " external=" + onExternal);
16516            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16517            return;
16518        }
16519
16520        // Retrieve PackageSettings and parse package
16521        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16522                | PackageParser.PARSE_ENFORCE_CODE
16523                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16524                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16525                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16526                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16527        PackageParser pp = new PackageParser();
16528        pp.setSeparateProcesses(mSeparateProcesses);
16529        pp.setDisplayMetrics(mMetrics);
16530        pp.setCallback(mPackageParserCallback);
16531
16532        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16533        final PackageParser.Package pkg;
16534        try {
16535            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16536        } catch (PackageParserException e) {
16537            res.setError("Failed parse during installPackageLI", e);
16538            return;
16539        } finally {
16540            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16541        }
16542
16543        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16544        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16545            Slog.w(TAG, "Instant app package " + pkg.packageName
16546                    + " does not target O, this will be a fatal error.");
16547            // STOPSHIP: Make this a fatal error
16548            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16549        }
16550        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16551            Slog.w(TAG, "Instant app package " + pkg.packageName
16552                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16553            // STOPSHIP: Make this a fatal error
16554            pkg.applicationInfo.targetSandboxVersion = 2;
16555        }
16556
16557        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16558            // Static shared libraries have synthetic package names
16559            renameStaticSharedLibraryPackage(pkg);
16560
16561            // No static shared libs on external storage
16562            if (onExternal) {
16563                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16564                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16565                        "Packages declaring static-shared libs cannot be updated");
16566                return;
16567            }
16568        }
16569
16570        // If we are installing a clustered package add results for the children
16571        if (pkg.childPackages != null) {
16572            synchronized (mPackages) {
16573                final int childCount = pkg.childPackages.size();
16574                for (int i = 0; i < childCount; i++) {
16575                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16576                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16577                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16578                    childRes.pkg = childPkg;
16579                    childRes.name = childPkg.packageName;
16580                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16581                    if (childPs != null) {
16582                        childRes.origUsers = childPs.queryInstalledUsers(
16583                                sUserManager.getUserIds(), true);
16584                    }
16585                    if ((mPackages.containsKey(childPkg.packageName))) {
16586                        childRes.removedInfo = new PackageRemovedInfo();
16587                        childRes.removedInfo.removedPackage = childPkg.packageName;
16588                    }
16589                    if (res.addedChildPackages == null) {
16590                        res.addedChildPackages = new ArrayMap<>();
16591                    }
16592                    res.addedChildPackages.put(childPkg.packageName, childRes);
16593                }
16594            }
16595        }
16596
16597        // If package doesn't declare API override, mark that we have an install
16598        // time CPU ABI override.
16599        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16600            pkg.cpuAbiOverride = args.abiOverride;
16601        }
16602
16603        String pkgName = res.name = pkg.packageName;
16604        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16605            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16606                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16607                return;
16608            }
16609        }
16610
16611        try {
16612            // either use what we've been given or parse directly from the APK
16613            if (args.certificates != null) {
16614                try {
16615                    PackageParser.populateCertificates(pkg, args.certificates);
16616                } catch (PackageParserException e) {
16617                    // there was something wrong with the certificates we were given;
16618                    // try to pull them from the APK
16619                    PackageParser.collectCertificates(pkg, parseFlags);
16620                }
16621            } else {
16622                PackageParser.collectCertificates(pkg, parseFlags);
16623            }
16624        } catch (PackageParserException e) {
16625            res.setError("Failed collect during installPackageLI", e);
16626            return;
16627        }
16628
16629        // Get rid of all references to package scan path via parser.
16630        pp = null;
16631        String oldCodePath = null;
16632        boolean systemApp = false;
16633        synchronized (mPackages) {
16634            // Check if installing already existing package
16635            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16636                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16637                if (pkg.mOriginalPackages != null
16638                        && pkg.mOriginalPackages.contains(oldName)
16639                        && mPackages.containsKey(oldName)) {
16640                    // This package is derived from an original package,
16641                    // and this device has been updating from that original
16642                    // name.  We must continue using the original name, so
16643                    // rename the new package here.
16644                    pkg.setPackageName(oldName);
16645                    pkgName = pkg.packageName;
16646                    replace = true;
16647                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16648                            + oldName + " pkgName=" + pkgName);
16649                } else if (mPackages.containsKey(pkgName)) {
16650                    // This package, under its official name, already exists
16651                    // on the device; we should replace it.
16652                    replace = true;
16653                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16654                }
16655
16656                // Child packages are installed through the parent package
16657                if (pkg.parentPackage != null) {
16658                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16659                            "Package " + pkg.packageName + " is child of package "
16660                                    + pkg.parentPackage.parentPackage + ". Child packages "
16661                                    + "can be updated only through the parent package.");
16662                    return;
16663                }
16664
16665                if (replace) {
16666                    // Prevent apps opting out from runtime permissions
16667                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16668                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16669                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16670                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16671                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16672                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16673                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16674                                        + " doesn't support runtime permissions but the old"
16675                                        + " target SDK " + oldTargetSdk + " does.");
16676                        return;
16677                    }
16678
16679                    // Prevent installing of child packages
16680                    if (oldPackage.parentPackage != null) {
16681                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16682                                "Package " + pkg.packageName + " is child of package "
16683                                        + oldPackage.parentPackage + ". Child packages "
16684                                        + "can be updated only through the parent package.");
16685                        return;
16686                    }
16687                }
16688            }
16689
16690            PackageSetting ps = mSettings.mPackages.get(pkgName);
16691            if (ps != null) {
16692                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16693
16694                // Static shared libs have same package with different versions where
16695                // we internally use a synthetic package name to allow multiple versions
16696                // of the same package, therefore we need to compare signatures against
16697                // the package setting for the latest library version.
16698                PackageSetting signatureCheckPs = ps;
16699                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16700                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16701                    if (libraryEntry != null) {
16702                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16703                    }
16704                }
16705
16706                // Quick sanity check that we're signed correctly if updating;
16707                // we'll check this again later when scanning, but we want to
16708                // bail early here before tripping over redefined permissions.
16709                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16710                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16711                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16712                                + pkg.packageName + " upgrade keys do not match the "
16713                                + "previously installed version");
16714                        return;
16715                    }
16716                } else {
16717                    try {
16718                        verifySignaturesLP(signatureCheckPs, pkg);
16719                    } catch (PackageManagerException e) {
16720                        res.setError(e.error, e.getMessage());
16721                        return;
16722                    }
16723                }
16724
16725                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16726                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16727                    systemApp = (ps.pkg.applicationInfo.flags &
16728                            ApplicationInfo.FLAG_SYSTEM) != 0;
16729                }
16730                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16731            }
16732
16733            int N = pkg.permissions.size();
16734            for (int i = N-1; i >= 0; i--) {
16735                PackageParser.Permission perm = pkg.permissions.get(i);
16736                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16737
16738                // Don't allow anyone but the platform to define ephemeral permissions.
16739                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16740                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16741                    Slog.w(TAG, "Package " + pkg.packageName
16742                            + " attempting to delcare ephemeral permission "
16743                            + perm.info.name + "; Removing ephemeral.");
16744                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16745                }
16746                // Check whether the newly-scanned package wants to define an already-defined perm
16747                if (bp != null) {
16748                    // If the defining package is signed with our cert, it's okay.  This
16749                    // also includes the "updating the same package" case, of course.
16750                    // "updating same package" could also involve key-rotation.
16751                    final boolean sigsOk;
16752                    if (bp.sourcePackage.equals(pkg.packageName)
16753                            && (bp.packageSetting instanceof PackageSetting)
16754                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16755                                    scanFlags))) {
16756                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16757                    } else {
16758                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16759                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16760                    }
16761                    if (!sigsOk) {
16762                        // If the owning package is the system itself, we log but allow
16763                        // install to proceed; we fail the install on all other permission
16764                        // redefinitions.
16765                        if (!bp.sourcePackage.equals("android")) {
16766                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16767                                    + pkg.packageName + " attempting to redeclare permission "
16768                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16769                            res.origPermission = perm.info.name;
16770                            res.origPackage = bp.sourcePackage;
16771                            return;
16772                        } else {
16773                            Slog.w(TAG, "Package " + pkg.packageName
16774                                    + " attempting to redeclare system permission "
16775                                    + perm.info.name + "; ignoring new declaration");
16776                            pkg.permissions.remove(i);
16777                        }
16778                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16779                        // Prevent apps to change protection level to dangerous from any other
16780                        // type as this would allow a privilege escalation where an app adds a
16781                        // normal/signature permission in other app's group and later redefines
16782                        // it as dangerous leading to the group auto-grant.
16783                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16784                                == PermissionInfo.PROTECTION_DANGEROUS) {
16785                            if (bp != null && !bp.isRuntime()) {
16786                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16787                                        + "non-runtime permission " + perm.info.name
16788                                        + " to runtime; keeping old protection level");
16789                                perm.info.protectionLevel = bp.protectionLevel;
16790                            }
16791                        }
16792                    }
16793                }
16794            }
16795        }
16796
16797        if (systemApp) {
16798            if (onExternal) {
16799                // Abort update; system app can't be replaced with app on sdcard
16800                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16801                        "Cannot install updates to system apps on sdcard");
16802                return;
16803            } else if (instantApp) {
16804                // Abort update; system app can't be replaced with an instant app
16805                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16806                        "Cannot update a system app with an instant app");
16807                return;
16808            }
16809        }
16810
16811        if (args.move != null) {
16812            // We did an in-place move, so dex is ready to roll
16813            scanFlags |= SCAN_NO_DEX;
16814            scanFlags |= SCAN_MOVE;
16815
16816            synchronized (mPackages) {
16817                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16818                if (ps == null) {
16819                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16820                            "Missing settings for moved package " + pkgName);
16821                }
16822
16823                // We moved the entire application as-is, so bring over the
16824                // previously derived ABI information.
16825                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16826                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16827            }
16828
16829        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16830            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16831            scanFlags |= SCAN_NO_DEX;
16832
16833            try {
16834                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16835                    args.abiOverride : pkg.cpuAbiOverride);
16836                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16837                        true /*extractLibs*/, mAppLib32InstallDir);
16838            } catch (PackageManagerException pme) {
16839                Slog.e(TAG, "Error deriving application ABI", pme);
16840                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16841                return;
16842            }
16843
16844            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16845            // Do not run PackageDexOptimizer through the local performDexOpt
16846            // method because `pkg` may not be in `mPackages` yet.
16847            //
16848            // Also, don't fail application installs if the dexopt step fails.
16849            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16850                    null /* instructionSets */, false /* checkProfiles */,
16851                    getCompilerFilterForReason(REASON_INSTALL),
16852                    getOrCreateCompilerPackageStats(pkg),
16853                    mDexManager.isUsedByOtherApps(pkg.packageName));
16854            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16855
16856            // Notify BackgroundDexOptJobService that the package has been changed.
16857            // If this is an update of a package which used to fail to compile,
16858            // BDOS will remove it from its blacklist.
16859            // TODO: Layering violation
16860            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16861        }
16862
16863        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16864            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16865            return;
16866        }
16867
16868        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16869
16870        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16871                "installPackageLI")) {
16872            if (replace) {
16873                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16874                    // Static libs have a synthetic package name containing the version
16875                    // and cannot be updated as an update would get a new package name,
16876                    // unless this is the exact same version code which is useful for
16877                    // development.
16878                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16879                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16880                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16881                                + "static-shared libs cannot be updated");
16882                        return;
16883                    }
16884                }
16885                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16886                        installerPackageName, res, args.installReason);
16887            } else {
16888                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16889                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16890            }
16891        }
16892        synchronized (mPackages) {
16893            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16894            if (ps != null) {
16895                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16896                ps.setUpdateAvailable(false /*updateAvailable*/);
16897            }
16898
16899            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16900            for (int i = 0; i < childCount; i++) {
16901                PackageParser.Package childPkg = pkg.childPackages.get(i);
16902                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16903                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16904                if (childPs != null) {
16905                    childRes.newUsers = childPs.queryInstalledUsers(
16906                            sUserManager.getUserIds(), true);
16907                }
16908            }
16909
16910            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16911                updateSequenceNumberLP(pkgName, res.newUsers);
16912            }
16913        }
16914    }
16915
16916    private void startIntentFilterVerifications(int userId, boolean replacing,
16917            PackageParser.Package pkg) {
16918        if (mIntentFilterVerifierComponent == null) {
16919            Slog.w(TAG, "No IntentFilter verification will not be done as "
16920                    + "there is no IntentFilterVerifier available!");
16921            return;
16922        }
16923
16924        final int verifierUid = getPackageUid(
16925                mIntentFilterVerifierComponent.getPackageName(),
16926                MATCH_DEBUG_TRIAGED_MISSING,
16927                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16928
16929        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16930        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16931        mHandler.sendMessage(msg);
16932
16933        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16934        for (int i = 0; i < childCount; i++) {
16935            PackageParser.Package childPkg = pkg.childPackages.get(i);
16936            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16937            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16938            mHandler.sendMessage(msg);
16939        }
16940    }
16941
16942    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16943            PackageParser.Package pkg) {
16944        int size = pkg.activities.size();
16945        if (size == 0) {
16946            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16947                    "No activity, so no need to verify any IntentFilter!");
16948            return;
16949        }
16950
16951        final boolean hasDomainURLs = hasDomainURLs(pkg);
16952        if (!hasDomainURLs) {
16953            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16954                    "No domain URLs, so no need to verify any IntentFilter!");
16955            return;
16956        }
16957
16958        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16959                + " if any IntentFilter from the " + size
16960                + " Activities needs verification ...");
16961
16962        int count = 0;
16963        final String packageName = pkg.packageName;
16964
16965        synchronized (mPackages) {
16966            // If this is a new install and we see that we've already run verification for this
16967            // package, we have nothing to do: it means the state was restored from backup.
16968            if (!replacing) {
16969                IntentFilterVerificationInfo ivi =
16970                        mSettings.getIntentFilterVerificationLPr(packageName);
16971                if (ivi != null) {
16972                    if (DEBUG_DOMAIN_VERIFICATION) {
16973                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16974                                + ivi.getStatusString());
16975                    }
16976                    return;
16977                }
16978            }
16979
16980            // If any filters need to be verified, then all need to be.
16981            boolean needToVerify = false;
16982            for (PackageParser.Activity a : pkg.activities) {
16983                for (ActivityIntentInfo filter : a.intents) {
16984                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16985                        if (DEBUG_DOMAIN_VERIFICATION) {
16986                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16987                        }
16988                        needToVerify = true;
16989                        break;
16990                    }
16991                }
16992            }
16993
16994            if (needToVerify) {
16995                final int verificationId = mIntentFilterVerificationToken++;
16996                for (PackageParser.Activity a : pkg.activities) {
16997                    for (ActivityIntentInfo filter : a.intents) {
16998                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16999                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17000                                    "Verification needed for IntentFilter:" + filter.toString());
17001                            mIntentFilterVerifier.addOneIntentFilterVerification(
17002                                    verifierUid, userId, verificationId, filter, packageName);
17003                            count++;
17004                        }
17005                    }
17006                }
17007            }
17008        }
17009
17010        if (count > 0) {
17011            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17012                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17013                    +  " for userId:" + userId);
17014            mIntentFilterVerifier.startVerifications(userId);
17015        } else {
17016            if (DEBUG_DOMAIN_VERIFICATION) {
17017                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17018            }
17019        }
17020    }
17021
17022    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17023        final ComponentName cn  = filter.activity.getComponentName();
17024        final String packageName = cn.getPackageName();
17025
17026        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17027                packageName);
17028        if (ivi == null) {
17029            return true;
17030        }
17031        int status = ivi.getStatus();
17032        switch (status) {
17033            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17034            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17035                return true;
17036
17037            default:
17038                // Nothing to do
17039                return false;
17040        }
17041    }
17042
17043    private static boolean isMultiArch(ApplicationInfo info) {
17044        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17045    }
17046
17047    private static boolean isExternal(PackageParser.Package pkg) {
17048        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17049    }
17050
17051    private static boolean isExternal(PackageSetting ps) {
17052        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17053    }
17054
17055    private static boolean isSystemApp(PackageParser.Package pkg) {
17056        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17057    }
17058
17059    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17060        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17061    }
17062
17063    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17064        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17065    }
17066
17067    private static boolean isSystemApp(PackageSetting ps) {
17068        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17069    }
17070
17071    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17072        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17073    }
17074
17075    private int packageFlagsToInstallFlags(PackageSetting ps) {
17076        int installFlags = 0;
17077        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17078            // This existing package was an external ASEC install when we have
17079            // the external flag without a UUID
17080            installFlags |= PackageManager.INSTALL_EXTERNAL;
17081        }
17082        if (ps.isForwardLocked()) {
17083            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17084        }
17085        return installFlags;
17086    }
17087
17088    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17089        if (isExternal(pkg)) {
17090            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17091                return StorageManager.UUID_PRIMARY_PHYSICAL;
17092            } else {
17093                return pkg.volumeUuid;
17094            }
17095        } else {
17096            return StorageManager.UUID_PRIVATE_INTERNAL;
17097        }
17098    }
17099
17100    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17101        if (isExternal(pkg)) {
17102            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17103                return mSettings.getExternalVersion();
17104            } else {
17105                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17106            }
17107        } else {
17108            return mSettings.getInternalVersion();
17109        }
17110    }
17111
17112    private void deleteTempPackageFiles() {
17113        final FilenameFilter filter = new FilenameFilter() {
17114            public boolean accept(File dir, String name) {
17115                return name.startsWith("vmdl") && name.endsWith(".tmp");
17116            }
17117        };
17118        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17119            file.delete();
17120        }
17121    }
17122
17123    @Override
17124    public void deletePackageAsUser(String packageName, int versionCode,
17125            IPackageDeleteObserver observer, int userId, int flags) {
17126        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17127                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17128    }
17129
17130    @Override
17131    public void deletePackageVersioned(VersionedPackage versionedPackage,
17132            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17133        mContext.enforceCallingOrSelfPermission(
17134                android.Manifest.permission.DELETE_PACKAGES, null);
17135        Preconditions.checkNotNull(versionedPackage);
17136        Preconditions.checkNotNull(observer);
17137        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17138                PackageManager.VERSION_CODE_HIGHEST,
17139                Integer.MAX_VALUE, "versionCode must be >= -1");
17140
17141        final String packageName = versionedPackage.getPackageName();
17142        // TODO: We will change version code to long, so in the new API it is long
17143        final int versionCode = (int) versionedPackage.getVersionCode();
17144        final String internalPackageName;
17145        synchronized (mPackages) {
17146            // Normalize package name to handle renamed packages and static libs
17147            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17148                    // TODO: We will change version code to long, so in the new API it is long
17149                    (int) versionedPackage.getVersionCode());
17150        }
17151
17152        final int uid = Binder.getCallingUid();
17153        if (!isOrphaned(internalPackageName)
17154                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17155            try {
17156                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17157                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17158                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17159                observer.onUserActionRequired(intent);
17160            } catch (RemoteException re) {
17161            }
17162            return;
17163        }
17164        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17165        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17166        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17167            mContext.enforceCallingOrSelfPermission(
17168                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17169                    "deletePackage for user " + userId);
17170        }
17171
17172        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17173            try {
17174                observer.onPackageDeleted(packageName,
17175                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17176            } catch (RemoteException re) {
17177            }
17178            return;
17179        }
17180
17181        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17182            try {
17183                observer.onPackageDeleted(packageName,
17184                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17185            } catch (RemoteException re) {
17186            }
17187            return;
17188        }
17189
17190        if (DEBUG_REMOVE) {
17191            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17192                    + " deleteAllUsers: " + deleteAllUsers + " version="
17193                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17194                    ? "VERSION_CODE_HIGHEST" : versionCode));
17195        }
17196        // Queue up an async operation since the package deletion may take a little while.
17197        mHandler.post(new Runnable() {
17198            public void run() {
17199                mHandler.removeCallbacks(this);
17200                int returnCode;
17201                if (!deleteAllUsers) {
17202                    returnCode = deletePackageX(internalPackageName, versionCode,
17203                            userId, deleteFlags);
17204                } else {
17205                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17206                            internalPackageName, users);
17207                    // If nobody is blocking uninstall, proceed with delete for all users
17208                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17209                        returnCode = deletePackageX(internalPackageName, versionCode,
17210                                userId, deleteFlags);
17211                    } else {
17212                        // Otherwise uninstall individually for users with blockUninstalls=false
17213                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17214                        for (int userId : users) {
17215                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17216                                returnCode = deletePackageX(internalPackageName, versionCode,
17217                                        userId, userFlags);
17218                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17219                                    Slog.w(TAG, "Package delete failed for user " + userId
17220                                            + ", returnCode " + returnCode);
17221                                }
17222                            }
17223                        }
17224                        // The app has only been marked uninstalled for certain users.
17225                        // We still need to report that delete was blocked
17226                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17227                    }
17228                }
17229                try {
17230                    observer.onPackageDeleted(packageName, returnCode, null);
17231                } catch (RemoteException e) {
17232                    Log.i(TAG, "Observer no longer exists.");
17233                } //end catch
17234            } //end run
17235        });
17236    }
17237
17238    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17239        if (pkg.staticSharedLibName != null) {
17240            return pkg.manifestPackageName;
17241        }
17242        return pkg.packageName;
17243    }
17244
17245    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17246        // Handle renamed packages
17247        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17248        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17249
17250        // Is this a static library?
17251        SparseArray<SharedLibraryEntry> versionedLib =
17252                mStaticLibsByDeclaringPackage.get(packageName);
17253        if (versionedLib == null || versionedLib.size() <= 0) {
17254            return packageName;
17255        }
17256
17257        // Figure out which lib versions the caller can see
17258        SparseIntArray versionsCallerCanSee = null;
17259        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17260        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17261                && callingAppId != Process.ROOT_UID) {
17262            versionsCallerCanSee = new SparseIntArray();
17263            String libName = versionedLib.valueAt(0).info.getName();
17264            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17265            if (uidPackages != null) {
17266                for (String uidPackage : uidPackages) {
17267                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17268                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17269                    if (libIdx >= 0) {
17270                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17271                        versionsCallerCanSee.append(libVersion, libVersion);
17272                    }
17273                }
17274            }
17275        }
17276
17277        // Caller can see nothing - done
17278        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17279            return packageName;
17280        }
17281
17282        // Find the version the caller can see and the app version code
17283        SharedLibraryEntry highestVersion = null;
17284        final int versionCount = versionedLib.size();
17285        for (int i = 0; i < versionCount; i++) {
17286            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17287            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17288                    libEntry.info.getVersion()) < 0) {
17289                continue;
17290            }
17291            // TODO: We will change version code to long, so in the new API it is long
17292            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17293            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17294                if (libVersionCode == versionCode) {
17295                    return libEntry.apk;
17296                }
17297            } else if (highestVersion == null) {
17298                highestVersion = libEntry;
17299            } else if (libVersionCode  > highestVersion.info
17300                    .getDeclaringPackage().getVersionCode()) {
17301                highestVersion = libEntry;
17302            }
17303        }
17304
17305        if (highestVersion != null) {
17306            return highestVersion.apk;
17307        }
17308
17309        return packageName;
17310    }
17311
17312    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17313        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17314              || callingUid == Process.SYSTEM_UID) {
17315            return true;
17316        }
17317        final int callingUserId = UserHandle.getUserId(callingUid);
17318        // If the caller installed the pkgName, then allow it to silently uninstall.
17319        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17320            return true;
17321        }
17322
17323        // Allow package verifier to silently uninstall.
17324        if (mRequiredVerifierPackage != null &&
17325                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17326            return true;
17327        }
17328
17329        // Allow package uninstaller to silently uninstall.
17330        if (mRequiredUninstallerPackage != null &&
17331                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17332            return true;
17333        }
17334
17335        // Allow storage manager to silently uninstall.
17336        if (mStorageManagerPackage != null &&
17337                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17338            return true;
17339        }
17340        return false;
17341    }
17342
17343    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17344        int[] result = EMPTY_INT_ARRAY;
17345        for (int userId : userIds) {
17346            if (getBlockUninstallForUser(packageName, userId)) {
17347                result = ArrayUtils.appendInt(result, userId);
17348            }
17349        }
17350        return result;
17351    }
17352
17353    @Override
17354    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17355        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17356    }
17357
17358    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17359        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17360                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17361        try {
17362            if (dpm != null) {
17363                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17364                        /* callingUserOnly =*/ false);
17365                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17366                        : deviceOwnerComponentName.getPackageName();
17367                // Does the package contains the device owner?
17368                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17369                // this check is probably not needed, since DO should be registered as a device
17370                // admin on some user too. (Original bug for this: b/17657954)
17371                if (packageName.equals(deviceOwnerPackageName)) {
17372                    return true;
17373                }
17374                // Does it contain a device admin for any user?
17375                int[] users;
17376                if (userId == UserHandle.USER_ALL) {
17377                    users = sUserManager.getUserIds();
17378                } else {
17379                    users = new int[]{userId};
17380                }
17381                for (int i = 0; i < users.length; ++i) {
17382                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17383                        return true;
17384                    }
17385                }
17386            }
17387        } catch (RemoteException e) {
17388        }
17389        return false;
17390    }
17391
17392    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17393        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17394    }
17395
17396    /**
17397     *  This method is an internal method that could be get invoked either
17398     *  to delete an installed package or to clean up a failed installation.
17399     *  After deleting an installed package, a broadcast is sent to notify any
17400     *  listeners that the package has been removed. For cleaning up a failed
17401     *  installation, the broadcast is not necessary since the package's
17402     *  installation wouldn't have sent the initial broadcast either
17403     *  The key steps in deleting a package are
17404     *  deleting the package information in internal structures like mPackages,
17405     *  deleting the packages base directories through installd
17406     *  updating mSettings to reflect current status
17407     *  persisting settings for later use
17408     *  sending a broadcast if necessary
17409     */
17410    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17411        final PackageRemovedInfo info = new PackageRemovedInfo();
17412        final boolean res;
17413
17414        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17415                ? UserHandle.USER_ALL : userId;
17416
17417        if (isPackageDeviceAdmin(packageName, removeUser)) {
17418            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17419            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17420        }
17421
17422        PackageSetting uninstalledPs = null;
17423        PackageParser.Package pkg = null;
17424
17425        // for the uninstall-updates case and restricted profiles, remember the per-
17426        // user handle installed state
17427        int[] allUsers;
17428        synchronized (mPackages) {
17429            uninstalledPs = mSettings.mPackages.get(packageName);
17430            if (uninstalledPs == null) {
17431                Slog.w(TAG, "Not removing non-existent package " + packageName);
17432                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17433            }
17434
17435            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17436                    && uninstalledPs.versionCode != versionCode) {
17437                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17438                        + uninstalledPs.versionCode + " != " + versionCode);
17439                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17440            }
17441
17442            // Static shared libs can be declared by any package, so let us not
17443            // allow removing a package if it provides a lib others depend on.
17444            pkg = mPackages.get(packageName);
17445            if (pkg != null && pkg.staticSharedLibName != null) {
17446                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17447                        pkg.staticSharedLibVersion);
17448                if (libEntry != null) {
17449                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17450                            libEntry.info, 0, userId);
17451                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17452                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17453                                + " hosting lib " + libEntry.info.getName() + " version "
17454                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17455                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17456                    }
17457                }
17458            }
17459
17460            allUsers = sUserManager.getUserIds();
17461            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17462        }
17463
17464        final int freezeUser;
17465        if (isUpdatedSystemApp(uninstalledPs)
17466                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17467            // We're downgrading a system app, which will apply to all users, so
17468            // freeze them all during the downgrade
17469            freezeUser = UserHandle.USER_ALL;
17470        } else {
17471            freezeUser = removeUser;
17472        }
17473
17474        synchronized (mInstallLock) {
17475            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17476            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17477                    deleteFlags, "deletePackageX")) {
17478                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17479                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17480            }
17481            synchronized (mPackages) {
17482                if (res) {
17483                    if (pkg != null) {
17484                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17485                    }
17486                    updateSequenceNumberLP(packageName, info.removedUsers);
17487                }
17488            }
17489        }
17490
17491        if (res) {
17492            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17493            info.sendPackageRemovedBroadcasts(killApp);
17494            info.sendSystemPackageUpdatedBroadcasts();
17495            info.sendSystemPackageAppearedBroadcasts();
17496        }
17497        // Force a gc here.
17498        Runtime.getRuntime().gc();
17499        // Delete the resources here after sending the broadcast to let
17500        // other processes clean up before deleting resources.
17501        if (info.args != null) {
17502            synchronized (mInstallLock) {
17503                info.args.doPostDeleteLI(true);
17504            }
17505        }
17506
17507        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17508    }
17509
17510    class PackageRemovedInfo {
17511        String removedPackage;
17512        int uid = -1;
17513        int removedAppId = -1;
17514        int[] origUsers;
17515        int[] removedUsers = null;
17516        SparseArray<Integer> installReasons;
17517        boolean isRemovedPackageSystemUpdate = false;
17518        boolean isUpdate;
17519        boolean dataRemoved;
17520        boolean removedForAllUsers;
17521        boolean isStaticSharedLib;
17522        // Clean up resources deleted packages.
17523        InstallArgs args = null;
17524        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17525        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17526
17527        void sendPackageRemovedBroadcasts(boolean killApp) {
17528            sendPackageRemovedBroadcastInternal(killApp);
17529            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17530            for (int i = 0; i < childCount; i++) {
17531                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17532                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17533            }
17534        }
17535
17536        void sendSystemPackageUpdatedBroadcasts() {
17537            if (isRemovedPackageSystemUpdate) {
17538                sendSystemPackageUpdatedBroadcastsInternal();
17539                final int childCount = (removedChildPackages != null)
17540                        ? removedChildPackages.size() : 0;
17541                for (int i = 0; i < childCount; i++) {
17542                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17543                    if (childInfo.isRemovedPackageSystemUpdate) {
17544                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17545                    }
17546                }
17547            }
17548        }
17549
17550        void sendSystemPackageAppearedBroadcasts() {
17551            final int packageCount = (appearedChildPackages != null)
17552                    ? appearedChildPackages.size() : 0;
17553            for (int i = 0; i < packageCount; i++) {
17554                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17555                sendPackageAddedForNewUsers(installedInfo.name, true,
17556                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17557            }
17558        }
17559
17560        private void sendSystemPackageUpdatedBroadcastsInternal() {
17561            Bundle extras = new Bundle(2);
17562            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17563            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17564            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17565                    extras, 0, null, null, null);
17566            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17567                    extras, 0, null, null, null);
17568            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17569                    null, 0, removedPackage, null, null);
17570        }
17571
17572        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17573            // Don't send static shared library removal broadcasts as these
17574            // libs are visible only the the apps that depend on them an one
17575            // cannot remove the library if it has a dependency.
17576            if (isStaticSharedLib) {
17577                return;
17578            }
17579            Bundle extras = new Bundle(2);
17580            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17581            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17582            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17583            if (isUpdate || isRemovedPackageSystemUpdate) {
17584                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17585            }
17586            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17587            if (removedPackage != null) {
17588                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17589                        extras, 0, null, null, removedUsers);
17590                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17591                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17592                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17593                            null, null, removedUsers);
17594                }
17595            }
17596            if (removedAppId >= 0) {
17597                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17598                        removedUsers);
17599            }
17600        }
17601    }
17602
17603    /*
17604     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17605     * flag is not set, the data directory is removed as well.
17606     * make sure this flag is set for partially installed apps. If not its meaningless to
17607     * delete a partially installed application.
17608     */
17609    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17610            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17611        String packageName = ps.name;
17612        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17613        // Retrieve object to delete permissions for shared user later on
17614        final PackageParser.Package deletedPkg;
17615        final PackageSetting deletedPs;
17616        // reader
17617        synchronized (mPackages) {
17618            deletedPkg = mPackages.get(packageName);
17619            deletedPs = mSettings.mPackages.get(packageName);
17620            if (outInfo != null) {
17621                outInfo.removedPackage = packageName;
17622                outInfo.isStaticSharedLib = deletedPkg != null
17623                        && deletedPkg.staticSharedLibName != null;
17624                outInfo.removedUsers = deletedPs != null
17625                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17626                        : null;
17627            }
17628        }
17629
17630        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17631
17632        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17633            final PackageParser.Package resolvedPkg;
17634            if (deletedPkg != null) {
17635                resolvedPkg = deletedPkg;
17636            } else {
17637                // We don't have a parsed package when it lives on an ejected
17638                // adopted storage device, so fake something together
17639                resolvedPkg = new PackageParser.Package(ps.name);
17640                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17641            }
17642            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17643                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17644            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17645            if (outInfo != null) {
17646                outInfo.dataRemoved = true;
17647            }
17648            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17649        }
17650
17651        int removedAppId = -1;
17652
17653        // writer
17654        synchronized (mPackages) {
17655            boolean installedStateChanged = false;
17656            if (deletedPs != null) {
17657                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17658                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17659                    clearDefaultBrowserIfNeeded(packageName);
17660                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17661                    removedAppId = mSettings.removePackageLPw(packageName);
17662                    if (outInfo != null) {
17663                        outInfo.removedAppId = removedAppId;
17664                    }
17665                    updatePermissionsLPw(deletedPs.name, null, 0);
17666                    if (deletedPs.sharedUser != null) {
17667                        // Remove permissions associated with package. Since runtime
17668                        // permissions are per user we have to kill the removed package
17669                        // or packages running under the shared user of the removed
17670                        // package if revoking the permissions requested only by the removed
17671                        // package is successful and this causes a change in gids.
17672                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17673                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17674                                    userId);
17675                            if (userIdToKill == UserHandle.USER_ALL
17676                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17677                                // If gids changed for this user, kill all affected packages.
17678                                mHandler.post(new Runnable() {
17679                                    @Override
17680                                    public void run() {
17681                                        // This has to happen with no lock held.
17682                                        killApplication(deletedPs.name, deletedPs.appId,
17683                                                KILL_APP_REASON_GIDS_CHANGED);
17684                                    }
17685                                });
17686                                break;
17687                            }
17688                        }
17689                    }
17690                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17691                }
17692                // make sure to preserve per-user disabled state if this removal was just
17693                // a downgrade of a system app to the factory package
17694                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17695                    if (DEBUG_REMOVE) {
17696                        Slog.d(TAG, "Propagating install state across downgrade");
17697                    }
17698                    for (int userId : allUserHandles) {
17699                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17700                        if (DEBUG_REMOVE) {
17701                            Slog.d(TAG, "    user " + userId + " => " + installed);
17702                        }
17703                        if (installed != ps.getInstalled(userId)) {
17704                            installedStateChanged = true;
17705                        }
17706                        ps.setInstalled(installed, userId);
17707                    }
17708                }
17709            }
17710            // can downgrade to reader
17711            if (writeSettings) {
17712                // Save settings now
17713                mSettings.writeLPr();
17714            }
17715            if (installedStateChanged) {
17716                mSettings.writeKernelMappingLPr(ps);
17717            }
17718        }
17719        if (removedAppId != -1) {
17720            // A user ID was deleted here. Go through all users and remove it
17721            // from KeyStore.
17722            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17723        }
17724    }
17725
17726    static boolean locationIsPrivileged(File path) {
17727        try {
17728            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17729                    .getCanonicalPath();
17730            return path.getCanonicalPath().startsWith(privilegedAppDir);
17731        } catch (IOException e) {
17732            Slog.e(TAG, "Unable to access code path " + path);
17733        }
17734        return false;
17735    }
17736
17737    /*
17738     * Tries to delete system package.
17739     */
17740    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17741            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17742            boolean writeSettings) {
17743        if (deletedPs.parentPackageName != null) {
17744            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17745            return false;
17746        }
17747
17748        final boolean applyUserRestrictions
17749                = (allUserHandles != null) && (outInfo.origUsers != null);
17750        final PackageSetting disabledPs;
17751        // Confirm if the system package has been updated
17752        // An updated system app can be deleted. This will also have to restore
17753        // the system pkg from system partition
17754        // reader
17755        synchronized (mPackages) {
17756            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17757        }
17758
17759        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17760                + " disabledPs=" + disabledPs);
17761
17762        if (disabledPs == null) {
17763            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17764            return false;
17765        } else if (DEBUG_REMOVE) {
17766            Slog.d(TAG, "Deleting system pkg from data partition");
17767        }
17768
17769        if (DEBUG_REMOVE) {
17770            if (applyUserRestrictions) {
17771                Slog.d(TAG, "Remembering install states:");
17772                for (int userId : allUserHandles) {
17773                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17774                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17775                }
17776            }
17777        }
17778
17779        // Delete the updated package
17780        outInfo.isRemovedPackageSystemUpdate = true;
17781        if (outInfo.removedChildPackages != null) {
17782            final int childCount = (deletedPs.childPackageNames != null)
17783                    ? deletedPs.childPackageNames.size() : 0;
17784            for (int i = 0; i < childCount; i++) {
17785                String childPackageName = deletedPs.childPackageNames.get(i);
17786                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17787                        .contains(childPackageName)) {
17788                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17789                            childPackageName);
17790                    if (childInfo != null) {
17791                        childInfo.isRemovedPackageSystemUpdate = true;
17792                    }
17793                }
17794            }
17795        }
17796
17797        if (disabledPs.versionCode < deletedPs.versionCode) {
17798            // Delete data for downgrades
17799            flags &= ~PackageManager.DELETE_KEEP_DATA;
17800        } else {
17801            // Preserve data by setting flag
17802            flags |= PackageManager.DELETE_KEEP_DATA;
17803        }
17804
17805        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17806                outInfo, writeSettings, disabledPs.pkg);
17807        if (!ret) {
17808            return false;
17809        }
17810
17811        // writer
17812        synchronized (mPackages) {
17813            // Reinstate the old system package
17814            enableSystemPackageLPw(disabledPs.pkg);
17815            // Remove any native libraries from the upgraded package.
17816            removeNativeBinariesLI(deletedPs);
17817        }
17818
17819        // Install the system package
17820        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17821        int parseFlags = mDefParseFlags
17822                | PackageParser.PARSE_MUST_BE_APK
17823                | PackageParser.PARSE_IS_SYSTEM
17824                | PackageParser.PARSE_IS_SYSTEM_DIR;
17825        if (locationIsPrivileged(disabledPs.codePath)) {
17826            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17827        }
17828
17829        final PackageParser.Package newPkg;
17830        try {
17831            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17832                0 /* currentTime */, null);
17833        } catch (PackageManagerException e) {
17834            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17835                    + e.getMessage());
17836            return false;
17837        }
17838
17839        try {
17840            // update shared libraries for the newly re-installed system package
17841            updateSharedLibrariesLPr(newPkg, null);
17842        } catch (PackageManagerException e) {
17843            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17844        }
17845
17846        prepareAppDataAfterInstallLIF(newPkg);
17847
17848        // writer
17849        synchronized (mPackages) {
17850            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17851
17852            // Propagate the permissions state as we do not want to drop on the floor
17853            // runtime permissions. The update permissions method below will take
17854            // care of removing obsolete permissions and grant install permissions.
17855            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17856            updatePermissionsLPw(newPkg.packageName, newPkg,
17857                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17858
17859            if (applyUserRestrictions) {
17860                boolean installedStateChanged = false;
17861                if (DEBUG_REMOVE) {
17862                    Slog.d(TAG, "Propagating install state across reinstall");
17863                }
17864                for (int userId : allUserHandles) {
17865                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17866                    if (DEBUG_REMOVE) {
17867                        Slog.d(TAG, "    user " + userId + " => " + installed);
17868                    }
17869                    if (installed != ps.getInstalled(userId)) {
17870                        installedStateChanged = true;
17871                    }
17872                    ps.setInstalled(installed, userId);
17873
17874                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17875                }
17876                // Regardless of writeSettings we need to ensure that this restriction
17877                // state propagation is persisted
17878                mSettings.writeAllUsersPackageRestrictionsLPr();
17879                if (installedStateChanged) {
17880                    mSettings.writeKernelMappingLPr(ps);
17881                }
17882            }
17883            // can downgrade to reader here
17884            if (writeSettings) {
17885                mSettings.writeLPr();
17886            }
17887        }
17888        return true;
17889    }
17890
17891    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17892            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17893            PackageRemovedInfo outInfo, boolean writeSettings,
17894            PackageParser.Package replacingPackage) {
17895        synchronized (mPackages) {
17896            if (outInfo != null) {
17897                outInfo.uid = ps.appId;
17898            }
17899
17900            if (outInfo != null && outInfo.removedChildPackages != null) {
17901                final int childCount = (ps.childPackageNames != null)
17902                        ? ps.childPackageNames.size() : 0;
17903                for (int i = 0; i < childCount; i++) {
17904                    String childPackageName = ps.childPackageNames.get(i);
17905                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17906                    if (childPs == null) {
17907                        return false;
17908                    }
17909                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17910                            childPackageName);
17911                    if (childInfo != null) {
17912                        childInfo.uid = childPs.appId;
17913                    }
17914                }
17915            }
17916        }
17917
17918        // Delete package data from internal structures and also remove data if flag is set
17919        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17920
17921        // Delete the child packages data
17922        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17923        for (int i = 0; i < childCount; i++) {
17924            PackageSetting childPs;
17925            synchronized (mPackages) {
17926                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17927            }
17928            if (childPs != null) {
17929                PackageRemovedInfo childOutInfo = (outInfo != null
17930                        && outInfo.removedChildPackages != null)
17931                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17932                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17933                        && (replacingPackage != null
17934                        && !replacingPackage.hasChildPackage(childPs.name))
17935                        ? flags & ~DELETE_KEEP_DATA : flags;
17936                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17937                        deleteFlags, writeSettings);
17938            }
17939        }
17940
17941        // Delete application code and resources only for parent packages
17942        if (ps.parentPackageName == null) {
17943            if (deleteCodeAndResources && (outInfo != null)) {
17944                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17945                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17946                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17947            }
17948        }
17949
17950        return true;
17951    }
17952
17953    @Override
17954    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17955            int userId) {
17956        mContext.enforceCallingOrSelfPermission(
17957                android.Manifest.permission.DELETE_PACKAGES, null);
17958        synchronized (mPackages) {
17959            PackageSetting ps = mSettings.mPackages.get(packageName);
17960            if (ps == null) {
17961                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17962                return false;
17963            }
17964            // Cannot block uninstall of static shared libs as they are
17965            // considered a part of the using app (emulating static linking).
17966            // Also static libs are installed always on internal storage.
17967            PackageParser.Package pkg = mPackages.get(packageName);
17968            if (pkg != null && pkg.staticSharedLibName != null) {
17969                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17970                        + " providing static shared library: " + pkg.staticSharedLibName);
17971                return false;
17972            }
17973            if (!ps.getInstalled(userId)) {
17974                // Can't block uninstall for an app that is not installed or enabled.
17975                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17976                return false;
17977            }
17978            ps.setBlockUninstall(blockUninstall, userId);
17979            mSettings.writePackageRestrictionsLPr(userId);
17980        }
17981        return true;
17982    }
17983
17984    @Override
17985    public boolean getBlockUninstallForUser(String packageName, int userId) {
17986        synchronized (mPackages) {
17987            PackageSetting ps = mSettings.mPackages.get(packageName);
17988            if (ps == null) {
17989                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17990                return false;
17991            }
17992            return ps.getBlockUninstall(userId);
17993        }
17994    }
17995
17996    @Override
17997    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17998        int callingUid = Binder.getCallingUid();
17999        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18000            throw new SecurityException(
18001                    "setRequiredForSystemUser can only be run by the system or root");
18002        }
18003        synchronized (mPackages) {
18004            PackageSetting ps = mSettings.mPackages.get(packageName);
18005            if (ps == null) {
18006                Log.w(TAG, "Package doesn't exist: " + packageName);
18007                return false;
18008            }
18009            if (systemUserApp) {
18010                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18011            } else {
18012                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18013            }
18014            mSettings.writeLPr();
18015        }
18016        return true;
18017    }
18018
18019    /*
18020     * This method handles package deletion in general
18021     */
18022    private boolean deletePackageLIF(String packageName, UserHandle user,
18023            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18024            PackageRemovedInfo outInfo, boolean writeSettings,
18025            PackageParser.Package replacingPackage) {
18026        if (packageName == null) {
18027            Slog.w(TAG, "Attempt to delete null packageName.");
18028            return false;
18029        }
18030
18031        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18032
18033        PackageSetting ps;
18034        synchronized (mPackages) {
18035            ps = mSettings.mPackages.get(packageName);
18036            if (ps == null) {
18037                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18038                return false;
18039            }
18040
18041            if (ps.parentPackageName != null && (!isSystemApp(ps)
18042                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18043                if (DEBUG_REMOVE) {
18044                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18045                            + ((user == null) ? UserHandle.USER_ALL : user));
18046                }
18047                final int removedUserId = (user != null) ? user.getIdentifier()
18048                        : UserHandle.USER_ALL;
18049                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18050                    return false;
18051                }
18052                markPackageUninstalledForUserLPw(ps, user);
18053                scheduleWritePackageRestrictionsLocked(user);
18054                return true;
18055            }
18056        }
18057
18058        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18059                && user.getIdentifier() != UserHandle.USER_ALL)) {
18060            // The caller is asking that the package only be deleted for a single
18061            // user.  To do this, we just mark its uninstalled state and delete
18062            // its data. If this is a system app, we only allow this to happen if
18063            // they have set the special DELETE_SYSTEM_APP which requests different
18064            // semantics than normal for uninstalling system apps.
18065            markPackageUninstalledForUserLPw(ps, user);
18066
18067            if (!isSystemApp(ps)) {
18068                // Do not uninstall the APK if an app should be cached
18069                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18070                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18071                    // Other user still have this package installed, so all
18072                    // we need to do is clear this user's data and save that
18073                    // it is uninstalled.
18074                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18075                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18076                        return false;
18077                    }
18078                    scheduleWritePackageRestrictionsLocked(user);
18079                    return true;
18080                } else {
18081                    // We need to set it back to 'installed' so the uninstall
18082                    // broadcasts will be sent correctly.
18083                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18084                    ps.setInstalled(true, user.getIdentifier());
18085                    mSettings.writeKernelMappingLPr(ps);
18086                }
18087            } else {
18088                // This is a system app, so we assume that the
18089                // other users still have this package installed, so all
18090                // we need to do is clear this user's data and save that
18091                // it is uninstalled.
18092                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18093                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18094                    return false;
18095                }
18096                scheduleWritePackageRestrictionsLocked(user);
18097                return true;
18098            }
18099        }
18100
18101        // If we are deleting a composite package for all users, keep track
18102        // of result for each child.
18103        if (ps.childPackageNames != null && outInfo != null) {
18104            synchronized (mPackages) {
18105                final int childCount = ps.childPackageNames.size();
18106                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18107                for (int i = 0; i < childCount; i++) {
18108                    String childPackageName = ps.childPackageNames.get(i);
18109                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18110                    childInfo.removedPackage = childPackageName;
18111                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18112                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18113                    if (childPs != null) {
18114                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18115                    }
18116                }
18117            }
18118        }
18119
18120        boolean ret = false;
18121        if (isSystemApp(ps)) {
18122            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18123            // When an updated system application is deleted we delete the existing resources
18124            // as well and fall back to existing code in system partition
18125            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18126        } else {
18127            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18128            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18129                    outInfo, writeSettings, replacingPackage);
18130        }
18131
18132        // Take a note whether we deleted the package for all users
18133        if (outInfo != null) {
18134            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18135            if (outInfo.removedChildPackages != null) {
18136                synchronized (mPackages) {
18137                    final int childCount = outInfo.removedChildPackages.size();
18138                    for (int i = 0; i < childCount; i++) {
18139                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18140                        if (childInfo != null) {
18141                            childInfo.removedForAllUsers = mPackages.get(
18142                                    childInfo.removedPackage) == null;
18143                        }
18144                    }
18145                }
18146            }
18147            // If we uninstalled an update to a system app there may be some
18148            // child packages that appeared as they are declared in the system
18149            // app but were not declared in the update.
18150            if (isSystemApp(ps)) {
18151                synchronized (mPackages) {
18152                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18153                    final int childCount = (updatedPs.childPackageNames != null)
18154                            ? updatedPs.childPackageNames.size() : 0;
18155                    for (int i = 0; i < childCount; i++) {
18156                        String childPackageName = updatedPs.childPackageNames.get(i);
18157                        if (outInfo.removedChildPackages == null
18158                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18159                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18160                            if (childPs == null) {
18161                                continue;
18162                            }
18163                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18164                            installRes.name = childPackageName;
18165                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18166                            installRes.pkg = mPackages.get(childPackageName);
18167                            installRes.uid = childPs.pkg.applicationInfo.uid;
18168                            if (outInfo.appearedChildPackages == null) {
18169                                outInfo.appearedChildPackages = new ArrayMap<>();
18170                            }
18171                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18172                        }
18173                    }
18174                }
18175            }
18176        }
18177
18178        return ret;
18179    }
18180
18181    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18182        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18183                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18184        for (int nextUserId : userIds) {
18185            if (DEBUG_REMOVE) {
18186                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18187            }
18188            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18189                    false /*installed*/,
18190                    true /*stopped*/,
18191                    true /*notLaunched*/,
18192                    false /*hidden*/,
18193                    false /*suspended*/,
18194                    false /*instantApp*/,
18195                    null /*lastDisableAppCaller*/,
18196                    null /*enabledComponents*/,
18197                    null /*disabledComponents*/,
18198                    false /*blockUninstall*/,
18199                    ps.readUserState(nextUserId).domainVerificationStatus,
18200                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18201        }
18202        mSettings.writeKernelMappingLPr(ps);
18203    }
18204
18205    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18206            PackageRemovedInfo outInfo) {
18207        final PackageParser.Package pkg;
18208        synchronized (mPackages) {
18209            pkg = mPackages.get(ps.name);
18210        }
18211
18212        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18213                : new int[] {userId};
18214        for (int nextUserId : userIds) {
18215            if (DEBUG_REMOVE) {
18216                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18217                        + nextUserId);
18218            }
18219
18220            destroyAppDataLIF(pkg, userId,
18221                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18222            destroyAppProfilesLIF(pkg, userId);
18223            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18224            schedulePackageCleaning(ps.name, nextUserId, false);
18225            synchronized (mPackages) {
18226                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18227                    scheduleWritePackageRestrictionsLocked(nextUserId);
18228                }
18229                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18230            }
18231        }
18232
18233        if (outInfo != null) {
18234            outInfo.removedPackage = ps.name;
18235            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18236            outInfo.removedAppId = ps.appId;
18237            outInfo.removedUsers = userIds;
18238        }
18239
18240        return true;
18241    }
18242
18243    private final class ClearStorageConnection implements ServiceConnection {
18244        IMediaContainerService mContainerService;
18245
18246        @Override
18247        public void onServiceConnected(ComponentName name, IBinder service) {
18248            synchronized (this) {
18249                mContainerService = IMediaContainerService.Stub
18250                        .asInterface(Binder.allowBlocking(service));
18251                notifyAll();
18252            }
18253        }
18254
18255        @Override
18256        public void onServiceDisconnected(ComponentName name) {
18257        }
18258    }
18259
18260    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18261        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18262
18263        final boolean mounted;
18264        if (Environment.isExternalStorageEmulated()) {
18265            mounted = true;
18266        } else {
18267            final String status = Environment.getExternalStorageState();
18268
18269            mounted = status.equals(Environment.MEDIA_MOUNTED)
18270                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18271        }
18272
18273        if (!mounted) {
18274            return;
18275        }
18276
18277        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18278        int[] users;
18279        if (userId == UserHandle.USER_ALL) {
18280            users = sUserManager.getUserIds();
18281        } else {
18282            users = new int[] { userId };
18283        }
18284        final ClearStorageConnection conn = new ClearStorageConnection();
18285        if (mContext.bindServiceAsUser(
18286                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18287            try {
18288                for (int curUser : users) {
18289                    long timeout = SystemClock.uptimeMillis() + 5000;
18290                    synchronized (conn) {
18291                        long now;
18292                        while (conn.mContainerService == null &&
18293                                (now = SystemClock.uptimeMillis()) < timeout) {
18294                            try {
18295                                conn.wait(timeout - now);
18296                            } catch (InterruptedException e) {
18297                            }
18298                        }
18299                    }
18300                    if (conn.mContainerService == null) {
18301                        return;
18302                    }
18303
18304                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18305                    clearDirectory(conn.mContainerService,
18306                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18307                    if (allData) {
18308                        clearDirectory(conn.mContainerService,
18309                                userEnv.buildExternalStorageAppDataDirs(packageName));
18310                        clearDirectory(conn.mContainerService,
18311                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18312                    }
18313                }
18314            } finally {
18315                mContext.unbindService(conn);
18316            }
18317        }
18318    }
18319
18320    @Override
18321    public void clearApplicationProfileData(String packageName) {
18322        enforceSystemOrRoot("Only the system can clear all profile data");
18323
18324        final PackageParser.Package pkg;
18325        synchronized (mPackages) {
18326            pkg = mPackages.get(packageName);
18327        }
18328
18329        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18330            synchronized (mInstallLock) {
18331                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18332            }
18333        }
18334    }
18335
18336    @Override
18337    public void clearApplicationUserData(final String packageName,
18338            final IPackageDataObserver observer, final int userId) {
18339        mContext.enforceCallingOrSelfPermission(
18340                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18341
18342        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18343                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18344
18345        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18346            throw new SecurityException("Cannot clear data for a protected package: "
18347                    + packageName);
18348        }
18349        // Queue up an async operation since the package deletion may take a little while.
18350        mHandler.post(new Runnable() {
18351            public void run() {
18352                mHandler.removeCallbacks(this);
18353                final boolean succeeded;
18354                try (PackageFreezer freezer = freezePackage(packageName,
18355                        "clearApplicationUserData")) {
18356                    synchronized (mInstallLock) {
18357                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18358                    }
18359                    clearExternalStorageDataSync(packageName, userId, true);
18360                    synchronized (mPackages) {
18361                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18362                                packageName, userId);
18363                    }
18364                }
18365                if (succeeded) {
18366                    // invoke DeviceStorageMonitor's update method to clear any notifications
18367                    DeviceStorageMonitorInternal dsm = LocalServices
18368                            .getService(DeviceStorageMonitorInternal.class);
18369                    if (dsm != null) {
18370                        dsm.checkMemory();
18371                    }
18372                }
18373                if(observer != null) {
18374                    try {
18375                        observer.onRemoveCompleted(packageName, succeeded);
18376                    } catch (RemoteException e) {
18377                        Log.i(TAG, "Observer no longer exists.");
18378                    }
18379                } //end if observer
18380            } //end run
18381        });
18382    }
18383
18384    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18385        if (packageName == null) {
18386            Slog.w(TAG, "Attempt to delete null packageName.");
18387            return false;
18388        }
18389
18390        // Try finding details about the requested package
18391        PackageParser.Package pkg;
18392        synchronized (mPackages) {
18393            pkg = mPackages.get(packageName);
18394            if (pkg == null) {
18395                final PackageSetting ps = mSettings.mPackages.get(packageName);
18396                if (ps != null) {
18397                    pkg = ps.pkg;
18398                }
18399            }
18400
18401            if (pkg == null) {
18402                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18403                return false;
18404            }
18405
18406            PackageSetting ps = (PackageSetting) pkg.mExtras;
18407            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18408        }
18409
18410        clearAppDataLIF(pkg, userId,
18411                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18412
18413        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18414        removeKeystoreDataIfNeeded(userId, appId);
18415
18416        UserManagerInternal umInternal = getUserManagerInternal();
18417        final int flags;
18418        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18419            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18420        } else if (umInternal.isUserRunning(userId)) {
18421            flags = StorageManager.FLAG_STORAGE_DE;
18422        } else {
18423            flags = 0;
18424        }
18425        prepareAppDataContentsLIF(pkg, userId, flags);
18426
18427        return true;
18428    }
18429
18430    /**
18431     * Reverts user permission state changes (permissions and flags) in
18432     * all packages for a given user.
18433     *
18434     * @param userId The device user for which to do a reset.
18435     */
18436    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18437        final int packageCount = mPackages.size();
18438        for (int i = 0; i < packageCount; i++) {
18439            PackageParser.Package pkg = mPackages.valueAt(i);
18440            PackageSetting ps = (PackageSetting) pkg.mExtras;
18441            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18442        }
18443    }
18444
18445    private void resetNetworkPolicies(int userId) {
18446        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18447    }
18448
18449    /**
18450     * Reverts user permission state changes (permissions and flags).
18451     *
18452     * @param ps The package for which to reset.
18453     * @param userId The device user for which to do a reset.
18454     */
18455    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18456            final PackageSetting ps, final int userId) {
18457        if (ps.pkg == null) {
18458            return;
18459        }
18460
18461        // These are flags that can change base on user actions.
18462        final int userSettableMask = FLAG_PERMISSION_USER_SET
18463                | FLAG_PERMISSION_USER_FIXED
18464                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18465                | FLAG_PERMISSION_REVIEW_REQUIRED;
18466
18467        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18468                | FLAG_PERMISSION_POLICY_FIXED;
18469
18470        boolean writeInstallPermissions = false;
18471        boolean writeRuntimePermissions = false;
18472
18473        final int permissionCount = ps.pkg.requestedPermissions.size();
18474        for (int i = 0; i < permissionCount; i++) {
18475            String permission = ps.pkg.requestedPermissions.get(i);
18476
18477            BasePermission bp = mSettings.mPermissions.get(permission);
18478            if (bp == null) {
18479                continue;
18480            }
18481
18482            // If shared user we just reset the state to which only this app contributed.
18483            if (ps.sharedUser != null) {
18484                boolean used = false;
18485                final int packageCount = ps.sharedUser.packages.size();
18486                for (int j = 0; j < packageCount; j++) {
18487                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18488                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18489                            && pkg.pkg.requestedPermissions.contains(permission)) {
18490                        used = true;
18491                        break;
18492                    }
18493                }
18494                if (used) {
18495                    continue;
18496                }
18497            }
18498
18499            PermissionsState permissionsState = ps.getPermissionsState();
18500
18501            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18502
18503            // Always clear the user settable flags.
18504            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18505                    bp.name) != null;
18506            // If permission review is enabled and this is a legacy app, mark the
18507            // permission as requiring a review as this is the initial state.
18508            int flags = 0;
18509            if (mPermissionReviewRequired
18510                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18511                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18512            }
18513            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18514                if (hasInstallState) {
18515                    writeInstallPermissions = true;
18516                } else {
18517                    writeRuntimePermissions = true;
18518                }
18519            }
18520
18521            // Below is only runtime permission handling.
18522            if (!bp.isRuntime()) {
18523                continue;
18524            }
18525
18526            // Never clobber system or policy.
18527            if ((oldFlags & policyOrSystemFlags) != 0) {
18528                continue;
18529            }
18530
18531            // If this permission was granted by default, make sure it is.
18532            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18533                if (permissionsState.grantRuntimePermission(bp, userId)
18534                        != PERMISSION_OPERATION_FAILURE) {
18535                    writeRuntimePermissions = true;
18536                }
18537            // If permission review is enabled the permissions for a legacy apps
18538            // are represented as constantly granted runtime ones, so don't revoke.
18539            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18540                // Otherwise, reset the permission.
18541                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18542                switch (revokeResult) {
18543                    case PERMISSION_OPERATION_SUCCESS:
18544                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18545                        writeRuntimePermissions = true;
18546                        final int appId = ps.appId;
18547                        mHandler.post(new Runnable() {
18548                            @Override
18549                            public void run() {
18550                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18551                            }
18552                        });
18553                    } break;
18554                }
18555            }
18556        }
18557
18558        // Synchronously write as we are taking permissions away.
18559        if (writeRuntimePermissions) {
18560            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18561        }
18562
18563        // Synchronously write as we are taking permissions away.
18564        if (writeInstallPermissions) {
18565            mSettings.writeLPr();
18566        }
18567    }
18568
18569    /**
18570     * Remove entries from the keystore daemon. Will only remove it if the
18571     * {@code appId} is valid.
18572     */
18573    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18574        if (appId < 0) {
18575            return;
18576        }
18577
18578        final KeyStore keyStore = KeyStore.getInstance();
18579        if (keyStore != null) {
18580            if (userId == UserHandle.USER_ALL) {
18581                for (final int individual : sUserManager.getUserIds()) {
18582                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18583                }
18584            } else {
18585                keyStore.clearUid(UserHandle.getUid(userId, appId));
18586            }
18587        } else {
18588            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18589        }
18590    }
18591
18592    @Override
18593    public void deleteApplicationCacheFiles(final String packageName,
18594            final IPackageDataObserver observer) {
18595        final int userId = UserHandle.getCallingUserId();
18596        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18597    }
18598
18599    @Override
18600    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18601            final IPackageDataObserver observer) {
18602        mContext.enforceCallingOrSelfPermission(
18603                android.Manifest.permission.DELETE_CACHE_FILES, null);
18604        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18605                /* requireFullPermission= */ true, /* checkShell= */ false,
18606                "delete application cache files");
18607
18608        final PackageParser.Package pkg;
18609        synchronized (mPackages) {
18610            pkg = mPackages.get(packageName);
18611        }
18612
18613        // Queue up an async operation since the package deletion may take a little while.
18614        mHandler.post(new Runnable() {
18615            public void run() {
18616                synchronized (mInstallLock) {
18617                    final int flags = StorageManager.FLAG_STORAGE_DE
18618                            | StorageManager.FLAG_STORAGE_CE;
18619                    // We're only clearing cache files, so we don't care if the
18620                    // app is unfrozen and still able to run
18621                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18622                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18623                }
18624                clearExternalStorageDataSync(packageName, userId, false);
18625                if (observer != null) {
18626                    try {
18627                        observer.onRemoveCompleted(packageName, true);
18628                    } catch (RemoteException e) {
18629                        Log.i(TAG, "Observer no longer exists.");
18630                    }
18631                }
18632            }
18633        });
18634    }
18635
18636    @Override
18637    public void getPackageSizeInfo(final String packageName, int userHandle,
18638            final IPackageStatsObserver observer) {
18639        throw new UnsupportedOperationException(
18640                "Shame on you for calling a hidden API. Shame!");
18641    }
18642
18643    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18644        final PackageSetting ps;
18645        synchronized (mPackages) {
18646            ps = mSettings.mPackages.get(packageName);
18647            if (ps == null) {
18648                Slog.w(TAG, "Failed to find settings for " + packageName);
18649                return false;
18650            }
18651        }
18652
18653        final String[] packageNames = { packageName };
18654        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18655        final String[] codePaths = { ps.codePathString };
18656
18657        try {
18658            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18659                    ps.appId, ceDataInodes, codePaths, stats);
18660
18661            // For now, ignore code size of packages on system partition
18662            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18663                stats.codeSize = 0;
18664            }
18665
18666            // External clients expect these to be tracked separately
18667            stats.dataSize -= stats.cacheSize;
18668
18669        } catch (InstallerException e) {
18670            Slog.w(TAG, String.valueOf(e));
18671            return false;
18672        }
18673
18674        return true;
18675    }
18676
18677    private int getUidTargetSdkVersionLockedLPr(int uid) {
18678        Object obj = mSettings.getUserIdLPr(uid);
18679        if (obj instanceof SharedUserSetting) {
18680            final SharedUserSetting sus = (SharedUserSetting) obj;
18681            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18682            final Iterator<PackageSetting> it = sus.packages.iterator();
18683            while (it.hasNext()) {
18684                final PackageSetting ps = it.next();
18685                if (ps.pkg != null) {
18686                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18687                    if (v < vers) vers = v;
18688                }
18689            }
18690            return vers;
18691        } else if (obj instanceof PackageSetting) {
18692            final PackageSetting ps = (PackageSetting) obj;
18693            if (ps.pkg != null) {
18694                return ps.pkg.applicationInfo.targetSdkVersion;
18695            }
18696        }
18697        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18698    }
18699
18700    @Override
18701    public void addPreferredActivity(IntentFilter filter, int match,
18702            ComponentName[] set, ComponentName activity, int userId) {
18703        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18704                "Adding preferred");
18705    }
18706
18707    private void addPreferredActivityInternal(IntentFilter filter, int match,
18708            ComponentName[] set, ComponentName activity, boolean always, int userId,
18709            String opname) {
18710        // writer
18711        int callingUid = Binder.getCallingUid();
18712        enforceCrossUserPermission(callingUid, userId,
18713                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18714        if (filter.countActions() == 0) {
18715            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18716            return;
18717        }
18718        synchronized (mPackages) {
18719            if (mContext.checkCallingOrSelfPermission(
18720                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18721                    != PackageManager.PERMISSION_GRANTED) {
18722                if (getUidTargetSdkVersionLockedLPr(callingUid)
18723                        < Build.VERSION_CODES.FROYO) {
18724                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18725                            + callingUid);
18726                    return;
18727                }
18728                mContext.enforceCallingOrSelfPermission(
18729                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18730            }
18731
18732            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18733            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18734                    + userId + ":");
18735            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18736            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18737            scheduleWritePackageRestrictionsLocked(userId);
18738            postPreferredActivityChangedBroadcast(userId);
18739        }
18740    }
18741
18742    private void postPreferredActivityChangedBroadcast(int userId) {
18743        mHandler.post(() -> {
18744            final IActivityManager am = ActivityManager.getService();
18745            if (am == null) {
18746                return;
18747            }
18748
18749            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18750            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18751            try {
18752                am.broadcastIntent(null, intent, null, null,
18753                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18754                        null, false, false, userId);
18755            } catch (RemoteException e) {
18756            }
18757        });
18758    }
18759
18760    @Override
18761    public void replacePreferredActivity(IntentFilter filter, int match,
18762            ComponentName[] set, ComponentName activity, int userId) {
18763        if (filter.countActions() != 1) {
18764            throw new IllegalArgumentException(
18765                    "replacePreferredActivity expects filter to have only 1 action.");
18766        }
18767        if (filter.countDataAuthorities() != 0
18768                || filter.countDataPaths() != 0
18769                || filter.countDataSchemes() > 1
18770                || filter.countDataTypes() != 0) {
18771            throw new IllegalArgumentException(
18772                    "replacePreferredActivity expects filter to have no data authorities, " +
18773                    "paths, or types; and at most one scheme.");
18774        }
18775
18776        final int callingUid = Binder.getCallingUid();
18777        enforceCrossUserPermission(callingUid, userId,
18778                true /* requireFullPermission */, false /* checkShell */,
18779                "replace preferred activity");
18780        synchronized (mPackages) {
18781            if (mContext.checkCallingOrSelfPermission(
18782                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18783                    != PackageManager.PERMISSION_GRANTED) {
18784                if (getUidTargetSdkVersionLockedLPr(callingUid)
18785                        < Build.VERSION_CODES.FROYO) {
18786                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18787                            + Binder.getCallingUid());
18788                    return;
18789                }
18790                mContext.enforceCallingOrSelfPermission(
18791                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18792            }
18793
18794            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18795            if (pir != null) {
18796                // Get all of the existing entries that exactly match this filter.
18797                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18798                if (existing != null && existing.size() == 1) {
18799                    PreferredActivity cur = existing.get(0);
18800                    if (DEBUG_PREFERRED) {
18801                        Slog.i(TAG, "Checking replace of preferred:");
18802                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18803                        if (!cur.mPref.mAlways) {
18804                            Slog.i(TAG, "  -- CUR; not mAlways!");
18805                        } else {
18806                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18807                            Slog.i(TAG, "  -- CUR: mSet="
18808                                    + Arrays.toString(cur.mPref.mSetComponents));
18809                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18810                            Slog.i(TAG, "  -- NEW: mMatch="
18811                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18812                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18813                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18814                        }
18815                    }
18816                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18817                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18818                            && cur.mPref.sameSet(set)) {
18819                        // Setting the preferred activity to what it happens to be already
18820                        if (DEBUG_PREFERRED) {
18821                            Slog.i(TAG, "Replacing with same preferred activity "
18822                                    + cur.mPref.mShortComponent + " for user "
18823                                    + userId + ":");
18824                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18825                        }
18826                        return;
18827                    }
18828                }
18829
18830                if (existing != null) {
18831                    if (DEBUG_PREFERRED) {
18832                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18833                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18834                    }
18835                    for (int i = 0; i < existing.size(); i++) {
18836                        PreferredActivity pa = existing.get(i);
18837                        if (DEBUG_PREFERRED) {
18838                            Slog.i(TAG, "Removing existing preferred activity "
18839                                    + pa.mPref.mComponent + ":");
18840                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18841                        }
18842                        pir.removeFilter(pa);
18843                    }
18844                }
18845            }
18846            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18847                    "Replacing preferred");
18848        }
18849    }
18850
18851    @Override
18852    public void clearPackagePreferredActivities(String packageName) {
18853        final int uid = Binder.getCallingUid();
18854        // writer
18855        synchronized (mPackages) {
18856            PackageParser.Package pkg = mPackages.get(packageName);
18857            if (pkg == null || pkg.applicationInfo.uid != uid) {
18858                if (mContext.checkCallingOrSelfPermission(
18859                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18860                        != PackageManager.PERMISSION_GRANTED) {
18861                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18862                            < Build.VERSION_CODES.FROYO) {
18863                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18864                                + Binder.getCallingUid());
18865                        return;
18866                    }
18867                    mContext.enforceCallingOrSelfPermission(
18868                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18869                }
18870            }
18871
18872            int user = UserHandle.getCallingUserId();
18873            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18874                scheduleWritePackageRestrictionsLocked(user);
18875            }
18876        }
18877    }
18878
18879    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18880    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18881        ArrayList<PreferredActivity> removed = null;
18882        boolean changed = false;
18883        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18884            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18885            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18886            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18887                continue;
18888            }
18889            Iterator<PreferredActivity> it = pir.filterIterator();
18890            while (it.hasNext()) {
18891                PreferredActivity pa = it.next();
18892                // Mark entry for removal only if it matches the package name
18893                // and the entry is of type "always".
18894                if (packageName == null ||
18895                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18896                                && pa.mPref.mAlways)) {
18897                    if (removed == null) {
18898                        removed = new ArrayList<PreferredActivity>();
18899                    }
18900                    removed.add(pa);
18901                }
18902            }
18903            if (removed != null) {
18904                for (int j=0; j<removed.size(); j++) {
18905                    PreferredActivity pa = removed.get(j);
18906                    pir.removeFilter(pa);
18907                }
18908                changed = true;
18909            }
18910        }
18911        if (changed) {
18912            postPreferredActivityChangedBroadcast(userId);
18913        }
18914        return changed;
18915    }
18916
18917    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18918    private void clearIntentFilterVerificationsLPw(int userId) {
18919        final int packageCount = mPackages.size();
18920        for (int i = 0; i < packageCount; i++) {
18921            PackageParser.Package pkg = mPackages.valueAt(i);
18922            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18923        }
18924    }
18925
18926    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18927    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18928        if (userId == UserHandle.USER_ALL) {
18929            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18930                    sUserManager.getUserIds())) {
18931                for (int oneUserId : sUserManager.getUserIds()) {
18932                    scheduleWritePackageRestrictionsLocked(oneUserId);
18933                }
18934            }
18935        } else {
18936            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18937                scheduleWritePackageRestrictionsLocked(userId);
18938            }
18939        }
18940    }
18941
18942    void clearDefaultBrowserIfNeeded(String packageName) {
18943        for (int oneUserId : sUserManager.getUserIds()) {
18944            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18945            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18946            if (packageName.equals(defaultBrowserPackageName)) {
18947                setDefaultBrowserPackageName(null, oneUserId);
18948            }
18949        }
18950    }
18951
18952    @Override
18953    public void resetApplicationPreferences(int userId) {
18954        mContext.enforceCallingOrSelfPermission(
18955                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18956        final long identity = Binder.clearCallingIdentity();
18957        // writer
18958        try {
18959            synchronized (mPackages) {
18960                clearPackagePreferredActivitiesLPw(null, userId);
18961                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18962                // TODO: We have to reset the default SMS and Phone. This requires
18963                // significant refactoring to keep all default apps in the package
18964                // manager (cleaner but more work) or have the services provide
18965                // callbacks to the package manager to request a default app reset.
18966                applyFactoryDefaultBrowserLPw(userId);
18967                clearIntentFilterVerificationsLPw(userId);
18968                primeDomainVerificationsLPw(userId);
18969                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18970                scheduleWritePackageRestrictionsLocked(userId);
18971            }
18972            resetNetworkPolicies(userId);
18973        } finally {
18974            Binder.restoreCallingIdentity(identity);
18975        }
18976    }
18977
18978    @Override
18979    public int getPreferredActivities(List<IntentFilter> outFilters,
18980            List<ComponentName> outActivities, String packageName) {
18981
18982        int num = 0;
18983        final int userId = UserHandle.getCallingUserId();
18984        // reader
18985        synchronized (mPackages) {
18986            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18987            if (pir != null) {
18988                final Iterator<PreferredActivity> it = pir.filterIterator();
18989                while (it.hasNext()) {
18990                    final PreferredActivity pa = it.next();
18991                    if (packageName == null
18992                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18993                                    && pa.mPref.mAlways)) {
18994                        if (outFilters != null) {
18995                            outFilters.add(new IntentFilter(pa));
18996                        }
18997                        if (outActivities != null) {
18998                            outActivities.add(pa.mPref.mComponent);
18999                        }
19000                    }
19001                }
19002            }
19003        }
19004
19005        return num;
19006    }
19007
19008    @Override
19009    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19010            int userId) {
19011        int callingUid = Binder.getCallingUid();
19012        if (callingUid != Process.SYSTEM_UID) {
19013            throw new SecurityException(
19014                    "addPersistentPreferredActivity can only be run by the system");
19015        }
19016        if (filter.countActions() == 0) {
19017            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19018            return;
19019        }
19020        synchronized (mPackages) {
19021            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19022                    ":");
19023            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19024            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19025                    new PersistentPreferredActivity(filter, activity));
19026            scheduleWritePackageRestrictionsLocked(userId);
19027            postPreferredActivityChangedBroadcast(userId);
19028        }
19029    }
19030
19031    @Override
19032    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19033        int callingUid = Binder.getCallingUid();
19034        if (callingUid != Process.SYSTEM_UID) {
19035            throw new SecurityException(
19036                    "clearPackagePersistentPreferredActivities can only be run by the system");
19037        }
19038        ArrayList<PersistentPreferredActivity> removed = null;
19039        boolean changed = false;
19040        synchronized (mPackages) {
19041            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19042                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19043                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19044                        .valueAt(i);
19045                if (userId != thisUserId) {
19046                    continue;
19047                }
19048                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19049                while (it.hasNext()) {
19050                    PersistentPreferredActivity ppa = it.next();
19051                    // Mark entry for removal only if it matches the package name.
19052                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19053                        if (removed == null) {
19054                            removed = new ArrayList<PersistentPreferredActivity>();
19055                        }
19056                        removed.add(ppa);
19057                    }
19058                }
19059                if (removed != null) {
19060                    for (int j=0; j<removed.size(); j++) {
19061                        PersistentPreferredActivity ppa = removed.get(j);
19062                        ppir.removeFilter(ppa);
19063                    }
19064                    changed = true;
19065                }
19066            }
19067
19068            if (changed) {
19069                scheduleWritePackageRestrictionsLocked(userId);
19070                postPreferredActivityChangedBroadcast(userId);
19071            }
19072        }
19073    }
19074
19075    /**
19076     * Common machinery for picking apart a restored XML blob and passing
19077     * it to a caller-supplied functor to be applied to the running system.
19078     */
19079    private void restoreFromXml(XmlPullParser parser, int userId,
19080            String expectedStartTag, BlobXmlRestorer functor)
19081            throws IOException, XmlPullParserException {
19082        int type;
19083        while ((type = parser.next()) != XmlPullParser.START_TAG
19084                && type != XmlPullParser.END_DOCUMENT) {
19085        }
19086        if (type != XmlPullParser.START_TAG) {
19087            // oops didn't find a start tag?!
19088            if (DEBUG_BACKUP) {
19089                Slog.e(TAG, "Didn't find start tag during restore");
19090            }
19091            return;
19092        }
19093Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19094        // this is supposed to be TAG_PREFERRED_BACKUP
19095        if (!expectedStartTag.equals(parser.getName())) {
19096            if (DEBUG_BACKUP) {
19097                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19098            }
19099            return;
19100        }
19101
19102        // skip interfering stuff, then we're aligned with the backing implementation
19103        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19104Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19105        functor.apply(parser, userId);
19106    }
19107
19108    private interface BlobXmlRestorer {
19109        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19110    }
19111
19112    /**
19113     * Non-Binder method, support for the backup/restore mechanism: write the
19114     * full set of preferred activities in its canonical XML format.  Returns the
19115     * XML output as a byte array, or null if there is none.
19116     */
19117    @Override
19118    public byte[] getPreferredActivityBackup(int userId) {
19119        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19120            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19121        }
19122
19123        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19124        try {
19125            final XmlSerializer serializer = new FastXmlSerializer();
19126            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19127            serializer.startDocument(null, true);
19128            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19129
19130            synchronized (mPackages) {
19131                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19132            }
19133
19134            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19135            serializer.endDocument();
19136            serializer.flush();
19137        } catch (Exception e) {
19138            if (DEBUG_BACKUP) {
19139                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19140            }
19141            return null;
19142        }
19143
19144        return dataStream.toByteArray();
19145    }
19146
19147    @Override
19148    public void restorePreferredActivities(byte[] backup, int userId) {
19149        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19150            throw new SecurityException("Only the system may call restorePreferredActivities()");
19151        }
19152
19153        try {
19154            final XmlPullParser parser = Xml.newPullParser();
19155            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19156            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19157                    new BlobXmlRestorer() {
19158                        @Override
19159                        public void apply(XmlPullParser parser, int userId)
19160                                throws XmlPullParserException, IOException {
19161                            synchronized (mPackages) {
19162                                mSettings.readPreferredActivitiesLPw(parser, userId);
19163                            }
19164                        }
19165                    } );
19166        } catch (Exception e) {
19167            if (DEBUG_BACKUP) {
19168                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19169            }
19170        }
19171    }
19172
19173    /**
19174     * Non-Binder method, support for the backup/restore mechanism: write the
19175     * default browser (etc) settings in its canonical XML format.  Returns the default
19176     * browser XML representation as a byte array, or null if there is none.
19177     */
19178    @Override
19179    public byte[] getDefaultAppsBackup(int userId) {
19180        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19181            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19182        }
19183
19184        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19185        try {
19186            final XmlSerializer serializer = new FastXmlSerializer();
19187            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19188            serializer.startDocument(null, true);
19189            serializer.startTag(null, TAG_DEFAULT_APPS);
19190
19191            synchronized (mPackages) {
19192                mSettings.writeDefaultAppsLPr(serializer, userId);
19193            }
19194
19195            serializer.endTag(null, TAG_DEFAULT_APPS);
19196            serializer.endDocument();
19197            serializer.flush();
19198        } catch (Exception e) {
19199            if (DEBUG_BACKUP) {
19200                Slog.e(TAG, "Unable to write default apps for backup", e);
19201            }
19202            return null;
19203        }
19204
19205        return dataStream.toByteArray();
19206    }
19207
19208    @Override
19209    public void restoreDefaultApps(byte[] backup, int userId) {
19210        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19211            throw new SecurityException("Only the system may call restoreDefaultApps()");
19212        }
19213
19214        try {
19215            final XmlPullParser parser = Xml.newPullParser();
19216            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19217            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19218                    new BlobXmlRestorer() {
19219                        @Override
19220                        public void apply(XmlPullParser parser, int userId)
19221                                throws XmlPullParserException, IOException {
19222                            synchronized (mPackages) {
19223                                mSettings.readDefaultAppsLPw(parser, userId);
19224                            }
19225                        }
19226                    } );
19227        } catch (Exception e) {
19228            if (DEBUG_BACKUP) {
19229                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19230            }
19231        }
19232    }
19233
19234    @Override
19235    public byte[] getIntentFilterVerificationBackup(int userId) {
19236        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19237            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19238        }
19239
19240        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19241        try {
19242            final XmlSerializer serializer = new FastXmlSerializer();
19243            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19244            serializer.startDocument(null, true);
19245            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19246
19247            synchronized (mPackages) {
19248                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19249            }
19250
19251            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19252            serializer.endDocument();
19253            serializer.flush();
19254        } catch (Exception e) {
19255            if (DEBUG_BACKUP) {
19256                Slog.e(TAG, "Unable to write default apps for backup", e);
19257            }
19258            return null;
19259        }
19260
19261        return dataStream.toByteArray();
19262    }
19263
19264    @Override
19265    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19266        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19267            throw new SecurityException("Only the system may call restorePreferredActivities()");
19268        }
19269
19270        try {
19271            final XmlPullParser parser = Xml.newPullParser();
19272            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19273            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19274                    new BlobXmlRestorer() {
19275                        @Override
19276                        public void apply(XmlPullParser parser, int userId)
19277                                throws XmlPullParserException, IOException {
19278                            synchronized (mPackages) {
19279                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19280                                mSettings.writeLPr();
19281                            }
19282                        }
19283                    } );
19284        } catch (Exception e) {
19285            if (DEBUG_BACKUP) {
19286                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19287            }
19288        }
19289    }
19290
19291    @Override
19292    public byte[] getPermissionGrantBackup(int userId) {
19293        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19294            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19295        }
19296
19297        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19298        try {
19299            final XmlSerializer serializer = new FastXmlSerializer();
19300            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19301            serializer.startDocument(null, true);
19302            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19303
19304            synchronized (mPackages) {
19305                serializeRuntimePermissionGrantsLPr(serializer, userId);
19306            }
19307
19308            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19309            serializer.endDocument();
19310            serializer.flush();
19311        } catch (Exception e) {
19312            if (DEBUG_BACKUP) {
19313                Slog.e(TAG, "Unable to write default apps for backup", e);
19314            }
19315            return null;
19316        }
19317
19318        return dataStream.toByteArray();
19319    }
19320
19321    @Override
19322    public void restorePermissionGrants(byte[] backup, int userId) {
19323        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19324            throw new SecurityException("Only the system may call restorePermissionGrants()");
19325        }
19326
19327        try {
19328            final XmlPullParser parser = Xml.newPullParser();
19329            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19330            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19331                    new BlobXmlRestorer() {
19332                        @Override
19333                        public void apply(XmlPullParser parser, int userId)
19334                                throws XmlPullParserException, IOException {
19335                            synchronized (mPackages) {
19336                                processRestoredPermissionGrantsLPr(parser, userId);
19337                            }
19338                        }
19339                    } );
19340        } catch (Exception e) {
19341            if (DEBUG_BACKUP) {
19342                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19343            }
19344        }
19345    }
19346
19347    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19348            throws IOException {
19349        serializer.startTag(null, TAG_ALL_GRANTS);
19350
19351        final int N = mSettings.mPackages.size();
19352        for (int i = 0; i < N; i++) {
19353            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19354            boolean pkgGrantsKnown = false;
19355
19356            PermissionsState packagePerms = ps.getPermissionsState();
19357
19358            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19359                final int grantFlags = state.getFlags();
19360                // only look at grants that are not system/policy fixed
19361                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19362                    final boolean isGranted = state.isGranted();
19363                    // And only back up the user-twiddled state bits
19364                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19365                        final String packageName = mSettings.mPackages.keyAt(i);
19366                        if (!pkgGrantsKnown) {
19367                            serializer.startTag(null, TAG_GRANT);
19368                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19369                            pkgGrantsKnown = true;
19370                        }
19371
19372                        final boolean userSet =
19373                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19374                        final boolean userFixed =
19375                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19376                        final boolean revoke =
19377                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19378
19379                        serializer.startTag(null, TAG_PERMISSION);
19380                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19381                        if (isGranted) {
19382                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19383                        }
19384                        if (userSet) {
19385                            serializer.attribute(null, ATTR_USER_SET, "true");
19386                        }
19387                        if (userFixed) {
19388                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19389                        }
19390                        if (revoke) {
19391                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19392                        }
19393                        serializer.endTag(null, TAG_PERMISSION);
19394                    }
19395                }
19396            }
19397
19398            if (pkgGrantsKnown) {
19399                serializer.endTag(null, TAG_GRANT);
19400            }
19401        }
19402
19403        serializer.endTag(null, TAG_ALL_GRANTS);
19404    }
19405
19406    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19407            throws XmlPullParserException, IOException {
19408        String pkgName = null;
19409        int outerDepth = parser.getDepth();
19410        int type;
19411        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19412                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19413            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19414                continue;
19415            }
19416
19417            final String tagName = parser.getName();
19418            if (tagName.equals(TAG_GRANT)) {
19419                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19420                if (DEBUG_BACKUP) {
19421                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19422                }
19423            } else if (tagName.equals(TAG_PERMISSION)) {
19424
19425                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19426                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19427
19428                int newFlagSet = 0;
19429                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19430                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19431                }
19432                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19433                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19434                }
19435                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19436                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19437                }
19438                if (DEBUG_BACKUP) {
19439                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19440                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19441                }
19442                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19443                if (ps != null) {
19444                    // Already installed so we apply the grant immediately
19445                    if (DEBUG_BACKUP) {
19446                        Slog.v(TAG, "        + already installed; applying");
19447                    }
19448                    PermissionsState perms = ps.getPermissionsState();
19449                    BasePermission bp = mSettings.mPermissions.get(permName);
19450                    if (bp != null) {
19451                        if (isGranted) {
19452                            perms.grantRuntimePermission(bp, userId);
19453                        }
19454                        if (newFlagSet != 0) {
19455                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19456                        }
19457                    }
19458                } else {
19459                    // Need to wait for post-restore install to apply the grant
19460                    if (DEBUG_BACKUP) {
19461                        Slog.v(TAG, "        - not yet installed; saving for later");
19462                    }
19463                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19464                            isGranted, newFlagSet, userId);
19465                }
19466            } else {
19467                PackageManagerService.reportSettingsProblem(Log.WARN,
19468                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19469                XmlUtils.skipCurrentTag(parser);
19470            }
19471        }
19472
19473        scheduleWriteSettingsLocked();
19474        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19475    }
19476
19477    @Override
19478    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19479            int sourceUserId, int targetUserId, int flags) {
19480        mContext.enforceCallingOrSelfPermission(
19481                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19482        int callingUid = Binder.getCallingUid();
19483        enforceOwnerRights(ownerPackage, callingUid);
19484        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19485        if (intentFilter.countActions() == 0) {
19486            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19487            return;
19488        }
19489        synchronized (mPackages) {
19490            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19491                    ownerPackage, targetUserId, flags);
19492            CrossProfileIntentResolver resolver =
19493                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19494            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19495            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19496            if (existing != null) {
19497                int size = existing.size();
19498                for (int i = 0; i < size; i++) {
19499                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19500                        return;
19501                    }
19502                }
19503            }
19504            resolver.addFilter(newFilter);
19505            scheduleWritePackageRestrictionsLocked(sourceUserId);
19506        }
19507    }
19508
19509    @Override
19510    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19511        mContext.enforceCallingOrSelfPermission(
19512                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19513        int callingUid = Binder.getCallingUid();
19514        enforceOwnerRights(ownerPackage, callingUid);
19515        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19516        synchronized (mPackages) {
19517            CrossProfileIntentResolver resolver =
19518                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19519            ArraySet<CrossProfileIntentFilter> set =
19520                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19521            for (CrossProfileIntentFilter filter : set) {
19522                if (filter.getOwnerPackage().equals(ownerPackage)) {
19523                    resolver.removeFilter(filter);
19524                }
19525            }
19526            scheduleWritePackageRestrictionsLocked(sourceUserId);
19527        }
19528    }
19529
19530    // Enforcing that callingUid is owning pkg on userId
19531    private void enforceOwnerRights(String pkg, int callingUid) {
19532        // The system owns everything.
19533        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19534            return;
19535        }
19536        int callingUserId = UserHandle.getUserId(callingUid);
19537        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19538        if (pi == null) {
19539            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19540                    + callingUserId);
19541        }
19542        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19543            throw new SecurityException("Calling uid " + callingUid
19544                    + " does not own package " + pkg);
19545        }
19546    }
19547
19548    @Override
19549    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19550        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19551    }
19552
19553    /**
19554     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19555     * then reports the most likely home activity or null if there are more than one.
19556     */
19557    public ComponentName getDefaultHomeActivity(int userId) {
19558        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19559        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19560        if (cn != null) {
19561            return cn;
19562        }
19563
19564        // Find the launcher with the highest priority and return that component if there are no
19565        // other home activity with the same priority.
19566        int lastPriority = Integer.MIN_VALUE;
19567        ComponentName lastComponent = null;
19568        final int size = allHomeCandidates.size();
19569        for (int i = 0; i < size; i++) {
19570            final ResolveInfo ri = allHomeCandidates.get(i);
19571            if (ri.priority > lastPriority) {
19572                lastComponent = ri.activityInfo.getComponentName();
19573                lastPriority = ri.priority;
19574            } else if (ri.priority == lastPriority) {
19575                // Two components found with same priority.
19576                lastComponent = null;
19577            }
19578        }
19579        return lastComponent;
19580    }
19581
19582    private Intent getHomeIntent() {
19583        Intent intent = new Intent(Intent.ACTION_MAIN);
19584        intent.addCategory(Intent.CATEGORY_HOME);
19585        intent.addCategory(Intent.CATEGORY_DEFAULT);
19586        return intent;
19587    }
19588
19589    private IntentFilter getHomeFilter() {
19590        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19591        filter.addCategory(Intent.CATEGORY_HOME);
19592        filter.addCategory(Intent.CATEGORY_DEFAULT);
19593        return filter;
19594    }
19595
19596    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19597            int userId) {
19598        Intent intent  = getHomeIntent();
19599        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19600                PackageManager.GET_META_DATA, userId);
19601        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19602                true, false, false, userId);
19603
19604        allHomeCandidates.clear();
19605        if (list != null) {
19606            for (ResolveInfo ri : list) {
19607                allHomeCandidates.add(ri);
19608            }
19609        }
19610        return (preferred == null || preferred.activityInfo == null)
19611                ? null
19612                : new ComponentName(preferred.activityInfo.packageName,
19613                        preferred.activityInfo.name);
19614    }
19615
19616    @Override
19617    public void setHomeActivity(ComponentName comp, int userId) {
19618        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19619        getHomeActivitiesAsUser(homeActivities, userId);
19620
19621        boolean found = false;
19622
19623        final int size = homeActivities.size();
19624        final ComponentName[] set = new ComponentName[size];
19625        for (int i = 0; i < size; i++) {
19626            final ResolveInfo candidate = homeActivities.get(i);
19627            final ActivityInfo info = candidate.activityInfo;
19628            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19629            set[i] = activityName;
19630            if (!found && activityName.equals(comp)) {
19631                found = true;
19632            }
19633        }
19634        if (!found) {
19635            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19636                    + userId);
19637        }
19638        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19639                set, comp, userId);
19640    }
19641
19642    private @Nullable String getSetupWizardPackageName() {
19643        final Intent intent = new Intent(Intent.ACTION_MAIN);
19644        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19645
19646        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19647                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19648                        | MATCH_DISABLED_COMPONENTS,
19649                UserHandle.myUserId());
19650        if (matches.size() == 1) {
19651            return matches.get(0).getComponentInfo().packageName;
19652        } else {
19653            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19654                    + ": matches=" + matches);
19655            return null;
19656        }
19657    }
19658
19659    private @Nullable String getStorageManagerPackageName() {
19660        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19661
19662        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19663                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19664                        | MATCH_DISABLED_COMPONENTS,
19665                UserHandle.myUserId());
19666        if (matches.size() == 1) {
19667            return matches.get(0).getComponentInfo().packageName;
19668        } else {
19669            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19670                    + matches.size() + ": matches=" + matches);
19671            return null;
19672        }
19673    }
19674
19675    @Override
19676    public void setApplicationEnabledSetting(String appPackageName,
19677            int newState, int flags, int userId, String callingPackage) {
19678        if (!sUserManager.exists(userId)) return;
19679        if (callingPackage == null) {
19680            callingPackage = Integer.toString(Binder.getCallingUid());
19681        }
19682        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19683    }
19684
19685    @Override
19686    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19687        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19688        synchronized (mPackages) {
19689            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19690            if (pkgSetting != null) {
19691                pkgSetting.setUpdateAvailable(updateAvailable);
19692            }
19693        }
19694    }
19695
19696    @Override
19697    public void setComponentEnabledSetting(ComponentName componentName,
19698            int newState, int flags, int userId) {
19699        if (!sUserManager.exists(userId)) return;
19700        setEnabledSetting(componentName.getPackageName(),
19701                componentName.getClassName(), newState, flags, userId, null);
19702    }
19703
19704    private void setEnabledSetting(final String packageName, String className, int newState,
19705            final int flags, int userId, String callingPackage) {
19706        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19707              || newState == COMPONENT_ENABLED_STATE_ENABLED
19708              || newState == COMPONENT_ENABLED_STATE_DISABLED
19709              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19710              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19711            throw new IllegalArgumentException("Invalid new component state: "
19712                    + newState);
19713        }
19714        PackageSetting pkgSetting;
19715        final int uid = Binder.getCallingUid();
19716        final int permission;
19717        if (uid == Process.SYSTEM_UID) {
19718            permission = PackageManager.PERMISSION_GRANTED;
19719        } else {
19720            permission = mContext.checkCallingOrSelfPermission(
19721                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19722        }
19723        enforceCrossUserPermission(uid, userId,
19724                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19725        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19726        boolean sendNow = false;
19727        boolean isApp = (className == null);
19728        String componentName = isApp ? packageName : className;
19729        int packageUid = -1;
19730        ArrayList<String> components;
19731
19732        // writer
19733        synchronized (mPackages) {
19734            pkgSetting = mSettings.mPackages.get(packageName);
19735            if (pkgSetting == null) {
19736                if (className == null) {
19737                    throw new IllegalArgumentException("Unknown package: " + packageName);
19738                }
19739                throw new IllegalArgumentException(
19740                        "Unknown component: " + packageName + "/" + className);
19741            }
19742        }
19743
19744        // Limit who can change which apps
19745        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19746            // Don't allow apps that don't have permission to modify other apps
19747            if (!allowedByPermission) {
19748                throw new SecurityException(
19749                        "Permission Denial: attempt to change component state from pid="
19750                        + Binder.getCallingPid()
19751                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19752            }
19753            // Don't allow changing protected packages.
19754            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19755                throw new SecurityException("Cannot disable a protected package: " + packageName);
19756            }
19757        }
19758
19759        synchronized (mPackages) {
19760            if (uid == Process.SHELL_UID
19761                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19762                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19763                // unless it is a test package.
19764                int oldState = pkgSetting.getEnabled(userId);
19765                if (className == null
19766                    &&
19767                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19768                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19769                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19770                    &&
19771                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19772                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19773                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19774                    // ok
19775                } else {
19776                    throw new SecurityException(
19777                            "Shell cannot change component state for " + packageName + "/"
19778                            + className + " to " + newState);
19779                }
19780            }
19781            if (className == null) {
19782                // We're dealing with an application/package level state change
19783                if (pkgSetting.getEnabled(userId) == newState) {
19784                    // Nothing to do
19785                    return;
19786                }
19787                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19788                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19789                    // Don't care about who enables an app.
19790                    callingPackage = null;
19791                }
19792                pkgSetting.setEnabled(newState, userId, callingPackage);
19793                // pkgSetting.pkg.mSetEnabled = newState;
19794            } else {
19795                // We're dealing with a component level state change
19796                // First, verify that this is a valid class name.
19797                PackageParser.Package pkg = pkgSetting.pkg;
19798                if (pkg == null || !pkg.hasComponentClassName(className)) {
19799                    if (pkg != null &&
19800                            pkg.applicationInfo.targetSdkVersion >=
19801                                    Build.VERSION_CODES.JELLY_BEAN) {
19802                        throw new IllegalArgumentException("Component class " + className
19803                                + " does not exist in " + packageName);
19804                    } else {
19805                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19806                                + className + " does not exist in " + packageName);
19807                    }
19808                }
19809                switch (newState) {
19810                case COMPONENT_ENABLED_STATE_ENABLED:
19811                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19812                        return;
19813                    }
19814                    break;
19815                case COMPONENT_ENABLED_STATE_DISABLED:
19816                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19817                        return;
19818                    }
19819                    break;
19820                case COMPONENT_ENABLED_STATE_DEFAULT:
19821                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19822                        return;
19823                    }
19824                    break;
19825                default:
19826                    Slog.e(TAG, "Invalid new component state: " + newState);
19827                    return;
19828                }
19829            }
19830            scheduleWritePackageRestrictionsLocked(userId);
19831            updateSequenceNumberLP(packageName, new int[] { userId });
19832            components = mPendingBroadcasts.get(userId, packageName);
19833            final boolean newPackage = components == null;
19834            if (newPackage) {
19835                components = new ArrayList<String>();
19836            }
19837            if (!components.contains(componentName)) {
19838                components.add(componentName);
19839            }
19840            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19841                sendNow = true;
19842                // Purge entry from pending broadcast list if another one exists already
19843                // since we are sending one right away.
19844                mPendingBroadcasts.remove(userId, packageName);
19845            } else {
19846                if (newPackage) {
19847                    mPendingBroadcasts.put(userId, packageName, components);
19848                }
19849                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19850                    // Schedule a message
19851                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19852                }
19853            }
19854        }
19855
19856        long callingId = Binder.clearCallingIdentity();
19857        try {
19858            if (sendNow) {
19859                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19860                sendPackageChangedBroadcast(packageName,
19861                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19862            }
19863        } finally {
19864            Binder.restoreCallingIdentity(callingId);
19865        }
19866    }
19867
19868    @Override
19869    public void flushPackageRestrictionsAsUser(int userId) {
19870        if (!sUserManager.exists(userId)) {
19871            return;
19872        }
19873        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19874                false /* checkShell */, "flushPackageRestrictions");
19875        synchronized (mPackages) {
19876            mSettings.writePackageRestrictionsLPr(userId);
19877            mDirtyUsers.remove(userId);
19878            if (mDirtyUsers.isEmpty()) {
19879                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19880            }
19881        }
19882    }
19883
19884    private void sendPackageChangedBroadcast(String packageName,
19885            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19886        if (DEBUG_INSTALL)
19887            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19888                    + componentNames);
19889        Bundle extras = new Bundle(4);
19890        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19891        String nameList[] = new String[componentNames.size()];
19892        componentNames.toArray(nameList);
19893        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19894        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19895        extras.putInt(Intent.EXTRA_UID, packageUid);
19896        // If this is not reporting a change of the overall package, then only send it
19897        // to registered receivers.  We don't want to launch a swath of apps for every
19898        // little component state change.
19899        final int flags = !componentNames.contains(packageName)
19900                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19901        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19902                new int[] {UserHandle.getUserId(packageUid)});
19903    }
19904
19905    @Override
19906    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19907        if (!sUserManager.exists(userId)) return;
19908        final int uid = Binder.getCallingUid();
19909        final int permission = mContext.checkCallingOrSelfPermission(
19910                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19911        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19912        enforceCrossUserPermission(uid, userId,
19913                true /* requireFullPermission */, true /* checkShell */, "stop package");
19914        // writer
19915        synchronized (mPackages) {
19916            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19917                    allowedByPermission, uid, userId)) {
19918                scheduleWritePackageRestrictionsLocked(userId);
19919            }
19920        }
19921    }
19922
19923    @Override
19924    public String getInstallerPackageName(String packageName) {
19925        // reader
19926        synchronized (mPackages) {
19927            return mSettings.getInstallerPackageNameLPr(packageName);
19928        }
19929    }
19930
19931    public boolean isOrphaned(String packageName) {
19932        // reader
19933        synchronized (mPackages) {
19934            return mSettings.isOrphaned(packageName);
19935        }
19936    }
19937
19938    @Override
19939    public int getApplicationEnabledSetting(String packageName, int userId) {
19940        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19941        int uid = Binder.getCallingUid();
19942        enforceCrossUserPermission(uid, userId,
19943                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19944        // reader
19945        synchronized (mPackages) {
19946            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19947        }
19948    }
19949
19950    @Override
19951    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19952        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19953        int uid = Binder.getCallingUid();
19954        enforceCrossUserPermission(uid, userId,
19955                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19956        // reader
19957        synchronized (mPackages) {
19958            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19959        }
19960    }
19961
19962    @Override
19963    public void enterSafeMode() {
19964        enforceSystemOrRoot("Only the system can request entering safe mode");
19965
19966        if (!mSystemReady) {
19967            mSafeMode = true;
19968        }
19969    }
19970
19971    @Override
19972    public void systemReady() {
19973        mSystemReady = true;
19974
19975        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19976        // disabled after already being started.
19977        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19978                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19979
19980        // Read the compatibilty setting when the system is ready.
19981        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19982                mContext.getContentResolver(),
19983                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19984        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19985        if (DEBUG_SETTINGS) {
19986            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19987        }
19988
19989        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19990
19991        synchronized (mPackages) {
19992            // Verify that all of the preferred activity components actually
19993            // exist.  It is possible for applications to be updated and at
19994            // that point remove a previously declared activity component that
19995            // had been set as a preferred activity.  We try to clean this up
19996            // the next time we encounter that preferred activity, but it is
19997            // possible for the user flow to never be able to return to that
19998            // situation so here we do a sanity check to make sure we haven't
19999            // left any junk around.
20000            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20001            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20002                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20003                removed.clear();
20004                for (PreferredActivity pa : pir.filterSet()) {
20005                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20006                        removed.add(pa);
20007                    }
20008                }
20009                if (removed.size() > 0) {
20010                    for (int r=0; r<removed.size(); r++) {
20011                        PreferredActivity pa = removed.get(r);
20012                        Slog.w(TAG, "Removing dangling preferred activity: "
20013                                + pa.mPref.mComponent);
20014                        pir.removeFilter(pa);
20015                    }
20016                    mSettings.writePackageRestrictionsLPr(
20017                            mSettings.mPreferredActivities.keyAt(i));
20018                }
20019            }
20020
20021            for (int userId : UserManagerService.getInstance().getUserIds()) {
20022                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20023                    grantPermissionsUserIds = ArrayUtils.appendInt(
20024                            grantPermissionsUserIds, userId);
20025                }
20026            }
20027        }
20028        sUserManager.systemReady();
20029
20030        // If we upgraded grant all default permissions before kicking off.
20031        for (int userId : grantPermissionsUserIds) {
20032            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20033        }
20034
20035        // If we did not grant default permissions, we preload from this the
20036        // default permission exceptions lazily to ensure we don't hit the
20037        // disk on a new user creation.
20038        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20039            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20040        }
20041
20042        // Kick off any messages waiting for system ready
20043        if (mPostSystemReadyMessages != null) {
20044            for (Message msg : mPostSystemReadyMessages) {
20045                msg.sendToTarget();
20046            }
20047            mPostSystemReadyMessages = null;
20048        }
20049
20050        // Watch for external volumes that come and go over time
20051        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20052        storage.registerListener(mStorageListener);
20053
20054        mInstallerService.systemReady();
20055        mPackageDexOptimizer.systemReady();
20056
20057        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20058                StorageManagerInternal.class);
20059        StorageManagerInternal.addExternalStoragePolicy(
20060                new StorageManagerInternal.ExternalStorageMountPolicy() {
20061            @Override
20062            public int getMountMode(int uid, String packageName) {
20063                if (Process.isIsolated(uid)) {
20064                    return Zygote.MOUNT_EXTERNAL_NONE;
20065                }
20066                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20067                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20068                }
20069                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20070                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20071                }
20072                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20073                    return Zygote.MOUNT_EXTERNAL_READ;
20074                }
20075                return Zygote.MOUNT_EXTERNAL_WRITE;
20076            }
20077
20078            @Override
20079            public boolean hasExternalStorage(int uid, String packageName) {
20080                return true;
20081            }
20082        });
20083
20084        // Now that we're mostly running, clean up stale users and apps
20085        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20086        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20087
20088        if (mPrivappPermissionsViolations != null) {
20089            Slog.wtf(TAG,"Signature|privileged permissions not in "
20090                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20091            mPrivappPermissionsViolations = null;
20092        }
20093    }
20094
20095    public void waitForAppDataPrepared() {
20096        if (mPrepareAppDataFuture == null) {
20097            return;
20098        }
20099        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20100        mPrepareAppDataFuture = null;
20101    }
20102
20103    @Override
20104    public boolean isSafeMode() {
20105        return mSafeMode;
20106    }
20107
20108    @Override
20109    public boolean hasSystemUidErrors() {
20110        return mHasSystemUidErrors;
20111    }
20112
20113    static String arrayToString(int[] array) {
20114        StringBuffer buf = new StringBuffer(128);
20115        buf.append('[');
20116        if (array != null) {
20117            for (int i=0; i<array.length; i++) {
20118                if (i > 0) buf.append(", ");
20119                buf.append(array[i]);
20120            }
20121        }
20122        buf.append(']');
20123        return buf.toString();
20124    }
20125
20126    static class DumpState {
20127        public static final int DUMP_LIBS = 1 << 0;
20128        public static final int DUMP_FEATURES = 1 << 1;
20129        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20130        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20131        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20132        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20133        public static final int DUMP_PERMISSIONS = 1 << 6;
20134        public static final int DUMP_PACKAGES = 1 << 7;
20135        public static final int DUMP_SHARED_USERS = 1 << 8;
20136        public static final int DUMP_MESSAGES = 1 << 9;
20137        public static final int DUMP_PROVIDERS = 1 << 10;
20138        public static final int DUMP_VERIFIERS = 1 << 11;
20139        public static final int DUMP_PREFERRED = 1 << 12;
20140        public static final int DUMP_PREFERRED_XML = 1 << 13;
20141        public static final int DUMP_KEYSETS = 1 << 14;
20142        public static final int DUMP_VERSION = 1 << 15;
20143        public static final int DUMP_INSTALLS = 1 << 16;
20144        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20145        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20146        public static final int DUMP_FROZEN = 1 << 19;
20147        public static final int DUMP_DEXOPT = 1 << 20;
20148        public static final int DUMP_COMPILER_STATS = 1 << 21;
20149        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20150
20151        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20152
20153        private int mTypes;
20154
20155        private int mOptions;
20156
20157        private boolean mTitlePrinted;
20158
20159        private SharedUserSetting mSharedUser;
20160
20161        public boolean isDumping(int type) {
20162            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20163                return true;
20164            }
20165
20166            return (mTypes & type) != 0;
20167        }
20168
20169        public void setDump(int type) {
20170            mTypes |= type;
20171        }
20172
20173        public boolean isOptionEnabled(int option) {
20174            return (mOptions & option) != 0;
20175        }
20176
20177        public void setOptionEnabled(int option) {
20178            mOptions |= option;
20179        }
20180
20181        public boolean onTitlePrinted() {
20182            final boolean printed = mTitlePrinted;
20183            mTitlePrinted = true;
20184            return printed;
20185        }
20186
20187        public boolean getTitlePrinted() {
20188            return mTitlePrinted;
20189        }
20190
20191        public void setTitlePrinted(boolean enabled) {
20192            mTitlePrinted = enabled;
20193        }
20194
20195        public SharedUserSetting getSharedUser() {
20196            return mSharedUser;
20197        }
20198
20199        public void setSharedUser(SharedUserSetting user) {
20200            mSharedUser = user;
20201        }
20202    }
20203
20204    @Override
20205    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20206            FileDescriptor err, String[] args, ShellCallback callback,
20207            ResultReceiver resultReceiver) {
20208        (new PackageManagerShellCommand(this)).exec(
20209                this, in, out, err, args, callback, resultReceiver);
20210    }
20211
20212    @Override
20213    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20214        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20215                != PackageManager.PERMISSION_GRANTED) {
20216            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20217                    + Binder.getCallingPid()
20218                    + ", uid=" + Binder.getCallingUid()
20219                    + " without permission "
20220                    + android.Manifest.permission.DUMP);
20221            return;
20222        }
20223
20224        DumpState dumpState = new DumpState();
20225        boolean fullPreferred = false;
20226        boolean checkin = false;
20227
20228        String packageName = null;
20229        ArraySet<String> permissionNames = null;
20230
20231        int opti = 0;
20232        while (opti < args.length) {
20233            String opt = args[opti];
20234            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20235                break;
20236            }
20237            opti++;
20238
20239            if ("-a".equals(opt)) {
20240                // Right now we only know how to print all.
20241            } else if ("-h".equals(opt)) {
20242                pw.println("Package manager dump options:");
20243                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20244                pw.println("    --checkin: dump for a checkin");
20245                pw.println("    -f: print details of intent filters");
20246                pw.println("    -h: print this help");
20247                pw.println("  cmd may be one of:");
20248                pw.println("    l[ibraries]: list known shared libraries");
20249                pw.println("    f[eatures]: list device features");
20250                pw.println("    k[eysets]: print known keysets");
20251                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20252                pw.println("    perm[issions]: dump permissions");
20253                pw.println("    permission [name ...]: dump declaration and use of given permission");
20254                pw.println("    pref[erred]: print preferred package settings");
20255                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20256                pw.println("    prov[iders]: dump content providers");
20257                pw.println("    p[ackages]: dump installed packages");
20258                pw.println("    s[hared-users]: dump shared user IDs");
20259                pw.println("    m[essages]: print collected runtime messages");
20260                pw.println("    v[erifiers]: print package verifier info");
20261                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20262                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20263                pw.println("    version: print database version info");
20264                pw.println("    write: write current settings now");
20265                pw.println("    installs: details about install sessions");
20266                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20267                pw.println("    dexopt: dump dexopt state");
20268                pw.println("    compiler-stats: dump compiler statistics");
20269                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20270                pw.println("    <package.name>: info about given package");
20271                return;
20272            } else if ("--checkin".equals(opt)) {
20273                checkin = true;
20274            } else if ("-f".equals(opt)) {
20275                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20276            } else if ("--proto".equals(opt)) {
20277                dumpProto(fd);
20278                return;
20279            } else {
20280                pw.println("Unknown argument: " + opt + "; use -h for help");
20281            }
20282        }
20283
20284        // Is the caller requesting to dump a particular piece of data?
20285        if (opti < args.length) {
20286            String cmd = args[opti];
20287            opti++;
20288            // Is this a package name?
20289            if ("android".equals(cmd) || cmd.contains(".")) {
20290                packageName = cmd;
20291                // When dumping a single package, we always dump all of its
20292                // filter information since the amount of data will be reasonable.
20293                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20294            } else if ("check-permission".equals(cmd)) {
20295                if (opti >= args.length) {
20296                    pw.println("Error: check-permission missing permission argument");
20297                    return;
20298                }
20299                String perm = args[opti];
20300                opti++;
20301                if (opti >= args.length) {
20302                    pw.println("Error: check-permission missing package argument");
20303                    return;
20304                }
20305
20306                String pkg = args[opti];
20307                opti++;
20308                int user = UserHandle.getUserId(Binder.getCallingUid());
20309                if (opti < args.length) {
20310                    try {
20311                        user = Integer.parseInt(args[opti]);
20312                    } catch (NumberFormatException e) {
20313                        pw.println("Error: check-permission user argument is not a number: "
20314                                + args[opti]);
20315                        return;
20316                    }
20317                }
20318
20319                // Normalize package name to handle renamed packages and static libs
20320                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20321
20322                pw.println(checkPermission(perm, pkg, user));
20323                return;
20324            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20325                dumpState.setDump(DumpState.DUMP_LIBS);
20326            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20327                dumpState.setDump(DumpState.DUMP_FEATURES);
20328            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20329                if (opti >= args.length) {
20330                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20331                            | DumpState.DUMP_SERVICE_RESOLVERS
20332                            | DumpState.DUMP_RECEIVER_RESOLVERS
20333                            | DumpState.DUMP_CONTENT_RESOLVERS);
20334                } else {
20335                    while (opti < args.length) {
20336                        String name = args[opti];
20337                        if ("a".equals(name) || "activity".equals(name)) {
20338                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20339                        } else if ("s".equals(name) || "service".equals(name)) {
20340                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20341                        } else if ("r".equals(name) || "receiver".equals(name)) {
20342                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20343                        } else if ("c".equals(name) || "content".equals(name)) {
20344                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20345                        } else {
20346                            pw.println("Error: unknown resolver table type: " + name);
20347                            return;
20348                        }
20349                        opti++;
20350                    }
20351                }
20352            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20353                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20354            } else if ("permission".equals(cmd)) {
20355                if (opti >= args.length) {
20356                    pw.println("Error: permission requires permission name");
20357                    return;
20358                }
20359                permissionNames = new ArraySet<>();
20360                while (opti < args.length) {
20361                    permissionNames.add(args[opti]);
20362                    opti++;
20363                }
20364                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20365                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20366            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20367                dumpState.setDump(DumpState.DUMP_PREFERRED);
20368            } else if ("preferred-xml".equals(cmd)) {
20369                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20370                if (opti < args.length && "--full".equals(args[opti])) {
20371                    fullPreferred = true;
20372                    opti++;
20373                }
20374            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20375                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20376            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20377                dumpState.setDump(DumpState.DUMP_PACKAGES);
20378            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20379                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20380            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20381                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20382            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20383                dumpState.setDump(DumpState.DUMP_MESSAGES);
20384            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20385                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20386            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20387                    || "intent-filter-verifiers".equals(cmd)) {
20388                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20389            } else if ("version".equals(cmd)) {
20390                dumpState.setDump(DumpState.DUMP_VERSION);
20391            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20392                dumpState.setDump(DumpState.DUMP_KEYSETS);
20393            } else if ("installs".equals(cmd)) {
20394                dumpState.setDump(DumpState.DUMP_INSTALLS);
20395            } else if ("frozen".equals(cmd)) {
20396                dumpState.setDump(DumpState.DUMP_FROZEN);
20397            } else if ("dexopt".equals(cmd)) {
20398                dumpState.setDump(DumpState.DUMP_DEXOPT);
20399            } else if ("compiler-stats".equals(cmd)) {
20400                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20401            } else if ("enabled-overlays".equals(cmd)) {
20402                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20403            } else if ("write".equals(cmd)) {
20404                synchronized (mPackages) {
20405                    mSettings.writeLPr();
20406                    pw.println("Settings written.");
20407                    return;
20408                }
20409            }
20410        }
20411
20412        if (checkin) {
20413            pw.println("vers,1");
20414        }
20415
20416        // reader
20417        synchronized (mPackages) {
20418            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20419                if (!checkin) {
20420                    if (dumpState.onTitlePrinted())
20421                        pw.println();
20422                    pw.println("Database versions:");
20423                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20424                }
20425            }
20426
20427            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20428                if (!checkin) {
20429                    if (dumpState.onTitlePrinted())
20430                        pw.println();
20431                    pw.println("Verifiers:");
20432                    pw.print("  Required: ");
20433                    pw.print(mRequiredVerifierPackage);
20434                    pw.print(" (uid=");
20435                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20436                            UserHandle.USER_SYSTEM));
20437                    pw.println(")");
20438                } else if (mRequiredVerifierPackage != null) {
20439                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20440                    pw.print(",");
20441                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20442                            UserHandle.USER_SYSTEM));
20443                }
20444            }
20445
20446            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20447                    packageName == null) {
20448                if (mIntentFilterVerifierComponent != null) {
20449                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20450                    if (!checkin) {
20451                        if (dumpState.onTitlePrinted())
20452                            pw.println();
20453                        pw.println("Intent Filter Verifier:");
20454                        pw.print("  Using: ");
20455                        pw.print(verifierPackageName);
20456                        pw.print(" (uid=");
20457                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20458                                UserHandle.USER_SYSTEM));
20459                        pw.println(")");
20460                    } else if (verifierPackageName != null) {
20461                        pw.print("ifv,"); pw.print(verifierPackageName);
20462                        pw.print(",");
20463                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20464                                UserHandle.USER_SYSTEM));
20465                    }
20466                } else {
20467                    pw.println();
20468                    pw.println("No Intent Filter Verifier available!");
20469                }
20470            }
20471
20472            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20473                boolean printedHeader = false;
20474                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20475                while (it.hasNext()) {
20476                    String libName = it.next();
20477                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20478                    if (versionedLib == null) {
20479                        continue;
20480                    }
20481                    final int versionCount = versionedLib.size();
20482                    for (int i = 0; i < versionCount; i++) {
20483                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20484                        if (!checkin) {
20485                            if (!printedHeader) {
20486                                if (dumpState.onTitlePrinted())
20487                                    pw.println();
20488                                pw.println("Libraries:");
20489                                printedHeader = true;
20490                            }
20491                            pw.print("  ");
20492                        } else {
20493                            pw.print("lib,");
20494                        }
20495                        pw.print(libEntry.info.getName());
20496                        if (libEntry.info.isStatic()) {
20497                            pw.print(" version=" + libEntry.info.getVersion());
20498                        }
20499                        if (!checkin) {
20500                            pw.print(" -> ");
20501                        }
20502                        if (libEntry.path != null) {
20503                            pw.print(" (jar) ");
20504                            pw.print(libEntry.path);
20505                        } else {
20506                            pw.print(" (apk) ");
20507                            pw.print(libEntry.apk);
20508                        }
20509                        pw.println();
20510                    }
20511                }
20512            }
20513
20514            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20515                if (dumpState.onTitlePrinted())
20516                    pw.println();
20517                if (!checkin) {
20518                    pw.println("Features:");
20519                }
20520
20521                synchronized (mAvailableFeatures) {
20522                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20523                        if (checkin) {
20524                            pw.print("feat,");
20525                            pw.print(feat.name);
20526                            pw.print(",");
20527                            pw.println(feat.version);
20528                        } else {
20529                            pw.print("  ");
20530                            pw.print(feat.name);
20531                            if (feat.version > 0) {
20532                                pw.print(" version=");
20533                                pw.print(feat.version);
20534                            }
20535                            pw.println();
20536                        }
20537                    }
20538                }
20539            }
20540
20541            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20542                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20543                        : "Activity Resolver Table:", "  ", packageName,
20544                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20545                    dumpState.setTitlePrinted(true);
20546                }
20547            }
20548            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20549                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20550                        : "Receiver Resolver Table:", "  ", packageName,
20551                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20552                    dumpState.setTitlePrinted(true);
20553                }
20554            }
20555            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20556                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20557                        : "Service Resolver Table:", "  ", packageName,
20558                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20559                    dumpState.setTitlePrinted(true);
20560                }
20561            }
20562            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20563                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20564                        : "Provider Resolver Table:", "  ", packageName,
20565                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20566                    dumpState.setTitlePrinted(true);
20567                }
20568            }
20569
20570            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20571                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20572                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20573                    int user = mSettings.mPreferredActivities.keyAt(i);
20574                    if (pir.dump(pw,
20575                            dumpState.getTitlePrinted()
20576                                ? "\nPreferred Activities User " + user + ":"
20577                                : "Preferred Activities User " + user + ":", "  ",
20578                            packageName, true, false)) {
20579                        dumpState.setTitlePrinted(true);
20580                    }
20581                }
20582            }
20583
20584            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20585                pw.flush();
20586                FileOutputStream fout = new FileOutputStream(fd);
20587                BufferedOutputStream str = new BufferedOutputStream(fout);
20588                XmlSerializer serializer = new FastXmlSerializer();
20589                try {
20590                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20591                    serializer.startDocument(null, true);
20592                    serializer.setFeature(
20593                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20594                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20595                    serializer.endDocument();
20596                    serializer.flush();
20597                } catch (IllegalArgumentException e) {
20598                    pw.println("Failed writing: " + e);
20599                } catch (IllegalStateException e) {
20600                    pw.println("Failed writing: " + e);
20601                } catch (IOException e) {
20602                    pw.println("Failed writing: " + e);
20603                }
20604            }
20605
20606            if (!checkin
20607                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20608                    && packageName == null) {
20609                pw.println();
20610                int count = mSettings.mPackages.size();
20611                if (count == 0) {
20612                    pw.println("No applications!");
20613                    pw.println();
20614                } else {
20615                    final String prefix = "  ";
20616                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20617                    if (allPackageSettings.size() == 0) {
20618                        pw.println("No domain preferred apps!");
20619                        pw.println();
20620                    } else {
20621                        pw.println("App verification status:");
20622                        pw.println();
20623                        count = 0;
20624                        for (PackageSetting ps : allPackageSettings) {
20625                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20626                            if (ivi == null || ivi.getPackageName() == null) continue;
20627                            pw.println(prefix + "Package: " + ivi.getPackageName());
20628                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20629                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20630                            pw.println();
20631                            count++;
20632                        }
20633                        if (count == 0) {
20634                            pw.println(prefix + "No app verification established.");
20635                            pw.println();
20636                        }
20637                        for (int userId : sUserManager.getUserIds()) {
20638                            pw.println("App linkages for user " + userId + ":");
20639                            pw.println();
20640                            count = 0;
20641                            for (PackageSetting ps : allPackageSettings) {
20642                                final long status = ps.getDomainVerificationStatusForUser(userId);
20643                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20644                                        && !DEBUG_DOMAIN_VERIFICATION) {
20645                                    continue;
20646                                }
20647                                pw.println(prefix + "Package: " + ps.name);
20648                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20649                                String statusStr = IntentFilterVerificationInfo.
20650                                        getStatusStringFromValue(status);
20651                                pw.println(prefix + "Status:  " + statusStr);
20652                                pw.println();
20653                                count++;
20654                            }
20655                            if (count == 0) {
20656                                pw.println(prefix + "No configured app linkages.");
20657                                pw.println();
20658                            }
20659                        }
20660                    }
20661                }
20662            }
20663
20664            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20665                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20666                if (packageName == null && permissionNames == null) {
20667                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20668                        if (iperm == 0) {
20669                            if (dumpState.onTitlePrinted())
20670                                pw.println();
20671                            pw.println("AppOp Permissions:");
20672                        }
20673                        pw.print("  AppOp Permission ");
20674                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20675                        pw.println(":");
20676                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20677                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20678                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20679                        }
20680                    }
20681                }
20682            }
20683
20684            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20685                boolean printedSomething = false;
20686                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20687                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20688                        continue;
20689                    }
20690                    if (!printedSomething) {
20691                        if (dumpState.onTitlePrinted())
20692                            pw.println();
20693                        pw.println("Registered ContentProviders:");
20694                        printedSomething = true;
20695                    }
20696                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20697                    pw.print("    "); pw.println(p.toString());
20698                }
20699                printedSomething = false;
20700                for (Map.Entry<String, PackageParser.Provider> entry :
20701                        mProvidersByAuthority.entrySet()) {
20702                    PackageParser.Provider p = entry.getValue();
20703                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20704                        continue;
20705                    }
20706                    if (!printedSomething) {
20707                        if (dumpState.onTitlePrinted())
20708                            pw.println();
20709                        pw.println("ContentProvider Authorities:");
20710                        printedSomething = true;
20711                    }
20712                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20713                    pw.print("    "); pw.println(p.toString());
20714                    if (p.info != null && p.info.applicationInfo != null) {
20715                        final String appInfo = p.info.applicationInfo.toString();
20716                        pw.print("      applicationInfo="); pw.println(appInfo);
20717                    }
20718                }
20719            }
20720
20721            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20722                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20723            }
20724
20725            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20726                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20727            }
20728
20729            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20730                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20731            }
20732
20733            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20734                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20735            }
20736
20737            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20738                // XXX should handle packageName != null by dumping only install data that
20739                // the given package is involved with.
20740                if (dumpState.onTitlePrinted()) pw.println();
20741                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20742            }
20743
20744            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20745                // XXX should handle packageName != null by dumping only install data that
20746                // the given package is involved with.
20747                if (dumpState.onTitlePrinted()) pw.println();
20748
20749                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20750                ipw.println();
20751                ipw.println("Frozen packages:");
20752                ipw.increaseIndent();
20753                if (mFrozenPackages.size() == 0) {
20754                    ipw.println("(none)");
20755                } else {
20756                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20757                        ipw.println(mFrozenPackages.valueAt(i));
20758                    }
20759                }
20760                ipw.decreaseIndent();
20761            }
20762
20763            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20764                if (dumpState.onTitlePrinted()) pw.println();
20765                dumpDexoptStateLPr(pw, packageName);
20766            }
20767
20768            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20769                if (dumpState.onTitlePrinted()) pw.println();
20770                dumpCompilerStatsLPr(pw, packageName);
20771            }
20772
20773            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20774                if (dumpState.onTitlePrinted()) pw.println();
20775                dumpEnabledOverlaysLPr(pw);
20776            }
20777
20778            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20779                if (dumpState.onTitlePrinted()) pw.println();
20780                mSettings.dumpReadMessagesLPr(pw, dumpState);
20781
20782                pw.println();
20783                pw.println("Package warning messages:");
20784                BufferedReader in = null;
20785                String line = null;
20786                try {
20787                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20788                    while ((line = in.readLine()) != null) {
20789                        if (line.contains("ignored: updated version")) continue;
20790                        pw.println(line);
20791                    }
20792                } catch (IOException ignored) {
20793                } finally {
20794                    IoUtils.closeQuietly(in);
20795                }
20796            }
20797
20798            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20799                BufferedReader in = null;
20800                String line = null;
20801                try {
20802                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20803                    while ((line = in.readLine()) != null) {
20804                        if (line.contains("ignored: updated version")) continue;
20805                        pw.print("msg,");
20806                        pw.println(line);
20807                    }
20808                } catch (IOException ignored) {
20809                } finally {
20810                    IoUtils.closeQuietly(in);
20811                }
20812            }
20813        }
20814    }
20815
20816    private void dumpProto(FileDescriptor fd) {
20817        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20818
20819        synchronized (mPackages) {
20820            final long requiredVerifierPackageToken =
20821                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20822            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20823            proto.write(
20824                    PackageServiceDumpProto.PackageShortProto.UID,
20825                    getPackageUid(
20826                            mRequiredVerifierPackage,
20827                            MATCH_DEBUG_TRIAGED_MISSING,
20828                            UserHandle.USER_SYSTEM));
20829            proto.end(requiredVerifierPackageToken);
20830
20831            if (mIntentFilterVerifierComponent != null) {
20832                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20833                final long verifierPackageToken =
20834                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20835                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20836                proto.write(
20837                        PackageServiceDumpProto.PackageShortProto.UID,
20838                        getPackageUid(
20839                                verifierPackageName,
20840                                MATCH_DEBUG_TRIAGED_MISSING,
20841                                UserHandle.USER_SYSTEM));
20842                proto.end(verifierPackageToken);
20843            }
20844
20845            dumpSharedLibrariesProto(proto);
20846            dumpFeaturesProto(proto);
20847            mSettings.dumpPackagesProto(proto);
20848            mSettings.dumpSharedUsersProto(proto);
20849            dumpMessagesProto(proto);
20850        }
20851        proto.flush();
20852    }
20853
20854    private void dumpMessagesProto(ProtoOutputStream proto) {
20855        BufferedReader in = null;
20856        String line = null;
20857        try {
20858            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20859            while ((line = in.readLine()) != null) {
20860                if (line.contains("ignored: updated version")) continue;
20861                proto.write(PackageServiceDumpProto.MESSAGES, line);
20862            }
20863        } catch (IOException ignored) {
20864        } finally {
20865            IoUtils.closeQuietly(in);
20866        }
20867    }
20868
20869    private void dumpFeaturesProto(ProtoOutputStream proto) {
20870        synchronized (mAvailableFeatures) {
20871            final int count = mAvailableFeatures.size();
20872            for (int i = 0; i < count; i++) {
20873                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20874                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20875                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20876                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20877                proto.end(featureToken);
20878            }
20879        }
20880    }
20881
20882    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20883        final int count = mSharedLibraries.size();
20884        for (int i = 0; i < count; i++) {
20885            final String libName = mSharedLibraries.keyAt(i);
20886            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20887            if (versionedLib == null) {
20888                continue;
20889            }
20890            final int versionCount = versionedLib.size();
20891            for (int j = 0; j < versionCount; j++) {
20892                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20893                final long sharedLibraryToken =
20894                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20895                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20896                final boolean isJar = (libEntry.path != null);
20897                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20898                if (isJar) {
20899                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20900                } else {
20901                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20902                }
20903                proto.end(sharedLibraryToken);
20904            }
20905        }
20906    }
20907
20908    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20909        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20910        ipw.println();
20911        ipw.println("Dexopt state:");
20912        ipw.increaseIndent();
20913        Collection<PackageParser.Package> packages = null;
20914        if (packageName != null) {
20915            PackageParser.Package targetPackage = mPackages.get(packageName);
20916            if (targetPackage != null) {
20917                packages = Collections.singletonList(targetPackage);
20918            } else {
20919                ipw.println("Unable to find package: " + packageName);
20920                return;
20921            }
20922        } else {
20923            packages = mPackages.values();
20924        }
20925
20926        for (PackageParser.Package pkg : packages) {
20927            ipw.println("[" + pkg.packageName + "]");
20928            ipw.increaseIndent();
20929            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20930            ipw.decreaseIndent();
20931        }
20932    }
20933
20934    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20935        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20936        ipw.println();
20937        ipw.println("Compiler stats:");
20938        ipw.increaseIndent();
20939        Collection<PackageParser.Package> packages = null;
20940        if (packageName != null) {
20941            PackageParser.Package targetPackage = mPackages.get(packageName);
20942            if (targetPackage != null) {
20943                packages = Collections.singletonList(targetPackage);
20944            } else {
20945                ipw.println("Unable to find package: " + packageName);
20946                return;
20947            }
20948        } else {
20949            packages = mPackages.values();
20950        }
20951
20952        for (PackageParser.Package pkg : packages) {
20953            ipw.println("[" + pkg.packageName + "]");
20954            ipw.increaseIndent();
20955
20956            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20957            if (stats == null) {
20958                ipw.println("(No recorded stats)");
20959            } else {
20960                stats.dump(ipw);
20961            }
20962            ipw.decreaseIndent();
20963        }
20964    }
20965
20966    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20967        pw.println("Enabled overlay paths:");
20968        final int N = mEnabledOverlayPaths.size();
20969        for (int i = 0; i < N; i++) {
20970            final int userId = mEnabledOverlayPaths.keyAt(i);
20971            pw.println(String.format("    User %d:", userId));
20972            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20973                mEnabledOverlayPaths.valueAt(i);
20974            final int M = userSpecificOverlays.size();
20975            for (int j = 0; j < M; j++) {
20976                final String targetPackageName = userSpecificOverlays.keyAt(j);
20977                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20978                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20979            }
20980        }
20981    }
20982
20983    private String dumpDomainString(String packageName) {
20984        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20985                .getList();
20986        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20987
20988        ArraySet<String> result = new ArraySet<>();
20989        if (iviList.size() > 0) {
20990            for (IntentFilterVerificationInfo ivi : iviList) {
20991                for (String host : ivi.getDomains()) {
20992                    result.add(host);
20993                }
20994            }
20995        }
20996        if (filters != null && filters.size() > 0) {
20997            for (IntentFilter filter : filters) {
20998                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20999                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21000                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21001                    result.addAll(filter.getHostsList());
21002                }
21003            }
21004        }
21005
21006        StringBuilder sb = new StringBuilder(result.size() * 16);
21007        for (String domain : result) {
21008            if (sb.length() > 0) sb.append(" ");
21009            sb.append(domain);
21010        }
21011        return sb.toString();
21012    }
21013
21014    // ------- apps on sdcard specific code -------
21015    static final boolean DEBUG_SD_INSTALL = false;
21016
21017    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21018
21019    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21020
21021    private boolean mMediaMounted = false;
21022
21023    static String getEncryptKey() {
21024        try {
21025            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21026                    SD_ENCRYPTION_KEYSTORE_NAME);
21027            if (sdEncKey == null) {
21028                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21029                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21030                if (sdEncKey == null) {
21031                    Slog.e(TAG, "Failed to create encryption keys");
21032                    return null;
21033                }
21034            }
21035            return sdEncKey;
21036        } catch (NoSuchAlgorithmException nsae) {
21037            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21038            return null;
21039        } catch (IOException ioe) {
21040            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21041            return null;
21042        }
21043    }
21044
21045    /*
21046     * Update media status on PackageManager.
21047     */
21048    @Override
21049    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21050        int callingUid = Binder.getCallingUid();
21051        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21052            throw new SecurityException("Media status can only be updated by the system");
21053        }
21054        // reader; this apparently protects mMediaMounted, but should probably
21055        // be a different lock in that case.
21056        synchronized (mPackages) {
21057            Log.i(TAG, "Updating external media status from "
21058                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21059                    + (mediaStatus ? "mounted" : "unmounted"));
21060            if (DEBUG_SD_INSTALL)
21061                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21062                        + ", mMediaMounted=" + mMediaMounted);
21063            if (mediaStatus == mMediaMounted) {
21064                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21065                        : 0, -1);
21066                mHandler.sendMessage(msg);
21067                return;
21068            }
21069            mMediaMounted = mediaStatus;
21070        }
21071        // Queue up an async operation since the package installation may take a
21072        // little while.
21073        mHandler.post(new Runnable() {
21074            public void run() {
21075                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21076            }
21077        });
21078    }
21079
21080    /**
21081     * Called by StorageManagerService when the initial ASECs to scan are available.
21082     * Should block until all the ASEC containers are finished being scanned.
21083     */
21084    public void scanAvailableAsecs() {
21085        updateExternalMediaStatusInner(true, false, false);
21086    }
21087
21088    /*
21089     * Collect information of applications on external media, map them against
21090     * existing containers and update information based on current mount status.
21091     * Please note that we always have to report status if reportStatus has been
21092     * set to true especially when unloading packages.
21093     */
21094    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21095            boolean externalStorage) {
21096        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21097        int[] uidArr = EmptyArray.INT;
21098
21099        final String[] list = PackageHelper.getSecureContainerList();
21100        if (ArrayUtils.isEmpty(list)) {
21101            Log.i(TAG, "No secure containers found");
21102        } else {
21103            // Process list of secure containers and categorize them
21104            // as active or stale based on their package internal state.
21105
21106            // reader
21107            synchronized (mPackages) {
21108                for (String cid : list) {
21109                    // Leave stages untouched for now; installer service owns them
21110                    if (PackageInstallerService.isStageName(cid)) continue;
21111
21112                    if (DEBUG_SD_INSTALL)
21113                        Log.i(TAG, "Processing container " + cid);
21114                    String pkgName = getAsecPackageName(cid);
21115                    if (pkgName == null) {
21116                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21117                        continue;
21118                    }
21119                    if (DEBUG_SD_INSTALL)
21120                        Log.i(TAG, "Looking for pkg : " + pkgName);
21121
21122                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21123                    if (ps == null) {
21124                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21125                        continue;
21126                    }
21127
21128                    /*
21129                     * Skip packages that are not external if we're unmounting
21130                     * external storage.
21131                     */
21132                    if (externalStorage && !isMounted && !isExternal(ps)) {
21133                        continue;
21134                    }
21135
21136                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21137                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21138                    // The package status is changed only if the code path
21139                    // matches between settings and the container id.
21140                    if (ps.codePathString != null
21141                            && ps.codePathString.startsWith(args.getCodePath())) {
21142                        if (DEBUG_SD_INSTALL) {
21143                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21144                                    + " at code path: " + ps.codePathString);
21145                        }
21146
21147                        // We do have a valid package installed on sdcard
21148                        processCids.put(args, ps.codePathString);
21149                        final int uid = ps.appId;
21150                        if (uid != -1) {
21151                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21152                        }
21153                    } else {
21154                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21155                                + ps.codePathString);
21156                    }
21157                }
21158            }
21159
21160            Arrays.sort(uidArr);
21161        }
21162
21163        // Process packages with valid entries.
21164        if (isMounted) {
21165            if (DEBUG_SD_INSTALL)
21166                Log.i(TAG, "Loading packages");
21167            loadMediaPackages(processCids, uidArr, externalStorage);
21168            startCleaningPackages();
21169            mInstallerService.onSecureContainersAvailable();
21170        } else {
21171            if (DEBUG_SD_INSTALL)
21172                Log.i(TAG, "Unloading packages");
21173            unloadMediaPackages(processCids, uidArr, reportStatus);
21174        }
21175    }
21176
21177    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21178            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21179        final int size = infos.size();
21180        final String[] packageNames = new String[size];
21181        final int[] packageUids = new int[size];
21182        for (int i = 0; i < size; i++) {
21183            final ApplicationInfo info = infos.get(i);
21184            packageNames[i] = info.packageName;
21185            packageUids[i] = info.uid;
21186        }
21187        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21188                finishedReceiver);
21189    }
21190
21191    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21192            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21193        sendResourcesChangedBroadcast(mediaStatus, replacing,
21194                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21195    }
21196
21197    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21198            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21199        int size = pkgList.length;
21200        if (size > 0) {
21201            // Send broadcasts here
21202            Bundle extras = new Bundle();
21203            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21204            if (uidArr != null) {
21205                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21206            }
21207            if (replacing) {
21208                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21209            }
21210            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21211                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21212            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21213        }
21214    }
21215
21216   /*
21217     * Look at potentially valid container ids from processCids If package
21218     * information doesn't match the one on record or package scanning fails,
21219     * the cid is added to list of removeCids. We currently don't delete stale
21220     * containers.
21221     */
21222    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21223            boolean externalStorage) {
21224        ArrayList<String> pkgList = new ArrayList<String>();
21225        Set<AsecInstallArgs> keys = processCids.keySet();
21226
21227        for (AsecInstallArgs args : keys) {
21228            String codePath = processCids.get(args);
21229            if (DEBUG_SD_INSTALL)
21230                Log.i(TAG, "Loading container : " + args.cid);
21231            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21232            try {
21233                // Make sure there are no container errors first.
21234                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21235                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21236                            + " when installing from sdcard");
21237                    continue;
21238                }
21239                // Check code path here.
21240                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21241                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21242                            + " does not match one in settings " + codePath);
21243                    continue;
21244                }
21245                // Parse package
21246                int parseFlags = mDefParseFlags;
21247                if (args.isExternalAsec()) {
21248                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21249                }
21250                if (args.isFwdLocked()) {
21251                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21252                }
21253
21254                synchronized (mInstallLock) {
21255                    PackageParser.Package pkg = null;
21256                    try {
21257                        // Sadly we don't know the package name yet to freeze it
21258                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21259                                SCAN_IGNORE_FROZEN, 0, null);
21260                    } catch (PackageManagerException e) {
21261                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21262                    }
21263                    // Scan the package
21264                    if (pkg != null) {
21265                        /*
21266                         * TODO why is the lock being held? doPostInstall is
21267                         * called in other places without the lock. This needs
21268                         * to be straightened out.
21269                         */
21270                        // writer
21271                        synchronized (mPackages) {
21272                            retCode = PackageManager.INSTALL_SUCCEEDED;
21273                            pkgList.add(pkg.packageName);
21274                            // Post process args
21275                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21276                                    pkg.applicationInfo.uid);
21277                        }
21278                    } else {
21279                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21280                    }
21281                }
21282
21283            } finally {
21284                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21285                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21286                }
21287            }
21288        }
21289        // writer
21290        synchronized (mPackages) {
21291            // If the platform SDK has changed since the last time we booted,
21292            // we need to re-grant app permission to catch any new ones that
21293            // appear. This is really a hack, and means that apps can in some
21294            // cases get permissions that the user didn't initially explicitly
21295            // allow... it would be nice to have some better way to handle
21296            // this situation.
21297            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21298                    : mSettings.getInternalVersion();
21299            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21300                    : StorageManager.UUID_PRIVATE_INTERNAL;
21301
21302            int updateFlags = UPDATE_PERMISSIONS_ALL;
21303            if (ver.sdkVersion != mSdkVersion) {
21304                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21305                        + mSdkVersion + "; regranting permissions for external");
21306                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21307            }
21308            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21309
21310            // Yay, everything is now upgraded
21311            ver.forceCurrent();
21312
21313            // can downgrade to reader
21314            // Persist settings
21315            mSettings.writeLPr();
21316        }
21317        // Send a broadcast to let everyone know we are done processing
21318        if (pkgList.size() > 0) {
21319            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21320        }
21321    }
21322
21323   /*
21324     * Utility method to unload a list of specified containers
21325     */
21326    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21327        // Just unmount all valid containers.
21328        for (AsecInstallArgs arg : cidArgs) {
21329            synchronized (mInstallLock) {
21330                arg.doPostDeleteLI(false);
21331           }
21332       }
21333   }
21334
21335    /*
21336     * Unload packages mounted on external media. This involves deleting package
21337     * data from internal structures, sending broadcasts about disabled packages,
21338     * gc'ing to free up references, unmounting all secure containers
21339     * corresponding to packages on external media, and posting a
21340     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21341     * that we always have to post this message if status has been requested no
21342     * matter what.
21343     */
21344    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21345            final boolean reportStatus) {
21346        if (DEBUG_SD_INSTALL)
21347            Log.i(TAG, "unloading media packages");
21348        ArrayList<String> pkgList = new ArrayList<String>();
21349        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21350        final Set<AsecInstallArgs> keys = processCids.keySet();
21351        for (AsecInstallArgs args : keys) {
21352            String pkgName = args.getPackageName();
21353            if (DEBUG_SD_INSTALL)
21354                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21355            // Delete package internally
21356            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21357            synchronized (mInstallLock) {
21358                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21359                final boolean res;
21360                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21361                        "unloadMediaPackages")) {
21362                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21363                            null);
21364                }
21365                if (res) {
21366                    pkgList.add(pkgName);
21367                } else {
21368                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21369                    failedList.add(args);
21370                }
21371            }
21372        }
21373
21374        // reader
21375        synchronized (mPackages) {
21376            // We didn't update the settings after removing each package;
21377            // write them now for all packages.
21378            mSettings.writeLPr();
21379        }
21380
21381        // We have to absolutely send UPDATED_MEDIA_STATUS only
21382        // after confirming that all the receivers processed the ordered
21383        // broadcast when packages get disabled, force a gc to clean things up.
21384        // and unload all the containers.
21385        if (pkgList.size() > 0) {
21386            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21387                    new IIntentReceiver.Stub() {
21388                public void performReceive(Intent intent, int resultCode, String data,
21389                        Bundle extras, boolean ordered, boolean sticky,
21390                        int sendingUser) throws RemoteException {
21391                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21392                            reportStatus ? 1 : 0, 1, keys);
21393                    mHandler.sendMessage(msg);
21394                }
21395            });
21396        } else {
21397            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21398                    keys);
21399            mHandler.sendMessage(msg);
21400        }
21401    }
21402
21403    private void loadPrivatePackages(final VolumeInfo vol) {
21404        mHandler.post(new Runnable() {
21405            @Override
21406            public void run() {
21407                loadPrivatePackagesInner(vol);
21408            }
21409        });
21410    }
21411
21412    private void loadPrivatePackagesInner(VolumeInfo vol) {
21413        final String volumeUuid = vol.fsUuid;
21414        if (TextUtils.isEmpty(volumeUuid)) {
21415            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21416            return;
21417        }
21418
21419        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21420        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21421        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21422
21423        final VersionInfo ver;
21424        final List<PackageSetting> packages;
21425        synchronized (mPackages) {
21426            ver = mSettings.findOrCreateVersion(volumeUuid);
21427            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21428        }
21429
21430        for (PackageSetting ps : packages) {
21431            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21432            synchronized (mInstallLock) {
21433                final PackageParser.Package pkg;
21434                try {
21435                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21436                    loaded.add(pkg.applicationInfo);
21437
21438                } catch (PackageManagerException e) {
21439                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21440                }
21441
21442                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21443                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21444                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21445                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21446                }
21447            }
21448        }
21449
21450        // Reconcile app data for all started/unlocked users
21451        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21452        final UserManager um = mContext.getSystemService(UserManager.class);
21453        UserManagerInternal umInternal = getUserManagerInternal();
21454        for (UserInfo user : um.getUsers()) {
21455            final int flags;
21456            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21457                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21458            } else if (umInternal.isUserRunning(user.id)) {
21459                flags = StorageManager.FLAG_STORAGE_DE;
21460            } else {
21461                continue;
21462            }
21463
21464            try {
21465                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21466                synchronized (mInstallLock) {
21467                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21468                }
21469            } catch (IllegalStateException e) {
21470                // Device was probably ejected, and we'll process that event momentarily
21471                Slog.w(TAG, "Failed to prepare storage: " + e);
21472            }
21473        }
21474
21475        synchronized (mPackages) {
21476            int updateFlags = UPDATE_PERMISSIONS_ALL;
21477            if (ver.sdkVersion != mSdkVersion) {
21478                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21479                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21480                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21481            }
21482            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21483
21484            // Yay, everything is now upgraded
21485            ver.forceCurrent();
21486
21487            mSettings.writeLPr();
21488        }
21489
21490        for (PackageFreezer freezer : freezers) {
21491            freezer.close();
21492        }
21493
21494        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21495        sendResourcesChangedBroadcast(true, false, loaded, null);
21496    }
21497
21498    private void unloadPrivatePackages(final VolumeInfo vol) {
21499        mHandler.post(new Runnable() {
21500            @Override
21501            public void run() {
21502                unloadPrivatePackagesInner(vol);
21503            }
21504        });
21505    }
21506
21507    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21508        final String volumeUuid = vol.fsUuid;
21509        if (TextUtils.isEmpty(volumeUuid)) {
21510            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21511            return;
21512        }
21513
21514        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21515        synchronized (mInstallLock) {
21516        synchronized (mPackages) {
21517            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21518            for (PackageSetting ps : packages) {
21519                if (ps.pkg == null) continue;
21520
21521                final ApplicationInfo info = ps.pkg.applicationInfo;
21522                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21523                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21524
21525                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21526                        "unloadPrivatePackagesInner")) {
21527                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21528                            false, null)) {
21529                        unloaded.add(info);
21530                    } else {
21531                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21532                    }
21533                }
21534
21535                // Try very hard to release any references to this package
21536                // so we don't risk the system server being killed due to
21537                // open FDs
21538                AttributeCache.instance().removePackage(ps.name);
21539            }
21540
21541            mSettings.writeLPr();
21542        }
21543        }
21544
21545        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21546        sendResourcesChangedBroadcast(false, false, unloaded, null);
21547
21548        // Try very hard to release any references to this path so we don't risk
21549        // the system server being killed due to open FDs
21550        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21551
21552        for (int i = 0; i < 3; i++) {
21553            System.gc();
21554            System.runFinalization();
21555        }
21556    }
21557
21558    private void assertPackageKnown(String volumeUuid, String packageName)
21559            throws PackageManagerException {
21560        synchronized (mPackages) {
21561            // Normalize package name to handle renamed packages
21562            packageName = normalizePackageNameLPr(packageName);
21563
21564            final PackageSetting ps = mSettings.mPackages.get(packageName);
21565            if (ps == null) {
21566                throw new PackageManagerException("Package " + packageName + " is unknown");
21567            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21568                throw new PackageManagerException(
21569                        "Package " + packageName + " found on unknown volume " + volumeUuid
21570                                + "; expected volume " + ps.volumeUuid);
21571            }
21572        }
21573    }
21574
21575    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21576            throws PackageManagerException {
21577        synchronized (mPackages) {
21578            // Normalize package name to handle renamed packages
21579            packageName = normalizePackageNameLPr(packageName);
21580
21581            final PackageSetting ps = mSettings.mPackages.get(packageName);
21582            if (ps == null) {
21583                throw new PackageManagerException("Package " + packageName + " is unknown");
21584            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21585                throw new PackageManagerException(
21586                        "Package " + packageName + " found on unknown volume " + volumeUuid
21587                                + "; expected volume " + ps.volumeUuid);
21588            } else if (!ps.getInstalled(userId)) {
21589                throw new PackageManagerException(
21590                        "Package " + packageName + " not installed for user " + userId);
21591            }
21592        }
21593    }
21594
21595    private List<String> collectAbsoluteCodePaths() {
21596        synchronized (mPackages) {
21597            List<String> codePaths = new ArrayList<>();
21598            final int packageCount = mSettings.mPackages.size();
21599            for (int i = 0; i < packageCount; i++) {
21600                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21601                codePaths.add(ps.codePath.getAbsolutePath());
21602            }
21603            return codePaths;
21604        }
21605    }
21606
21607    /**
21608     * Examine all apps present on given mounted volume, and destroy apps that
21609     * aren't expected, either due to uninstallation or reinstallation on
21610     * another volume.
21611     */
21612    private void reconcileApps(String volumeUuid) {
21613        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21614        List<File> filesToDelete = null;
21615
21616        final File[] files = FileUtils.listFilesOrEmpty(
21617                Environment.getDataAppDirectory(volumeUuid));
21618        for (File file : files) {
21619            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21620                    && !PackageInstallerService.isStageName(file.getName());
21621            if (!isPackage) {
21622                // Ignore entries which are not packages
21623                continue;
21624            }
21625
21626            String absolutePath = file.getAbsolutePath();
21627
21628            boolean pathValid = false;
21629            final int absoluteCodePathCount = absoluteCodePaths.size();
21630            for (int i = 0; i < absoluteCodePathCount; i++) {
21631                String absoluteCodePath = absoluteCodePaths.get(i);
21632                if (absolutePath.startsWith(absoluteCodePath)) {
21633                    pathValid = true;
21634                    break;
21635                }
21636            }
21637
21638            if (!pathValid) {
21639                if (filesToDelete == null) {
21640                    filesToDelete = new ArrayList<>();
21641                }
21642                filesToDelete.add(file);
21643            }
21644        }
21645
21646        if (filesToDelete != null) {
21647            final int fileToDeleteCount = filesToDelete.size();
21648            for (int i = 0; i < fileToDeleteCount; i++) {
21649                File fileToDelete = filesToDelete.get(i);
21650                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21651                synchronized (mInstallLock) {
21652                    removeCodePathLI(fileToDelete);
21653                }
21654            }
21655        }
21656    }
21657
21658    /**
21659     * Reconcile all app data for the given user.
21660     * <p>
21661     * Verifies that directories exist and that ownership and labeling is
21662     * correct for all installed apps on all mounted volumes.
21663     */
21664    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21665        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21666        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21667            final String volumeUuid = vol.getFsUuid();
21668            synchronized (mInstallLock) {
21669                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21670            }
21671        }
21672    }
21673
21674    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21675            boolean migrateAppData) {
21676        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21677    }
21678
21679    /**
21680     * Reconcile all app data on given mounted volume.
21681     * <p>
21682     * Destroys app data that isn't expected, either due to uninstallation or
21683     * reinstallation on another volume.
21684     * <p>
21685     * Verifies that directories exist and that ownership and labeling is
21686     * correct for all installed apps.
21687     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21688     */
21689    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21690            boolean migrateAppData, boolean onlyCoreApps) {
21691        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21692                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21693        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21694
21695        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21696        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21697
21698        // First look for stale data that doesn't belong, and check if things
21699        // have changed since we did our last restorecon
21700        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21701            if (StorageManager.isFileEncryptedNativeOrEmulated()
21702                    && !StorageManager.isUserKeyUnlocked(userId)) {
21703                throw new RuntimeException(
21704                        "Yikes, someone asked us to reconcile CE storage while " + userId
21705                                + " was still locked; this would have caused massive data loss!");
21706            }
21707
21708            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21709            for (File file : files) {
21710                final String packageName = file.getName();
21711                try {
21712                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21713                } catch (PackageManagerException e) {
21714                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21715                    try {
21716                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21717                                StorageManager.FLAG_STORAGE_CE, 0);
21718                    } catch (InstallerException e2) {
21719                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21720                    }
21721                }
21722            }
21723        }
21724        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21725            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21726            for (File file : files) {
21727                final String packageName = file.getName();
21728                try {
21729                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21730                } catch (PackageManagerException e) {
21731                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21732                    try {
21733                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21734                                StorageManager.FLAG_STORAGE_DE, 0);
21735                    } catch (InstallerException e2) {
21736                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21737                    }
21738                }
21739            }
21740        }
21741
21742        // Ensure that data directories are ready to roll for all packages
21743        // installed for this volume and user
21744        final List<PackageSetting> packages;
21745        synchronized (mPackages) {
21746            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21747        }
21748        int preparedCount = 0;
21749        for (PackageSetting ps : packages) {
21750            final String packageName = ps.name;
21751            if (ps.pkg == null) {
21752                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21753                // TODO: might be due to legacy ASEC apps; we should circle back
21754                // and reconcile again once they're scanned
21755                continue;
21756            }
21757            // Skip non-core apps if requested
21758            if (onlyCoreApps && !ps.pkg.coreApp) {
21759                result.add(packageName);
21760                continue;
21761            }
21762
21763            if (ps.getInstalled(userId)) {
21764                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21765                preparedCount++;
21766            }
21767        }
21768
21769        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21770        return result;
21771    }
21772
21773    /**
21774     * Prepare app data for the given app just after it was installed or
21775     * upgraded. This method carefully only touches users that it's installed
21776     * for, and it forces a restorecon to handle any seinfo changes.
21777     * <p>
21778     * Verifies that directories exist and that ownership and labeling is
21779     * correct for all installed apps. If there is an ownership mismatch, it
21780     * will try recovering system apps by wiping data; third-party app data is
21781     * left intact.
21782     * <p>
21783     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21784     */
21785    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21786        final PackageSetting ps;
21787        synchronized (mPackages) {
21788            ps = mSettings.mPackages.get(pkg.packageName);
21789            mSettings.writeKernelMappingLPr(ps);
21790        }
21791
21792        final UserManager um = mContext.getSystemService(UserManager.class);
21793        UserManagerInternal umInternal = getUserManagerInternal();
21794        for (UserInfo user : um.getUsers()) {
21795            final int flags;
21796            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21797                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21798            } else if (umInternal.isUserRunning(user.id)) {
21799                flags = StorageManager.FLAG_STORAGE_DE;
21800            } else {
21801                continue;
21802            }
21803
21804            if (ps.getInstalled(user.id)) {
21805                // TODO: when user data is locked, mark that we're still dirty
21806                prepareAppDataLIF(pkg, user.id, flags);
21807            }
21808        }
21809    }
21810
21811    /**
21812     * Prepare app data for the given app.
21813     * <p>
21814     * Verifies that directories exist and that ownership and labeling is
21815     * correct for all installed apps. If there is an ownership mismatch, this
21816     * will try recovering system apps by wiping data; third-party app data is
21817     * left intact.
21818     */
21819    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21820        if (pkg == null) {
21821            Slog.wtf(TAG, "Package was null!", new Throwable());
21822            return;
21823        }
21824        prepareAppDataLeafLIF(pkg, userId, flags);
21825        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21826        for (int i = 0; i < childCount; i++) {
21827            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21828        }
21829    }
21830
21831    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21832            boolean maybeMigrateAppData) {
21833        prepareAppDataLIF(pkg, userId, flags);
21834
21835        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21836            // We may have just shuffled around app data directories, so
21837            // prepare them one more time
21838            prepareAppDataLIF(pkg, userId, flags);
21839        }
21840    }
21841
21842    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21843        if (DEBUG_APP_DATA) {
21844            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21845                    + Integer.toHexString(flags));
21846        }
21847
21848        final String volumeUuid = pkg.volumeUuid;
21849        final String packageName = pkg.packageName;
21850        final ApplicationInfo app = pkg.applicationInfo;
21851        final int appId = UserHandle.getAppId(app.uid);
21852
21853        Preconditions.checkNotNull(app.seInfo);
21854
21855        long ceDataInode = -1;
21856        try {
21857            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21858                    appId, app.seInfo, app.targetSdkVersion);
21859        } catch (InstallerException e) {
21860            if (app.isSystemApp()) {
21861                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21862                        + ", but trying to recover: " + e);
21863                destroyAppDataLeafLIF(pkg, userId, flags);
21864                try {
21865                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21866                            appId, app.seInfo, app.targetSdkVersion);
21867                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21868                } catch (InstallerException e2) {
21869                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21870                }
21871            } else {
21872                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21873            }
21874        }
21875
21876        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21877            // TODO: mark this structure as dirty so we persist it!
21878            synchronized (mPackages) {
21879                final PackageSetting ps = mSettings.mPackages.get(packageName);
21880                if (ps != null) {
21881                    ps.setCeDataInode(ceDataInode, userId);
21882                }
21883            }
21884        }
21885
21886        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21887    }
21888
21889    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21890        if (pkg == null) {
21891            Slog.wtf(TAG, "Package was null!", new Throwable());
21892            return;
21893        }
21894        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21895        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21896        for (int i = 0; i < childCount; i++) {
21897            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21898        }
21899    }
21900
21901    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21902        final String volumeUuid = pkg.volumeUuid;
21903        final String packageName = pkg.packageName;
21904        final ApplicationInfo app = pkg.applicationInfo;
21905
21906        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21907            // Create a native library symlink only if we have native libraries
21908            // and if the native libraries are 32 bit libraries. We do not provide
21909            // this symlink for 64 bit libraries.
21910            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21911                final String nativeLibPath = app.nativeLibraryDir;
21912                try {
21913                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21914                            nativeLibPath, userId);
21915                } catch (InstallerException e) {
21916                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21917                }
21918            }
21919        }
21920    }
21921
21922    /**
21923     * For system apps on non-FBE devices, this method migrates any existing
21924     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21925     * requested by the app.
21926     */
21927    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21928        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21929                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21930            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21931                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21932            try {
21933                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21934                        storageTarget);
21935            } catch (InstallerException e) {
21936                logCriticalInfo(Log.WARN,
21937                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21938            }
21939            return true;
21940        } else {
21941            return false;
21942        }
21943    }
21944
21945    public PackageFreezer freezePackage(String packageName, String killReason) {
21946        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21947    }
21948
21949    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21950        return new PackageFreezer(packageName, userId, killReason);
21951    }
21952
21953    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21954            String killReason) {
21955        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21956    }
21957
21958    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21959            String killReason) {
21960        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21961            return new PackageFreezer();
21962        } else {
21963            return freezePackage(packageName, userId, killReason);
21964        }
21965    }
21966
21967    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21968            String killReason) {
21969        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21970    }
21971
21972    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21973            String killReason) {
21974        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21975            return new PackageFreezer();
21976        } else {
21977            return freezePackage(packageName, userId, killReason);
21978        }
21979    }
21980
21981    /**
21982     * Class that freezes and kills the given package upon creation, and
21983     * unfreezes it upon closing. This is typically used when doing surgery on
21984     * app code/data to prevent the app from running while you're working.
21985     */
21986    private class PackageFreezer implements AutoCloseable {
21987        private final String mPackageName;
21988        private final PackageFreezer[] mChildren;
21989
21990        private final boolean mWeFroze;
21991
21992        private final AtomicBoolean mClosed = new AtomicBoolean();
21993        private final CloseGuard mCloseGuard = CloseGuard.get();
21994
21995        /**
21996         * Create and return a stub freezer that doesn't actually do anything,
21997         * typically used when someone requested
21998         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21999         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22000         */
22001        public PackageFreezer() {
22002            mPackageName = null;
22003            mChildren = null;
22004            mWeFroze = false;
22005            mCloseGuard.open("close");
22006        }
22007
22008        public PackageFreezer(String packageName, int userId, String killReason) {
22009            synchronized (mPackages) {
22010                mPackageName = packageName;
22011                mWeFroze = mFrozenPackages.add(mPackageName);
22012
22013                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22014                if (ps != null) {
22015                    killApplication(ps.name, ps.appId, userId, killReason);
22016                }
22017
22018                final PackageParser.Package p = mPackages.get(packageName);
22019                if (p != null && p.childPackages != null) {
22020                    final int N = p.childPackages.size();
22021                    mChildren = new PackageFreezer[N];
22022                    for (int i = 0; i < N; i++) {
22023                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22024                                userId, killReason);
22025                    }
22026                } else {
22027                    mChildren = null;
22028                }
22029            }
22030            mCloseGuard.open("close");
22031        }
22032
22033        @Override
22034        protected void finalize() throws Throwable {
22035            try {
22036                mCloseGuard.warnIfOpen();
22037                close();
22038            } finally {
22039                super.finalize();
22040            }
22041        }
22042
22043        @Override
22044        public void close() {
22045            mCloseGuard.close();
22046            if (mClosed.compareAndSet(false, true)) {
22047                synchronized (mPackages) {
22048                    if (mWeFroze) {
22049                        mFrozenPackages.remove(mPackageName);
22050                    }
22051
22052                    if (mChildren != null) {
22053                        for (PackageFreezer freezer : mChildren) {
22054                            freezer.close();
22055                        }
22056                    }
22057                }
22058            }
22059        }
22060    }
22061
22062    /**
22063     * Verify that given package is currently frozen.
22064     */
22065    private void checkPackageFrozen(String packageName) {
22066        synchronized (mPackages) {
22067            if (!mFrozenPackages.contains(packageName)) {
22068                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22069            }
22070        }
22071    }
22072
22073    @Override
22074    public int movePackage(final String packageName, final String volumeUuid) {
22075        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22076
22077        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22078        final int moveId = mNextMoveId.getAndIncrement();
22079        mHandler.post(new Runnable() {
22080            @Override
22081            public void run() {
22082                try {
22083                    movePackageInternal(packageName, volumeUuid, moveId, user);
22084                } catch (PackageManagerException e) {
22085                    Slog.w(TAG, "Failed to move " + packageName, e);
22086                    mMoveCallbacks.notifyStatusChanged(moveId,
22087                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22088                }
22089            }
22090        });
22091        return moveId;
22092    }
22093
22094    private void movePackageInternal(final String packageName, final String volumeUuid,
22095            final int moveId, UserHandle user) throws PackageManagerException {
22096        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22097        final PackageManager pm = mContext.getPackageManager();
22098
22099        final boolean currentAsec;
22100        final String currentVolumeUuid;
22101        final File codeFile;
22102        final String installerPackageName;
22103        final String packageAbiOverride;
22104        final int appId;
22105        final String seinfo;
22106        final String label;
22107        final int targetSdkVersion;
22108        final PackageFreezer freezer;
22109        final int[] installedUserIds;
22110
22111        // reader
22112        synchronized (mPackages) {
22113            final PackageParser.Package pkg = mPackages.get(packageName);
22114            final PackageSetting ps = mSettings.mPackages.get(packageName);
22115            if (pkg == null || ps == null) {
22116                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22117            }
22118
22119            if (pkg.applicationInfo.isSystemApp()) {
22120                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22121                        "Cannot move system application");
22122            }
22123
22124            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22125            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22126                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22127            if (isInternalStorage && !allow3rdPartyOnInternal) {
22128                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22129                        "3rd party apps are not allowed on internal storage");
22130            }
22131
22132            if (pkg.applicationInfo.isExternalAsec()) {
22133                currentAsec = true;
22134                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22135            } else if (pkg.applicationInfo.isForwardLocked()) {
22136                currentAsec = true;
22137                currentVolumeUuid = "forward_locked";
22138            } else {
22139                currentAsec = false;
22140                currentVolumeUuid = ps.volumeUuid;
22141
22142                final File probe = new File(pkg.codePath);
22143                final File probeOat = new File(probe, "oat");
22144                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22145                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22146                            "Move only supported for modern cluster style installs");
22147                }
22148            }
22149
22150            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22151                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22152                        "Package already moved to " + volumeUuid);
22153            }
22154            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22155                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22156                        "Device admin cannot be moved");
22157            }
22158
22159            if (mFrozenPackages.contains(packageName)) {
22160                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22161                        "Failed to move already frozen package");
22162            }
22163
22164            codeFile = new File(pkg.codePath);
22165            installerPackageName = ps.installerPackageName;
22166            packageAbiOverride = ps.cpuAbiOverrideString;
22167            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22168            seinfo = pkg.applicationInfo.seInfo;
22169            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22170            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22171            freezer = freezePackage(packageName, "movePackageInternal");
22172            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22173        }
22174
22175        final Bundle extras = new Bundle();
22176        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22177        extras.putString(Intent.EXTRA_TITLE, label);
22178        mMoveCallbacks.notifyCreated(moveId, extras);
22179
22180        int installFlags;
22181        final boolean moveCompleteApp;
22182        final File measurePath;
22183
22184        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22185            installFlags = INSTALL_INTERNAL;
22186            moveCompleteApp = !currentAsec;
22187            measurePath = Environment.getDataAppDirectory(volumeUuid);
22188        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22189            installFlags = INSTALL_EXTERNAL;
22190            moveCompleteApp = false;
22191            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22192        } else {
22193            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22194            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22195                    || !volume.isMountedWritable()) {
22196                freezer.close();
22197                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22198                        "Move location not mounted private volume");
22199            }
22200
22201            Preconditions.checkState(!currentAsec);
22202
22203            installFlags = INSTALL_INTERNAL;
22204            moveCompleteApp = true;
22205            measurePath = Environment.getDataAppDirectory(volumeUuid);
22206        }
22207
22208        final PackageStats stats = new PackageStats(null, -1);
22209        synchronized (mInstaller) {
22210            for (int userId : installedUserIds) {
22211                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22212                    freezer.close();
22213                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22214                            "Failed to measure package size");
22215                }
22216            }
22217        }
22218
22219        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22220                + stats.dataSize);
22221
22222        final long startFreeBytes = measurePath.getFreeSpace();
22223        final long sizeBytes;
22224        if (moveCompleteApp) {
22225            sizeBytes = stats.codeSize + stats.dataSize;
22226        } else {
22227            sizeBytes = stats.codeSize;
22228        }
22229
22230        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22231            freezer.close();
22232            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22233                    "Not enough free space to move");
22234        }
22235
22236        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22237
22238        final CountDownLatch installedLatch = new CountDownLatch(1);
22239        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22240            @Override
22241            public void onUserActionRequired(Intent intent) throws RemoteException {
22242                throw new IllegalStateException();
22243            }
22244
22245            @Override
22246            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22247                    Bundle extras) throws RemoteException {
22248                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22249                        + PackageManager.installStatusToString(returnCode, msg));
22250
22251                installedLatch.countDown();
22252                freezer.close();
22253
22254                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22255                switch (status) {
22256                    case PackageInstaller.STATUS_SUCCESS:
22257                        mMoveCallbacks.notifyStatusChanged(moveId,
22258                                PackageManager.MOVE_SUCCEEDED);
22259                        break;
22260                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22261                        mMoveCallbacks.notifyStatusChanged(moveId,
22262                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22263                        break;
22264                    default:
22265                        mMoveCallbacks.notifyStatusChanged(moveId,
22266                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22267                        break;
22268                }
22269            }
22270        };
22271
22272        final MoveInfo move;
22273        if (moveCompleteApp) {
22274            // Kick off a thread to report progress estimates
22275            new Thread() {
22276                @Override
22277                public void run() {
22278                    while (true) {
22279                        try {
22280                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22281                                break;
22282                            }
22283                        } catch (InterruptedException ignored) {
22284                        }
22285
22286                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22287                        final int progress = 10 + (int) MathUtils.constrain(
22288                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22289                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22290                    }
22291                }
22292            }.start();
22293
22294            final String dataAppName = codeFile.getName();
22295            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22296                    dataAppName, appId, seinfo, targetSdkVersion);
22297        } else {
22298            move = null;
22299        }
22300
22301        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22302
22303        final Message msg = mHandler.obtainMessage(INIT_COPY);
22304        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22305        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22306                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22307                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22308                PackageManager.INSTALL_REASON_UNKNOWN);
22309        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22310        msg.obj = params;
22311
22312        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22313                System.identityHashCode(msg.obj));
22314        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22315                System.identityHashCode(msg.obj));
22316
22317        mHandler.sendMessage(msg);
22318    }
22319
22320    @Override
22321    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22322        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22323
22324        final int realMoveId = mNextMoveId.getAndIncrement();
22325        final Bundle extras = new Bundle();
22326        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22327        mMoveCallbacks.notifyCreated(realMoveId, extras);
22328
22329        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22330            @Override
22331            public void onCreated(int moveId, Bundle extras) {
22332                // Ignored
22333            }
22334
22335            @Override
22336            public void onStatusChanged(int moveId, int status, long estMillis) {
22337                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22338            }
22339        };
22340
22341        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22342        storage.setPrimaryStorageUuid(volumeUuid, callback);
22343        return realMoveId;
22344    }
22345
22346    @Override
22347    public int getMoveStatus(int moveId) {
22348        mContext.enforceCallingOrSelfPermission(
22349                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22350        return mMoveCallbacks.mLastStatus.get(moveId);
22351    }
22352
22353    @Override
22354    public void registerMoveCallback(IPackageMoveObserver callback) {
22355        mContext.enforceCallingOrSelfPermission(
22356                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22357        mMoveCallbacks.register(callback);
22358    }
22359
22360    @Override
22361    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22362        mContext.enforceCallingOrSelfPermission(
22363                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22364        mMoveCallbacks.unregister(callback);
22365    }
22366
22367    @Override
22368    public boolean setInstallLocation(int loc) {
22369        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22370                null);
22371        if (getInstallLocation() == loc) {
22372            return true;
22373        }
22374        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22375                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22376            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22377                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22378            return true;
22379        }
22380        return false;
22381   }
22382
22383    @Override
22384    public int getInstallLocation() {
22385        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22386                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22387                PackageHelper.APP_INSTALL_AUTO);
22388    }
22389
22390    /** Called by UserManagerService */
22391    void cleanUpUser(UserManagerService userManager, int userHandle) {
22392        synchronized (mPackages) {
22393            mDirtyUsers.remove(userHandle);
22394            mUserNeedsBadging.delete(userHandle);
22395            mSettings.removeUserLPw(userHandle);
22396            mPendingBroadcasts.remove(userHandle);
22397            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22398            removeUnusedPackagesLPw(userManager, userHandle);
22399        }
22400    }
22401
22402    /**
22403     * We're removing userHandle and would like to remove any downloaded packages
22404     * that are no longer in use by any other user.
22405     * @param userHandle the user being removed
22406     */
22407    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22408        final boolean DEBUG_CLEAN_APKS = false;
22409        int [] users = userManager.getUserIds();
22410        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22411        while (psit.hasNext()) {
22412            PackageSetting ps = psit.next();
22413            if (ps.pkg == null) {
22414                continue;
22415            }
22416            final String packageName = ps.pkg.packageName;
22417            // Skip over if system app
22418            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22419                continue;
22420            }
22421            if (DEBUG_CLEAN_APKS) {
22422                Slog.i(TAG, "Checking package " + packageName);
22423            }
22424            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22425            if (keep) {
22426                if (DEBUG_CLEAN_APKS) {
22427                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22428                }
22429            } else {
22430                for (int i = 0; i < users.length; i++) {
22431                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22432                        keep = true;
22433                        if (DEBUG_CLEAN_APKS) {
22434                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22435                                    + users[i]);
22436                        }
22437                        break;
22438                    }
22439                }
22440            }
22441            if (!keep) {
22442                if (DEBUG_CLEAN_APKS) {
22443                    Slog.i(TAG, "  Removing package " + packageName);
22444                }
22445                mHandler.post(new Runnable() {
22446                    public void run() {
22447                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22448                                userHandle, 0);
22449                    } //end run
22450                });
22451            }
22452        }
22453    }
22454
22455    /** Called by UserManagerService */
22456    void createNewUser(int userId, String[] disallowedPackages) {
22457        synchronized (mInstallLock) {
22458            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22459        }
22460        synchronized (mPackages) {
22461            scheduleWritePackageRestrictionsLocked(userId);
22462            scheduleWritePackageListLocked(userId);
22463            applyFactoryDefaultBrowserLPw(userId);
22464            primeDomainVerificationsLPw(userId);
22465        }
22466    }
22467
22468    void onNewUserCreated(final int userId) {
22469        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22470        // If permission review for legacy apps is required, we represent
22471        // dagerous permissions for such apps as always granted runtime
22472        // permissions to keep per user flag state whether review is needed.
22473        // Hence, if a new user is added we have to propagate dangerous
22474        // permission grants for these legacy apps.
22475        if (mPermissionReviewRequired) {
22476            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22477                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22478        }
22479    }
22480
22481    @Override
22482    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22483        mContext.enforceCallingOrSelfPermission(
22484                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22485                "Only package verification agents can read the verifier device identity");
22486
22487        synchronized (mPackages) {
22488            return mSettings.getVerifierDeviceIdentityLPw();
22489        }
22490    }
22491
22492    @Override
22493    public void setPermissionEnforced(String permission, boolean enforced) {
22494        // TODO: Now that we no longer change GID for storage, this should to away.
22495        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22496                "setPermissionEnforced");
22497        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22498            synchronized (mPackages) {
22499                if (mSettings.mReadExternalStorageEnforced == null
22500                        || mSettings.mReadExternalStorageEnforced != enforced) {
22501                    mSettings.mReadExternalStorageEnforced = enforced;
22502                    mSettings.writeLPr();
22503                }
22504            }
22505            // kill any non-foreground processes so we restart them and
22506            // grant/revoke the GID.
22507            final IActivityManager am = ActivityManager.getService();
22508            if (am != null) {
22509                final long token = Binder.clearCallingIdentity();
22510                try {
22511                    am.killProcessesBelowForeground("setPermissionEnforcement");
22512                } catch (RemoteException e) {
22513                } finally {
22514                    Binder.restoreCallingIdentity(token);
22515                }
22516            }
22517        } else {
22518            throw new IllegalArgumentException("No selective enforcement for " + permission);
22519        }
22520    }
22521
22522    @Override
22523    @Deprecated
22524    public boolean isPermissionEnforced(String permission) {
22525        return true;
22526    }
22527
22528    @Override
22529    public boolean isStorageLow() {
22530        final long token = Binder.clearCallingIdentity();
22531        try {
22532            final DeviceStorageMonitorInternal
22533                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22534            if (dsm != null) {
22535                return dsm.isMemoryLow();
22536            } else {
22537                return false;
22538            }
22539        } finally {
22540            Binder.restoreCallingIdentity(token);
22541        }
22542    }
22543
22544    @Override
22545    public IPackageInstaller getPackageInstaller() {
22546        return mInstallerService;
22547    }
22548
22549    private boolean userNeedsBadging(int userId) {
22550        int index = mUserNeedsBadging.indexOfKey(userId);
22551        if (index < 0) {
22552            final UserInfo userInfo;
22553            final long token = Binder.clearCallingIdentity();
22554            try {
22555                userInfo = sUserManager.getUserInfo(userId);
22556            } finally {
22557                Binder.restoreCallingIdentity(token);
22558            }
22559            final boolean b;
22560            if (userInfo != null && userInfo.isManagedProfile()) {
22561                b = true;
22562            } else {
22563                b = false;
22564            }
22565            mUserNeedsBadging.put(userId, b);
22566            return b;
22567        }
22568        return mUserNeedsBadging.valueAt(index);
22569    }
22570
22571    @Override
22572    public KeySet getKeySetByAlias(String packageName, String alias) {
22573        if (packageName == null || alias == null) {
22574            return null;
22575        }
22576        synchronized(mPackages) {
22577            final PackageParser.Package pkg = mPackages.get(packageName);
22578            if (pkg == null) {
22579                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22580                throw new IllegalArgumentException("Unknown package: " + packageName);
22581            }
22582            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22583            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22584        }
22585    }
22586
22587    @Override
22588    public KeySet getSigningKeySet(String packageName) {
22589        if (packageName == null) {
22590            return null;
22591        }
22592        synchronized(mPackages) {
22593            final PackageParser.Package pkg = mPackages.get(packageName);
22594            if (pkg == null) {
22595                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22596                throw new IllegalArgumentException("Unknown package: " + packageName);
22597            }
22598            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22599                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22600                throw new SecurityException("May not access signing KeySet of other apps.");
22601            }
22602            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22603            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22604        }
22605    }
22606
22607    @Override
22608    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22609        if (packageName == null || ks == null) {
22610            return false;
22611        }
22612        synchronized(mPackages) {
22613            final PackageParser.Package pkg = mPackages.get(packageName);
22614            if (pkg == null) {
22615                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22616                throw new IllegalArgumentException("Unknown package: " + packageName);
22617            }
22618            IBinder ksh = ks.getToken();
22619            if (ksh instanceof KeySetHandle) {
22620                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22621                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22622            }
22623            return false;
22624        }
22625    }
22626
22627    @Override
22628    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22629        if (packageName == null || ks == null) {
22630            return false;
22631        }
22632        synchronized(mPackages) {
22633            final PackageParser.Package pkg = mPackages.get(packageName);
22634            if (pkg == null) {
22635                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22636                throw new IllegalArgumentException("Unknown package: " + packageName);
22637            }
22638            IBinder ksh = ks.getToken();
22639            if (ksh instanceof KeySetHandle) {
22640                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22641                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22642            }
22643            return false;
22644        }
22645    }
22646
22647    private void deletePackageIfUnusedLPr(final String packageName) {
22648        PackageSetting ps = mSettings.mPackages.get(packageName);
22649        if (ps == null) {
22650            return;
22651        }
22652        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22653            // TODO Implement atomic delete if package is unused
22654            // It is currently possible that the package will be deleted even if it is installed
22655            // after this method returns.
22656            mHandler.post(new Runnable() {
22657                public void run() {
22658                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22659                            0, PackageManager.DELETE_ALL_USERS);
22660                }
22661            });
22662        }
22663    }
22664
22665    /**
22666     * Check and throw if the given before/after packages would be considered a
22667     * downgrade.
22668     */
22669    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22670            throws PackageManagerException {
22671        if (after.versionCode < before.mVersionCode) {
22672            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22673                    "Update version code " + after.versionCode + " is older than current "
22674                    + before.mVersionCode);
22675        } else if (after.versionCode == before.mVersionCode) {
22676            if (after.baseRevisionCode < before.baseRevisionCode) {
22677                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22678                        "Update base revision code " + after.baseRevisionCode
22679                        + " is older than current " + before.baseRevisionCode);
22680            }
22681
22682            if (!ArrayUtils.isEmpty(after.splitNames)) {
22683                for (int i = 0; i < after.splitNames.length; i++) {
22684                    final String splitName = after.splitNames[i];
22685                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22686                    if (j != -1) {
22687                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22688                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22689                                    "Update split " + splitName + " revision code "
22690                                    + after.splitRevisionCodes[i] + " is older than current "
22691                                    + before.splitRevisionCodes[j]);
22692                        }
22693                    }
22694                }
22695            }
22696        }
22697    }
22698
22699    private static class MoveCallbacks extends Handler {
22700        private static final int MSG_CREATED = 1;
22701        private static final int MSG_STATUS_CHANGED = 2;
22702
22703        private final RemoteCallbackList<IPackageMoveObserver>
22704                mCallbacks = new RemoteCallbackList<>();
22705
22706        private final SparseIntArray mLastStatus = new SparseIntArray();
22707
22708        public MoveCallbacks(Looper looper) {
22709            super(looper);
22710        }
22711
22712        public void register(IPackageMoveObserver callback) {
22713            mCallbacks.register(callback);
22714        }
22715
22716        public void unregister(IPackageMoveObserver callback) {
22717            mCallbacks.unregister(callback);
22718        }
22719
22720        @Override
22721        public void handleMessage(Message msg) {
22722            final SomeArgs args = (SomeArgs) msg.obj;
22723            final int n = mCallbacks.beginBroadcast();
22724            for (int i = 0; i < n; i++) {
22725                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22726                try {
22727                    invokeCallback(callback, msg.what, args);
22728                } catch (RemoteException ignored) {
22729                }
22730            }
22731            mCallbacks.finishBroadcast();
22732            args.recycle();
22733        }
22734
22735        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22736                throws RemoteException {
22737            switch (what) {
22738                case MSG_CREATED: {
22739                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22740                    break;
22741                }
22742                case MSG_STATUS_CHANGED: {
22743                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22744                    break;
22745                }
22746            }
22747        }
22748
22749        private void notifyCreated(int moveId, Bundle extras) {
22750            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22751
22752            final SomeArgs args = SomeArgs.obtain();
22753            args.argi1 = moveId;
22754            args.arg2 = extras;
22755            obtainMessage(MSG_CREATED, args).sendToTarget();
22756        }
22757
22758        private void notifyStatusChanged(int moveId, int status) {
22759            notifyStatusChanged(moveId, status, -1);
22760        }
22761
22762        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22763            Slog.v(TAG, "Move " + moveId + " status " + status);
22764
22765            final SomeArgs args = SomeArgs.obtain();
22766            args.argi1 = moveId;
22767            args.argi2 = status;
22768            args.arg3 = estMillis;
22769            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22770
22771            synchronized (mLastStatus) {
22772                mLastStatus.put(moveId, status);
22773            }
22774        }
22775    }
22776
22777    private final static class OnPermissionChangeListeners extends Handler {
22778        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22779
22780        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22781                new RemoteCallbackList<>();
22782
22783        public OnPermissionChangeListeners(Looper looper) {
22784            super(looper);
22785        }
22786
22787        @Override
22788        public void handleMessage(Message msg) {
22789            switch (msg.what) {
22790                case MSG_ON_PERMISSIONS_CHANGED: {
22791                    final int uid = msg.arg1;
22792                    handleOnPermissionsChanged(uid);
22793                } break;
22794            }
22795        }
22796
22797        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22798            mPermissionListeners.register(listener);
22799
22800        }
22801
22802        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22803            mPermissionListeners.unregister(listener);
22804        }
22805
22806        public void onPermissionsChanged(int uid) {
22807            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22808                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22809            }
22810        }
22811
22812        private void handleOnPermissionsChanged(int uid) {
22813            final int count = mPermissionListeners.beginBroadcast();
22814            try {
22815                for (int i = 0; i < count; i++) {
22816                    IOnPermissionsChangeListener callback = mPermissionListeners
22817                            .getBroadcastItem(i);
22818                    try {
22819                        callback.onPermissionsChanged(uid);
22820                    } catch (RemoteException e) {
22821                        Log.e(TAG, "Permission listener is dead", e);
22822                    }
22823                }
22824            } finally {
22825                mPermissionListeners.finishBroadcast();
22826            }
22827        }
22828    }
22829
22830    private class PackageManagerInternalImpl extends PackageManagerInternal {
22831        @Override
22832        public void setLocationPackagesProvider(PackagesProvider provider) {
22833            synchronized (mPackages) {
22834                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22835            }
22836        }
22837
22838        @Override
22839        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22840            synchronized (mPackages) {
22841                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22842            }
22843        }
22844
22845        @Override
22846        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22847            synchronized (mPackages) {
22848                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22849            }
22850        }
22851
22852        @Override
22853        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22854            synchronized (mPackages) {
22855                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22856            }
22857        }
22858
22859        @Override
22860        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22861            synchronized (mPackages) {
22862                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22863            }
22864        }
22865
22866        @Override
22867        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22868            synchronized (mPackages) {
22869                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22870            }
22871        }
22872
22873        @Override
22874        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22875            synchronized (mPackages) {
22876                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22877                        packageName, userId);
22878            }
22879        }
22880
22881        @Override
22882        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22883            synchronized (mPackages) {
22884                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22885                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22886                        packageName, userId);
22887            }
22888        }
22889
22890        @Override
22891        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22892            synchronized (mPackages) {
22893                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22894                        packageName, userId);
22895            }
22896        }
22897
22898        @Override
22899        public void setKeepUninstalledPackages(final List<String> packageList) {
22900            Preconditions.checkNotNull(packageList);
22901            List<String> removedFromList = null;
22902            synchronized (mPackages) {
22903                if (mKeepUninstalledPackages != null) {
22904                    final int packagesCount = mKeepUninstalledPackages.size();
22905                    for (int i = 0; i < packagesCount; i++) {
22906                        String oldPackage = mKeepUninstalledPackages.get(i);
22907                        if (packageList != null && packageList.contains(oldPackage)) {
22908                            continue;
22909                        }
22910                        if (removedFromList == null) {
22911                            removedFromList = new ArrayList<>();
22912                        }
22913                        removedFromList.add(oldPackage);
22914                    }
22915                }
22916                mKeepUninstalledPackages = new ArrayList<>(packageList);
22917                if (removedFromList != null) {
22918                    final int removedCount = removedFromList.size();
22919                    for (int i = 0; i < removedCount; i++) {
22920                        deletePackageIfUnusedLPr(removedFromList.get(i));
22921                    }
22922                }
22923            }
22924        }
22925
22926        @Override
22927        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22928            synchronized (mPackages) {
22929                // If we do not support permission review, done.
22930                if (!mPermissionReviewRequired) {
22931                    return false;
22932                }
22933
22934                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22935                if (packageSetting == null) {
22936                    return false;
22937                }
22938
22939                // Permission review applies only to apps not supporting the new permission model.
22940                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22941                    return false;
22942                }
22943
22944                // Legacy apps have the permission and get user consent on launch.
22945                PermissionsState permissionsState = packageSetting.getPermissionsState();
22946                return permissionsState.isPermissionReviewRequired(userId);
22947            }
22948        }
22949
22950        @Override
22951        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22952            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22953        }
22954
22955        @Override
22956        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22957                int userId) {
22958            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22959        }
22960
22961        @Override
22962        public void setDeviceAndProfileOwnerPackages(
22963                int deviceOwnerUserId, String deviceOwnerPackage,
22964                SparseArray<String> profileOwnerPackages) {
22965            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22966                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22967        }
22968
22969        @Override
22970        public boolean isPackageDataProtected(int userId, String packageName) {
22971            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22972        }
22973
22974        @Override
22975        public boolean isPackageEphemeral(int userId, String packageName) {
22976            synchronized (mPackages) {
22977                final PackageSetting ps = mSettings.mPackages.get(packageName);
22978                return ps != null ? ps.getInstantApp(userId) : false;
22979            }
22980        }
22981
22982        @Override
22983        public boolean wasPackageEverLaunched(String packageName, int userId) {
22984            synchronized (mPackages) {
22985                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22986            }
22987        }
22988
22989        @Override
22990        public void grantRuntimePermission(String packageName, String name, int userId,
22991                boolean overridePolicy) {
22992            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22993                    overridePolicy);
22994        }
22995
22996        @Override
22997        public void revokeRuntimePermission(String packageName, String name, int userId,
22998                boolean overridePolicy) {
22999            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23000                    overridePolicy);
23001        }
23002
23003        @Override
23004        public String getNameForUid(int uid) {
23005            return PackageManagerService.this.getNameForUid(uid);
23006        }
23007
23008        @Override
23009        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23010                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23011            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23012                    responseObj, origIntent, resolvedType, callingPackage, userId);
23013        }
23014
23015        @Override
23016        public void grantEphemeralAccess(int userId, Intent intent,
23017                int targetAppId, int ephemeralAppId) {
23018            synchronized (mPackages) {
23019                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23020                        targetAppId, ephemeralAppId);
23021            }
23022        }
23023
23024        @Override
23025        public void pruneInstantApps() {
23026            synchronized (mPackages) {
23027                mInstantAppRegistry.pruneInstantAppsLPw();
23028            }
23029        }
23030
23031        @Override
23032        public String getSetupWizardPackageName() {
23033            return mSetupWizardPackage;
23034        }
23035
23036        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23037            if (policy != null) {
23038                mExternalSourcesPolicy = policy;
23039            }
23040        }
23041
23042        @Override
23043        public boolean isPackagePersistent(String packageName) {
23044            synchronized (mPackages) {
23045                PackageParser.Package pkg = mPackages.get(packageName);
23046                return pkg != null
23047                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23048                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23049                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23050                        : false;
23051            }
23052        }
23053
23054        @Override
23055        public List<PackageInfo> getOverlayPackages(int userId) {
23056            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23057            synchronized (mPackages) {
23058                for (PackageParser.Package p : mPackages.values()) {
23059                    if (p.mOverlayTarget != null) {
23060                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23061                        if (pkg != null) {
23062                            overlayPackages.add(pkg);
23063                        }
23064                    }
23065                }
23066            }
23067            return overlayPackages;
23068        }
23069
23070        @Override
23071        public List<String> getTargetPackageNames(int userId) {
23072            List<String> targetPackages = new ArrayList<>();
23073            synchronized (mPackages) {
23074                for (PackageParser.Package p : mPackages.values()) {
23075                    if (p.mOverlayTarget == null) {
23076                        targetPackages.add(p.packageName);
23077                    }
23078                }
23079            }
23080            return targetPackages;
23081        }
23082
23083        @Override
23084        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23085                @Nullable List<String> overlayPackageNames) {
23086            synchronized (mPackages) {
23087                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23088                    Slog.e(TAG, "failed to find package " + targetPackageName);
23089                    return false;
23090                }
23091
23092                ArrayList<String> paths = null;
23093                if (overlayPackageNames != null) {
23094                    final int N = overlayPackageNames.size();
23095                    paths = new ArrayList<>(N);
23096                    for (int i = 0; i < N; i++) {
23097                        final String packageName = overlayPackageNames.get(i);
23098                        final PackageParser.Package pkg = mPackages.get(packageName);
23099                        if (pkg == null) {
23100                            Slog.e(TAG, "failed to find package " + packageName);
23101                            return false;
23102                        }
23103                        paths.add(pkg.baseCodePath);
23104                    }
23105                }
23106
23107                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23108                    mEnabledOverlayPaths.get(userId);
23109                if (userSpecificOverlays == null) {
23110                    userSpecificOverlays = new ArrayMap<>();
23111                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23112                }
23113
23114                if (paths != null && paths.size() > 0) {
23115                    userSpecificOverlays.put(targetPackageName, paths);
23116                } else {
23117                    userSpecificOverlays.remove(targetPackageName);
23118                }
23119                return true;
23120            }
23121        }
23122
23123        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23124                int flags, int userId) {
23125            return resolveIntentInternal(
23126                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23127        }
23128    }
23129
23130    @Override
23131    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23132        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23133        synchronized (mPackages) {
23134            final long identity = Binder.clearCallingIdentity();
23135            try {
23136                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23137                        packageNames, userId);
23138            } finally {
23139                Binder.restoreCallingIdentity(identity);
23140            }
23141        }
23142    }
23143
23144    @Override
23145    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23146        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23147        synchronized (mPackages) {
23148            final long identity = Binder.clearCallingIdentity();
23149            try {
23150                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23151                        packageNames, userId);
23152            } finally {
23153                Binder.restoreCallingIdentity(identity);
23154            }
23155        }
23156    }
23157
23158    private static void enforceSystemOrPhoneCaller(String tag) {
23159        int callingUid = Binder.getCallingUid();
23160        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23161            throw new SecurityException(
23162                    "Cannot call " + tag + " from UID " + callingUid);
23163        }
23164    }
23165
23166    boolean isHistoricalPackageUsageAvailable() {
23167        return mPackageUsage.isHistoricalPackageUsageAvailable();
23168    }
23169
23170    /**
23171     * Return a <b>copy</b> of the collection of packages known to the package manager.
23172     * @return A copy of the values of mPackages.
23173     */
23174    Collection<PackageParser.Package> getPackages() {
23175        synchronized (mPackages) {
23176            return new ArrayList<>(mPackages.values());
23177        }
23178    }
23179
23180    /**
23181     * Logs process start information (including base APK hash) to the security log.
23182     * @hide
23183     */
23184    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23185            String apkFile, int pid) {
23186        if (!SecurityLog.isLoggingEnabled()) {
23187            return;
23188        }
23189        Bundle data = new Bundle();
23190        data.putLong("startTimestamp", System.currentTimeMillis());
23191        data.putString("processName", processName);
23192        data.putInt("uid", uid);
23193        data.putString("seinfo", seinfo);
23194        data.putString("apkFile", apkFile);
23195        data.putInt("pid", pid);
23196        Message msg = mProcessLoggingHandler.obtainMessage(
23197                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23198        msg.setData(data);
23199        mProcessLoggingHandler.sendMessage(msg);
23200    }
23201
23202    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23203        return mCompilerStats.getPackageStats(pkgName);
23204    }
23205
23206    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23207        return getOrCreateCompilerPackageStats(pkg.packageName);
23208    }
23209
23210    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23211        return mCompilerStats.getOrCreatePackageStats(pkgName);
23212    }
23213
23214    public void deleteCompilerPackageStats(String pkgName) {
23215        mCompilerStats.deletePackageStats(pkgName);
23216    }
23217
23218    @Override
23219    public int getInstallReason(String packageName, int userId) {
23220        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23221                true /* requireFullPermission */, false /* checkShell */,
23222                "get install reason");
23223        synchronized (mPackages) {
23224            final PackageSetting ps = mSettings.mPackages.get(packageName);
23225            if (ps != null) {
23226                return ps.getInstallReason(userId);
23227            }
23228        }
23229        return PackageManager.INSTALL_REASON_UNKNOWN;
23230    }
23231
23232    @Override
23233    public boolean canRequestPackageInstalls(String packageName, int userId) {
23234        int callingUid = Binder.getCallingUid();
23235        int uid = getPackageUid(packageName, 0, userId);
23236        if (callingUid != uid && callingUid != Process.ROOT_UID
23237                && callingUid != Process.SYSTEM_UID) {
23238            throw new SecurityException(
23239                    "Caller uid " + callingUid + " does not own package " + packageName);
23240        }
23241        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23242        if (info == null) {
23243            return false;
23244        }
23245        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23246            throw new UnsupportedOperationException(
23247                    "Operation only supported on apps targeting Android O or higher");
23248        }
23249        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23250        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23251        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23252            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23253        }
23254        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23255            return false;
23256        }
23257        if (mExternalSourcesPolicy != null) {
23258            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23259            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23260                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23261            }
23262        }
23263        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23264    }
23265}
23266