PackageManagerService.java revision 22d8bb2ca310a929803be4c4ab99c44bc43d1a93
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
103
104import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.ServiceInfo;
168import android.content.pm.SharedLibraryInfo;
169import android.content.pm.Signature;
170import android.content.pm.UserInfo;
171import android.content.pm.VerifierDeviceIdentity;
172import android.content.pm.VerifierInfo;
173import android.content.pm.VersionedPackage;
174import android.content.res.Resources;
175import android.database.ContentObserver;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.BootTimingsTraceLog;
225import android.util.DisplayMetrics;
226import android.util.EventLog;
227import android.util.ExceptionUtils;
228import android.util.Log;
229import android.util.LogPrinter;
230import android.util.MathUtils;
231import android.util.PackageUtils;
232import android.util.Pair;
233import android.util.PrintStreamPrinter;
234import android.util.Slog;
235import android.util.SparseArray;
236import android.util.SparseBooleanArray;
237import android.util.SparseIntArray;
238import android.util.Xml;
239import android.util.jar.StrictJarFile;
240import android.util.proto.ProtoOutputStream;
241import android.view.Display;
242
243import com.android.internal.R;
244import com.android.internal.annotations.GuardedBy;
245import com.android.internal.app.IMediaContainerService;
246import com.android.internal.app.ResolverActivity;
247import com.android.internal.content.NativeLibraryHelper;
248import com.android.internal.content.PackageHelper;
249import com.android.internal.logging.MetricsLogger;
250import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
251import com.android.internal.os.IParcelFileDescriptorFactory;
252import com.android.internal.os.RoSystemProperties;
253import com.android.internal.os.SomeArgs;
254import com.android.internal.os.Zygote;
255import com.android.internal.telephony.CarrierAppUtils;
256import com.android.internal.util.ArrayUtils;
257import com.android.internal.util.ConcurrentUtils;
258import com.android.internal.util.DumpUtils;
259import com.android.internal.util.FastPrintWriter;
260import com.android.internal.util.FastXmlSerializer;
261import com.android.internal.util.IndentingPrintWriter;
262import com.android.internal.util.Preconditions;
263import com.android.internal.util.XmlUtils;
264import com.android.server.AttributeCache;
265import com.android.server.DeviceIdleController;
266import com.android.server.EventLogTags;
267import com.android.server.FgThread;
268import com.android.server.IntentResolver;
269import com.android.server.LocalServices;
270import com.android.server.LockGuard;
271import com.android.server.ServiceThread;
272import com.android.server.SystemConfig;
273import com.android.server.SystemServerInitThreadPool;
274import com.android.server.Watchdog;
275import com.android.server.net.NetworkPolicyManagerInternal;
276import com.android.server.pm.Installer.InstallerException;
277import com.android.server.pm.PermissionsState.PermissionState;
278import com.android.server.pm.Settings.DatabaseVersion;
279import com.android.server.pm.Settings.VersionInfo;
280import com.android.server.pm.dex.DexManager;
281import com.android.server.storage.DeviceStorageMonitorInternal;
282
283import dalvik.system.CloseGuard;
284import dalvik.system.DexFile;
285import dalvik.system.VMRuntime;
286
287import libcore.io.IoUtils;
288import libcore.util.EmptyArray;
289
290import org.xmlpull.v1.XmlPullParser;
291import org.xmlpull.v1.XmlPullParserException;
292import org.xmlpull.v1.XmlSerializer;
293
294import java.io.BufferedOutputStream;
295import java.io.BufferedReader;
296import java.io.ByteArrayInputStream;
297import java.io.ByteArrayOutputStream;
298import java.io.File;
299import java.io.FileDescriptor;
300import java.io.FileInputStream;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub
369        implements PackageSender {
370    static final String TAG = "PackageManager";
371    static final boolean DEBUG_SETTINGS = false;
372    static final boolean DEBUG_PREFERRED = false;
373    static final boolean DEBUG_UPGRADE = false;
374    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
375    private static final boolean DEBUG_BACKUP = false;
376    private static final boolean DEBUG_INSTALL = false;
377    private static final boolean DEBUG_REMOVE = false;
378    private static final boolean DEBUG_BROADCASTS = false;
379    private static final boolean DEBUG_SHOW_INFO = false;
380    private static final boolean DEBUG_PACKAGE_INFO = false;
381    private static final boolean DEBUG_INTENT_MATCHING = false;
382    private static final boolean DEBUG_PACKAGE_SCANNING = false;
383    private static final boolean DEBUG_VERIFY = false;
384    private static final boolean DEBUG_FILTERS = false;
385
386    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
387    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
388    // user, but by default initialize to this.
389    public static final boolean DEBUG_DEXOPT = false;
390
391    private static final boolean DEBUG_ABI_SELECTION = false;
392    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
393    private static final boolean DEBUG_TRIAGED_MISSING = false;
394    private static final boolean DEBUG_APP_DATA = false;
395
396    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
397    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
398
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    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
541    public static final int REASON_LAST = REASON_AB_OTA;
542
543    /** All dangerous permission names in the same order as the events in MetricsEvent */
544    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
545            Manifest.permission.READ_CALENDAR,
546            Manifest.permission.WRITE_CALENDAR,
547            Manifest.permission.CAMERA,
548            Manifest.permission.READ_CONTACTS,
549            Manifest.permission.WRITE_CONTACTS,
550            Manifest.permission.GET_ACCOUNTS,
551            Manifest.permission.ACCESS_FINE_LOCATION,
552            Manifest.permission.ACCESS_COARSE_LOCATION,
553            Manifest.permission.RECORD_AUDIO,
554            Manifest.permission.READ_PHONE_STATE,
555            Manifest.permission.CALL_PHONE,
556            Manifest.permission.READ_CALL_LOG,
557            Manifest.permission.WRITE_CALL_LOG,
558            Manifest.permission.ADD_VOICEMAIL,
559            Manifest.permission.USE_SIP,
560            Manifest.permission.PROCESS_OUTGOING_CALLS,
561            Manifest.permission.READ_CELL_BROADCASTS,
562            Manifest.permission.BODY_SENSORS,
563            Manifest.permission.SEND_SMS,
564            Manifest.permission.RECEIVE_SMS,
565            Manifest.permission.READ_SMS,
566            Manifest.permission.RECEIVE_WAP_PUSH,
567            Manifest.permission.RECEIVE_MMS,
568            Manifest.permission.READ_EXTERNAL_STORAGE,
569            Manifest.permission.WRITE_EXTERNAL_STORAGE,
570            Manifest.permission.READ_PHONE_NUMBERS,
571            Manifest.permission.ANSWER_PHONE_CALLS);
572
573
574    /**
575     * Version number for the package parser cache. Increment this whenever the format or
576     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
577     */
578    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
579
580    /**
581     * Whether the package parser cache is enabled.
582     */
583    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
584
585    final ServiceThread mHandlerThread;
586
587    final PackageHandler mHandler;
588
589    private final ProcessLoggingHandler mProcessLoggingHandler;
590
591    /**
592     * Messages for {@link #mHandler} that need to wait for system ready before
593     * being dispatched.
594     */
595    private ArrayList<Message> mPostSystemReadyMessages;
596
597    final int mSdkVersion = Build.VERSION.SDK_INT;
598
599    final Context mContext;
600    final boolean mFactoryTest;
601    final boolean mOnlyCore;
602    final DisplayMetrics mMetrics;
603    final int mDefParseFlags;
604    final String[] mSeparateProcesses;
605    final boolean mIsUpgrade;
606    final boolean mIsPreNUpgrade;
607    final boolean mIsPreNMR1Upgrade;
608
609    // Have we told the Activity Manager to whitelist the default container service by uid yet?
610    @GuardedBy("mPackages")
611    boolean mDefaultContainerWhitelisted = false;
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    // Keys are isolated uids and values are the uid of the application
657    // that created the isolated proccess.
658    @GuardedBy("mPackages")
659    final SparseIntArray mIsolatedOwners = new SparseIntArray();
660
661    // List of APK paths to load for each user and package. This data is never
662    // persisted by the package manager. Instead, the overlay manager will
663    // ensure the data is up-to-date in runtime.
664    @GuardedBy("mPackages")
665    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
666        new SparseArray<ArrayMap<String, ArrayList<String>>>();
667
668    /**
669     * Tracks new system packages [received in an OTA] that we expect to
670     * find updated user-installed versions. Keys are package name, values
671     * are package location.
672     */
673    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
674    /**
675     * Tracks high priority intent filters for protected actions. During boot, certain
676     * filter actions are protected and should never be allowed to have a high priority
677     * intent filter for them. However, there is one, and only one exception -- the
678     * setup wizard. It must be able to define a high priority intent filter for these
679     * actions to ensure there are no escapes from the wizard. We need to delay processing
680     * of these during boot as we need to look at all of the system packages in order
681     * to know which component is the setup wizard.
682     */
683    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
684    /**
685     * Whether or not processing protected filters should be deferred.
686     */
687    private boolean mDeferProtectedFilters = true;
688
689    /**
690     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
691     */
692    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
693    /**
694     * Whether or not system app permissions should be promoted from install to runtime.
695     */
696    boolean mPromoteSystemApps;
697
698    @GuardedBy("mPackages")
699    final Settings mSettings;
700
701    /**
702     * Set of package names that are currently "frozen", which means active
703     * surgery is being done on the code/data for that package. The platform
704     * will refuse to launch frozen packages to avoid race conditions.
705     *
706     * @see PackageFreezer
707     */
708    @GuardedBy("mPackages")
709    final ArraySet<String> mFrozenPackages = new ArraySet<>();
710
711    final ProtectedPackages mProtectedPackages;
712
713    boolean mFirstBoot;
714
715    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
716
717    // System configuration read by SystemConfig.
718    final int[] mGlobalGids;
719    final SparseArray<ArraySet<String>> mSystemPermissions;
720    @GuardedBy("mAvailableFeatures")
721    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
722
723    // If mac_permissions.xml was found for seinfo labeling.
724    boolean mFoundPolicyFile;
725
726    private final InstantAppRegistry mInstantAppRegistry;
727
728    @GuardedBy("mPackages")
729    int mChangedPackagesSequenceNumber;
730    /**
731     * List of changed [installed, removed or updated] packages.
732     * mapping from user id -> sequence number -> package name
733     */
734    @GuardedBy("mPackages")
735    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
736    /**
737     * The sequence number of the last change to a package.
738     * mapping from user id -> package name -> sequence number
739     */
740    @GuardedBy("mPackages")
741    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
742
743    class PackageParserCallback implements PackageParser.Callback {
744        @Override public final boolean hasFeature(String feature) {
745            return PackageManagerService.this.hasSystemFeature(feature, 0);
746        }
747
748        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
749                Collection<PackageParser.Package> allPackages, String targetPackageName) {
750            List<PackageParser.Package> overlayPackages = null;
751            for (PackageParser.Package p : allPackages) {
752                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
753                    if (overlayPackages == null) {
754                        overlayPackages = new ArrayList<PackageParser.Package>();
755                    }
756                    overlayPackages.add(p);
757                }
758            }
759            if (overlayPackages != null) {
760                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
761                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
762                        return p1.mOverlayPriority - p2.mOverlayPriority;
763                    }
764                };
765                Collections.sort(overlayPackages, cmp);
766            }
767            return overlayPackages;
768        }
769
770        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
771                String targetPackageName, String targetPath) {
772            if ("android".equals(targetPackageName)) {
773                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
774                // native AssetManager.
775                return null;
776            }
777            List<PackageParser.Package> overlayPackages =
778                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
779            if (overlayPackages == null || overlayPackages.isEmpty()) {
780                return null;
781            }
782            List<String> overlayPathList = null;
783            for (PackageParser.Package overlayPackage : overlayPackages) {
784                if (targetPath == null) {
785                    if (overlayPathList == null) {
786                        overlayPathList = new ArrayList<String>();
787                    }
788                    overlayPathList.add(overlayPackage.baseCodePath);
789                    continue;
790                }
791
792                try {
793                    // Creates idmaps for system to parse correctly the Android manifest of the
794                    // target package.
795                    //
796                    // OverlayManagerService will update each of them with a correct gid from its
797                    // target package app id.
798                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
799                            UserHandle.getSharedAppGid(
800                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
801                    if (overlayPathList == null) {
802                        overlayPathList = new ArrayList<String>();
803                    }
804                    overlayPathList.add(overlayPackage.baseCodePath);
805                } catch (InstallerException e) {
806                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
807                            overlayPackage.baseCodePath);
808                }
809            }
810            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
811        }
812
813        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
814            synchronized (mPackages) {
815                return getStaticOverlayPathsLocked(
816                        mPackages.values(), targetPackageName, targetPath);
817            }
818        }
819
820        @Override public final String[] getOverlayApks(String targetPackageName) {
821            return getStaticOverlayPaths(targetPackageName, null);
822        }
823
824        @Override public final String[] getOverlayPaths(String targetPackageName,
825                String targetPath) {
826            return getStaticOverlayPaths(targetPackageName, targetPath);
827        }
828    };
829
830    class ParallelPackageParserCallback extends PackageParserCallback {
831        List<PackageParser.Package> mOverlayPackages = null;
832
833        void findStaticOverlayPackages() {
834            synchronized (mPackages) {
835                for (PackageParser.Package p : mPackages.values()) {
836                    if (p.mIsStaticOverlay) {
837                        if (mOverlayPackages == null) {
838                            mOverlayPackages = new ArrayList<PackageParser.Package>();
839                        }
840                        mOverlayPackages.add(p);
841                    }
842                }
843            }
844        }
845
846        @Override
847        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            // We can trust mOverlayPackages without holding mPackages because package uninstall
849            // can't happen while running parallel parsing.
850            // Moreover holding mPackages on each parsing thread causes dead-lock.
851            return mOverlayPackages == null ? null :
852                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
853        }
854    }
855
856    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
857    final ParallelPackageParserCallback mParallelPackageParserCallback =
858            new ParallelPackageParserCallback();
859
860    public static final class SharedLibraryEntry {
861        public final String path;
862        public final String apk;
863        public final SharedLibraryInfo info;
864
865        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
866                String declaringPackageName, int declaringPackageVersionCode) {
867            path = _path;
868            apk = _apk;
869            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
870                    declaringPackageName, declaringPackageVersionCode), null);
871        }
872    }
873
874    // Currently known shared libraries.
875    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
876    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
877            new ArrayMap<>();
878
879    // All available activities, for your resolving pleasure.
880    final ActivityIntentResolver mActivities =
881            new ActivityIntentResolver();
882
883    // All available receivers, for your resolving pleasure.
884    final ActivityIntentResolver mReceivers =
885            new ActivityIntentResolver();
886
887    // All available services, for your resolving pleasure.
888    final ServiceIntentResolver mServices = new ServiceIntentResolver();
889
890    // All available providers, for your resolving pleasure.
891    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
892
893    // Mapping from provider base names (first directory in content URI codePath)
894    // to the provider information.
895    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
896            new ArrayMap<String, PackageParser.Provider>();
897
898    // Mapping from instrumentation class names to info about them.
899    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
900            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
901
902    // Mapping from permission names to info about them.
903    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
904            new ArrayMap<String, PackageParser.PermissionGroup>();
905
906    // Packages whose data we have transfered into another package, thus
907    // should no longer exist.
908    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
909
910    // Broadcast actions that are only available to the system.
911    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
912
913    /** List of packages waiting for verification. */
914    final SparseArray<PackageVerificationState> mPendingVerification
915            = new SparseArray<PackageVerificationState>();
916
917    /** Set of packages associated with each app op permission. */
918    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
919
920    final PackageInstallerService mInstallerService;
921
922    private final PackageDexOptimizer mPackageDexOptimizer;
923    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
924    // is used by other apps).
925    private final DexManager mDexManager;
926
927    private AtomicInteger mNextMoveId = new AtomicInteger();
928    private final MoveCallbacks mMoveCallbacks;
929
930    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
931
932    // Cache of users who need badging.
933    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
934
935    /** Token for keys in mPendingVerification. */
936    private int mPendingVerificationToken = 0;
937
938    volatile boolean mSystemReady;
939    volatile boolean mSafeMode;
940    volatile boolean mHasSystemUidErrors;
941    private volatile boolean mEphemeralAppsDisabled;
942
943    ApplicationInfo mAndroidApplication;
944    final ActivityInfo mResolveActivity = new ActivityInfo();
945    final ResolveInfo mResolveInfo = new ResolveInfo();
946    ComponentName mResolveComponentName;
947    PackageParser.Package mPlatformPackage;
948    ComponentName mCustomResolverComponentName;
949
950    boolean mResolverReplaced = false;
951
952    private final @Nullable ComponentName mIntentFilterVerifierComponent;
953    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
954
955    private int mIntentFilterVerificationToken = 0;
956
957    /** The service connection to the ephemeral resolver */
958    final EphemeralResolverConnection mInstantAppResolverConnection;
959    /** Component used to show resolver settings for Instant Apps */
960    final ComponentName mInstantAppResolverSettingsComponent;
961
962    /** Activity used to install instant applications */
963    ActivityInfo mInstantAppInstallerActivity;
964    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
965
966    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
967            = new SparseArray<IntentFilterVerificationState>();
968
969    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
970
971    // List of packages names to keep cached, even if they are uninstalled for all users
972    private List<String> mKeepUninstalledPackages;
973
974    private UserManagerInternal mUserManagerInternal;
975
976    private DeviceIdleController.LocalService mDeviceIdleController;
977
978    private File mCacheDir;
979
980    private ArraySet<String> mPrivappPermissionsViolations;
981
982    private Future<?> mPrepareAppDataFuture;
983
984    private static class IFVerificationParams {
985        PackageParser.Package pkg;
986        boolean replacing;
987        int userId;
988        int verifierUid;
989
990        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
991                int _userId, int _verifierUid) {
992            pkg = _pkg;
993            replacing = _replacing;
994            userId = _userId;
995            replacing = _replacing;
996            verifierUid = _verifierUid;
997        }
998    }
999
1000    private interface IntentFilterVerifier<T extends IntentFilter> {
1001        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1002                                               T filter, String packageName);
1003        void startVerifications(int userId);
1004        void receiveVerificationResponse(int verificationId);
1005    }
1006
1007    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1008        private Context mContext;
1009        private ComponentName mIntentFilterVerifierComponent;
1010        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1011
1012        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1013            mContext = context;
1014            mIntentFilterVerifierComponent = verifierComponent;
1015        }
1016
1017        private String getDefaultScheme() {
1018            return IntentFilter.SCHEME_HTTPS;
1019        }
1020
1021        @Override
1022        public void startVerifications(int userId) {
1023            // Launch verifications requests
1024            int count = mCurrentIntentFilterVerifications.size();
1025            for (int n=0; n<count; n++) {
1026                int verificationId = mCurrentIntentFilterVerifications.get(n);
1027                final IntentFilterVerificationState ivs =
1028                        mIntentFilterVerificationStates.get(verificationId);
1029
1030                String packageName = ivs.getPackageName();
1031
1032                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1033                final int filterCount = filters.size();
1034                ArraySet<String> domainsSet = new ArraySet<>();
1035                for (int m=0; m<filterCount; m++) {
1036                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1037                    domainsSet.addAll(filter.getHostsList());
1038                }
1039                synchronized (mPackages) {
1040                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1041                            packageName, domainsSet) != null) {
1042                        scheduleWriteSettingsLocked();
1043                    }
1044                }
1045                sendVerificationRequest(userId, verificationId, ivs);
1046            }
1047            mCurrentIntentFilterVerifications.clear();
1048        }
1049
1050        private void sendVerificationRequest(int userId, int verificationId,
1051                IntentFilterVerificationState ivs) {
1052
1053            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1054            verificationIntent.putExtra(
1055                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1056                    verificationId);
1057            verificationIntent.putExtra(
1058                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1059                    getDefaultScheme());
1060            verificationIntent.putExtra(
1061                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1062                    ivs.getHostsString());
1063            verificationIntent.putExtra(
1064                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1065                    ivs.getPackageName());
1066            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1067            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1068
1069            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1070            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1071                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1072                    userId, false, "intent filter verifier");
1073
1074            UserHandle user = new UserHandle(userId);
1075            mContext.sendBroadcastAsUser(verificationIntent, user);
1076            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1077                    "Sending IntentFilter verification broadcast");
1078        }
1079
1080        public void receiveVerificationResponse(int verificationId) {
1081            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1082
1083            final boolean verified = ivs.isVerified();
1084
1085            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1086            final int count = filters.size();
1087            if (DEBUG_DOMAIN_VERIFICATION) {
1088                Slog.i(TAG, "Received verification response " + verificationId
1089                        + " for " + count + " filters, verified=" + verified);
1090            }
1091            for (int n=0; n<count; n++) {
1092                PackageParser.ActivityIntentInfo filter = filters.get(n);
1093                filter.setVerified(verified);
1094
1095                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1096                        + " verified with result:" + verified + " and hosts:"
1097                        + ivs.getHostsString());
1098            }
1099
1100            mIntentFilterVerificationStates.remove(verificationId);
1101
1102            final String packageName = ivs.getPackageName();
1103            IntentFilterVerificationInfo ivi = null;
1104
1105            synchronized (mPackages) {
1106                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1107            }
1108            if (ivi == null) {
1109                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1110                        + verificationId + " packageName:" + packageName);
1111                return;
1112            }
1113            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1114                    "Updating IntentFilterVerificationInfo for package " + packageName
1115                            +" verificationId:" + verificationId);
1116
1117            synchronized (mPackages) {
1118                if (verified) {
1119                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1120                } else {
1121                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1122                }
1123                scheduleWriteSettingsLocked();
1124
1125                final int userId = ivs.getUserId();
1126                if (userId != UserHandle.USER_ALL) {
1127                    final int userStatus =
1128                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1129
1130                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1131                    boolean needUpdate = false;
1132
1133                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1134                    // already been set by the User thru the Disambiguation dialog
1135                    switch (userStatus) {
1136                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1137                            if (verified) {
1138                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1139                            } else {
1140                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1141                            }
1142                            needUpdate = true;
1143                            break;
1144
1145                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1146                            if (verified) {
1147                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1148                                needUpdate = true;
1149                            }
1150                            break;
1151
1152                        default:
1153                            // Nothing to do
1154                    }
1155
1156                    if (needUpdate) {
1157                        mSettings.updateIntentFilterVerificationStatusLPw(
1158                                packageName, updatedStatus, userId);
1159                        scheduleWritePackageRestrictionsLocked(userId);
1160                    }
1161                }
1162            }
1163        }
1164
1165        @Override
1166        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1167                    ActivityIntentInfo filter, String packageName) {
1168            if (!hasValidDomains(filter)) {
1169                return false;
1170            }
1171            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1172            if (ivs == null) {
1173                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1174                        packageName);
1175            }
1176            if (DEBUG_DOMAIN_VERIFICATION) {
1177                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1178            }
1179            ivs.addFilter(filter);
1180            return true;
1181        }
1182
1183        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1184                int userId, int verificationId, String packageName) {
1185            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1186                    verifierUid, userId, packageName);
1187            ivs.setPendingState();
1188            synchronized (mPackages) {
1189                mIntentFilterVerificationStates.append(verificationId, ivs);
1190                mCurrentIntentFilterVerifications.add(verificationId);
1191            }
1192            return ivs;
1193        }
1194    }
1195
1196    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1197        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1198                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1199                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1200    }
1201
1202    // Set of pending broadcasts for aggregating enable/disable of components.
1203    static class PendingPackageBroadcasts {
1204        // for each user id, a map of <package name -> components within that package>
1205        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1206
1207        public PendingPackageBroadcasts() {
1208            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1209        }
1210
1211        public ArrayList<String> get(int userId, String packageName) {
1212            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1213            return packages.get(packageName);
1214        }
1215
1216        public void put(int userId, String packageName, ArrayList<String> components) {
1217            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1218            packages.put(packageName, components);
1219        }
1220
1221        public void remove(int userId, String packageName) {
1222            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1223            if (packages != null) {
1224                packages.remove(packageName);
1225            }
1226        }
1227
1228        public void remove(int userId) {
1229            mUidMap.remove(userId);
1230        }
1231
1232        public int userIdCount() {
1233            return mUidMap.size();
1234        }
1235
1236        public int userIdAt(int n) {
1237            return mUidMap.keyAt(n);
1238        }
1239
1240        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1241            return mUidMap.get(userId);
1242        }
1243
1244        public int size() {
1245            // total number of pending broadcast entries across all userIds
1246            int num = 0;
1247            for (int i = 0; i< mUidMap.size(); i++) {
1248                num += mUidMap.valueAt(i).size();
1249            }
1250            return num;
1251        }
1252
1253        public void clear() {
1254            mUidMap.clear();
1255        }
1256
1257        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1258            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1259            if (map == null) {
1260                map = new ArrayMap<String, ArrayList<String>>();
1261                mUidMap.put(userId, map);
1262            }
1263            return map;
1264        }
1265    }
1266    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1267
1268    // Service Connection to remote media container service to copy
1269    // package uri's from external media onto secure containers
1270    // or internal storage.
1271    private IMediaContainerService mContainerService = null;
1272
1273    static final int SEND_PENDING_BROADCAST = 1;
1274    static final int MCS_BOUND = 3;
1275    static final int END_COPY = 4;
1276    static final int INIT_COPY = 5;
1277    static final int MCS_UNBIND = 6;
1278    static final int START_CLEANING_PACKAGE = 7;
1279    static final int FIND_INSTALL_LOC = 8;
1280    static final int POST_INSTALL = 9;
1281    static final int MCS_RECONNECT = 10;
1282    static final int MCS_GIVE_UP = 11;
1283    static final int UPDATED_MEDIA_STATUS = 12;
1284    static final int WRITE_SETTINGS = 13;
1285    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1286    static final int PACKAGE_VERIFIED = 15;
1287    static final int CHECK_PENDING_VERIFICATION = 16;
1288    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1289    static final int INTENT_FILTER_VERIFIED = 18;
1290    static final int WRITE_PACKAGE_LIST = 19;
1291    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1292
1293    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1294
1295    // Delay time in millisecs
1296    static final int BROADCAST_DELAY = 10 * 1000;
1297
1298    static UserManagerService sUserManager;
1299
1300    // Stores a list of users whose package restrictions file needs to be updated
1301    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1302
1303    final private DefaultContainerConnection mDefContainerConn =
1304            new DefaultContainerConnection();
1305    class DefaultContainerConnection implements ServiceConnection {
1306        public void onServiceConnected(ComponentName name, IBinder service) {
1307            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1308            final IMediaContainerService imcs = IMediaContainerService.Stub
1309                    .asInterface(Binder.allowBlocking(service));
1310            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1311        }
1312
1313        public void onServiceDisconnected(ComponentName name) {
1314            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1315        }
1316    }
1317
1318    // Recordkeeping of restore-after-install operations that are currently in flight
1319    // between the Package Manager and the Backup Manager
1320    static class PostInstallData {
1321        public InstallArgs args;
1322        public PackageInstalledInfo res;
1323
1324        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1325            args = _a;
1326            res = _r;
1327        }
1328    }
1329
1330    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1331    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1332
1333    // XML tags for backup/restore of various bits of state
1334    private static final String TAG_PREFERRED_BACKUP = "pa";
1335    private static final String TAG_DEFAULT_APPS = "da";
1336    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1337
1338    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1339    private static final String TAG_ALL_GRANTS = "rt-grants";
1340    private static final String TAG_GRANT = "grant";
1341    private static final String ATTR_PACKAGE_NAME = "pkg";
1342
1343    private static final String TAG_PERMISSION = "perm";
1344    private static final String ATTR_PERMISSION_NAME = "name";
1345    private static final String ATTR_IS_GRANTED = "g";
1346    private static final String ATTR_USER_SET = "set";
1347    private static final String ATTR_USER_FIXED = "fixed";
1348    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1349
1350    // System/policy permission grants are not backed up
1351    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1352            FLAG_PERMISSION_POLICY_FIXED
1353            | FLAG_PERMISSION_SYSTEM_FIXED
1354            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1355
1356    // And we back up these user-adjusted states
1357    private static final int USER_RUNTIME_GRANT_MASK =
1358            FLAG_PERMISSION_USER_SET
1359            | FLAG_PERMISSION_USER_FIXED
1360            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1361
1362    final @Nullable String mRequiredVerifierPackage;
1363    final @NonNull String mRequiredInstallerPackage;
1364    final @NonNull String mRequiredUninstallerPackage;
1365    final @Nullable String mSetupWizardPackage;
1366    final @Nullable String mStorageManagerPackage;
1367    final @NonNull String mServicesSystemSharedLibraryPackageName;
1368    final @NonNull String mSharedSystemSharedLibraryPackageName;
1369
1370    final boolean mPermissionReviewRequired;
1371
1372    private final PackageUsage mPackageUsage = new PackageUsage();
1373    private final CompilerStats mCompilerStats = new CompilerStats();
1374
1375    class PackageHandler extends Handler {
1376        private boolean mBound = false;
1377        final ArrayList<HandlerParams> mPendingInstalls =
1378            new ArrayList<HandlerParams>();
1379
1380        private boolean connectToService() {
1381            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1382                    " DefaultContainerService");
1383            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1384            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1385            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1386                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1387                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1388                mBound = true;
1389                return true;
1390            }
1391            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1392            return false;
1393        }
1394
1395        private void disconnectService() {
1396            mContainerService = null;
1397            mBound = false;
1398            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1399            mContext.unbindService(mDefContainerConn);
1400            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1401        }
1402
1403        PackageHandler(Looper looper) {
1404            super(looper);
1405        }
1406
1407        public void handleMessage(Message msg) {
1408            try {
1409                doHandleMessage(msg);
1410            } finally {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412            }
1413        }
1414
1415        void doHandleMessage(Message msg) {
1416            switch (msg.what) {
1417                case INIT_COPY: {
1418                    HandlerParams params = (HandlerParams) msg.obj;
1419                    int idx = mPendingInstalls.size();
1420                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1421                    // If a bind was already initiated we dont really
1422                    // need to do anything. The pending install
1423                    // will be processed later on.
1424                    if (!mBound) {
1425                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1426                                System.identityHashCode(mHandler));
1427                        // If this is the only one pending we might
1428                        // have to bind to the service again.
1429                        if (!connectToService()) {
1430                            Slog.e(TAG, "Failed to bind to media container service");
1431                            params.serviceError();
1432                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1433                                    System.identityHashCode(mHandler));
1434                            if (params.traceMethod != null) {
1435                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1436                                        params.traceCookie);
1437                            }
1438                            return;
1439                        } else {
1440                            // Once we bind to the service, the first
1441                            // pending request will be processed.
1442                            mPendingInstalls.add(idx, params);
1443                        }
1444                    } else {
1445                        mPendingInstalls.add(idx, params);
1446                        // Already bound to the service. Just make
1447                        // sure we trigger off processing the first request.
1448                        if (idx == 0) {
1449                            mHandler.sendEmptyMessage(MCS_BOUND);
1450                        }
1451                    }
1452                    break;
1453                }
1454                case MCS_BOUND: {
1455                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1456                    if (msg.obj != null) {
1457                        mContainerService = (IMediaContainerService) msg.obj;
1458                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1459                                System.identityHashCode(mHandler));
1460                    }
1461                    if (mContainerService == null) {
1462                        if (!mBound) {
1463                            // Something seriously wrong since we are not bound and we are not
1464                            // waiting for connection. Bail out.
1465                            Slog.e(TAG, "Cannot bind to media container service");
1466                            for (HandlerParams params : mPendingInstalls) {
1467                                // Indicate service bind error
1468                                params.serviceError();
1469                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1470                                        System.identityHashCode(params));
1471                                if (params.traceMethod != null) {
1472                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1473                                            params.traceMethod, params.traceCookie);
1474                                }
1475                                return;
1476                            }
1477                            mPendingInstalls.clear();
1478                        } else {
1479                            Slog.w(TAG, "Waiting to connect to media container service");
1480                        }
1481                    } else if (mPendingInstalls.size() > 0) {
1482                        HandlerParams params = mPendingInstalls.get(0);
1483                        if (params != null) {
1484                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1485                                    System.identityHashCode(params));
1486                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1487                            if (params.startCopy()) {
1488                                // We are done...  look for more work or to
1489                                // go idle.
1490                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1491                                        "Checking for more work or unbind...");
1492                                // Delete pending install
1493                                if (mPendingInstalls.size() > 0) {
1494                                    mPendingInstalls.remove(0);
1495                                }
1496                                if (mPendingInstalls.size() == 0) {
1497                                    if (mBound) {
1498                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1499                                                "Posting delayed MCS_UNBIND");
1500                                        removeMessages(MCS_UNBIND);
1501                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1502                                        // Unbind after a little delay, to avoid
1503                                        // continual thrashing.
1504                                        sendMessageDelayed(ubmsg, 10000);
1505                                    }
1506                                } else {
1507                                    // There are more pending requests in queue.
1508                                    // Just post MCS_BOUND message to trigger processing
1509                                    // of next pending install.
1510                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1511                                            "Posting MCS_BOUND for next work");
1512                                    mHandler.sendEmptyMessage(MCS_BOUND);
1513                                }
1514                            }
1515                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1516                        }
1517                    } else {
1518                        // Should never happen ideally.
1519                        Slog.w(TAG, "Empty queue");
1520                    }
1521                    break;
1522                }
1523                case MCS_RECONNECT: {
1524                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1525                    if (mPendingInstalls.size() > 0) {
1526                        if (mBound) {
1527                            disconnectService();
1528                        }
1529                        if (!connectToService()) {
1530                            Slog.e(TAG, "Failed to bind to media container service");
1531                            for (HandlerParams params : mPendingInstalls) {
1532                                // Indicate service bind error
1533                                params.serviceError();
1534                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1535                                        System.identityHashCode(params));
1536                            }
1537                            mPendingInstalls.clear();
1538                        }
1539                    }
1540                    break;
1541                }
1542                case MCS_UNBIND: {
1543                    // If there is no actual work left, then time to unbind.
1544                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1545
1546                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1547                        if (mBound) {
1548                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1549
1550                            disconnectService();
1551                        }
1552                    } else if (mPendingInstalls.size() > 0) {
1553                        // There are more pending requests in queue.
1554                        // Just post MCS_BOUND message to trigger processing
1555                        // of next pending install.
1556                        mHandler.sendEmptyMessage(MCS_BOUND);
1557                    }
1558
1559                    break;
1560                }
1561                case MCS_GIVE_UP: {
1562                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1563                    HandlerParams params = mPendingInstalls.remove(0);
1564                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1565                            System.identityHashCode(params));
1566                    break;
1567                }
1568                case SEND_PENDING_BROADCAST: {
1569                    String packages[];
1570                    ArrayList<String> components[];
1571                    int size = 0;
1572                    int uids[];
1573                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1574                    synchronized (mPackages) {
1575                        if (mPendingBroadcasts == null) {
1576                            return;
1577                        }
1578                        size = mPendingBroadcasts.size();
1579                        if (size <= 0) {
1580                            // Nothing to be done. Just return
1581                            return;
1582                        }
1583                        packages = new String[size];
1584                        components = new ArrayList[size];
1585                        uids = new int[size];
1586                        int i = 0;  // filling out the above arrays
1587
1588                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1589                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1590                            Iterator<Map.Entry<String, ArrayList<String>>> it
1591                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1592                                            .entrySet().iterator();
1593                            while (it.hasNext() && i < size) {
1594                                Map.Entry<String, ArrayList<String>> ent = it.next();
1595                                packages[i] = ent.getKey();
1596                                components[i] = ent.getValue();
1597                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1598                                uids[i] = (ps != null)
1599                                        ? UserHandle.getUid(packageUserId, ps.appId)
1600                                        : -1;
1601                                i++;
1602                            }
1603                        }
1604                        size = i;
1605                        mPendingBroadcasts.clear();
1606                    }
1607                    // Send broadcasts
1608                    for (int i = 0; i < size; i++) {
1609                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1610                    }
1611                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1612                    break;
1613                }
1614                case START_CLEANING_PACKAGE: {
1615                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1616                    final String packageName = (String)msg.obj;
1617                    final int userId = msg.arg1;
1618                    final boolean andCode = msg.arg2 != 0;
1619                    synchronized (mPackages) {
1620                        if (userId == UserHandle.USER_ALL) {
1621                            int[] users = sUserManager.getUserIds();
1622                            for (int user : users) {
1623                                mSettings.addPackageToCleanLPw(
1624                                        new PackageCleanItem(user, packageName, andCode));
1625                            }
1626                        } else {
1627                            mSettings.addPackageToCleanLPw(
1628                                    new PackageCleanItem(userId, packageName, andCode));
1629                        }
1630                    }
1631                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1632                    startCleaningPackages();
1633                } break;
1634                case POST_INSTALL: {
1635                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1636
1637                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1638                    final boolean didRestore = (msg.arg2 != 0);
1639                    mRunningInstalls.delete(msg.arg1);
1640
1641                    if (data != null) {
1642                        InstallArgs args = data.args;
1643                        PackageInstalledInfo parentRes = data.res;
1644
1645                        final boolean grantPermissions = (args.installFlags
1646                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1647                        final boolean killApp = (args.installFlags
1648                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1649                        final String[] grantedPermissions = args.installGrantPermissions;
1650
1651                        // Handle the parent package
1652                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1653                                grantedPermissions, didRestore, args.installerPackageName,
1654                                args.observer);
1655
1656                        // Handle the child packages
1657                        final int childCount = (parentRes.addedChildPackages != null)
1658                                ? parentRes.addedChildPackages.size() : 0;
1659                        for (int i = 0; i < childCount; i++) {
1660                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1661                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1662                                    grantedPermissions, false, args.installerPackageName,
1663                                    args.observer);
1664                        }
1665
1666                        // Log tracing if needed
1667                        if (args.traceMethod != null) {
1668                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1669                                    args.traceCookie);
1670                        }
1671                    } else {
1672                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1673                    }
1674
1675                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1676                } break;
1677                case UPDATED_MEDIA_STATUS: {
1678                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1679                    boolean reportStatus = msg.arg1 == 1;
1680                    boolean doGc = msg.arg2 == 1;
1681                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1682                    if (doGc) {
1683                        // Force a gc to clear up stale containers.
1684                        Runtime.getRuntime().gc();
1685                    }
1686                    if (msg.obj != null) {
1687                        @SuppressWarnings("unchecked")
1688                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1689                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1690                        // Unload containers
1691                        unloadAllContainers(args);
1692                    }
1693                    if (reportStatus) {
1694                        try {
1695                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1696                                    "Invoking StorageManagerService call back");
1697                            PackageHelper.getStorageManager().finishMediaUpdate();
1698                        } catch (RemoteException e) {
1699                            Log.e(TAG, "StorageManagerService not running?");
1700                        }
1701                    }
1702                } break;
1703                case WRITE_SETTINGS: {
1704                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1705                    synchronized (mPackages) {
1706                        removeMessages(WRITE_SETTINGS);
1707                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1708                        mSettings.writeLPr();
1709                        mDirtyUsers.clear();
1710                    }
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1712                } break;
1713                case WRITE_PACKAGE_RESTRICTIONS: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1717                        for (int userId : mDirtyUsers) {
1718                            mSettings.writePackageRestrictionsLPr(userId);
1719                        }
1720                        mDirtyUsers.clear();
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case WRITE_PACKAGE_LIST: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_PACKAGE_LIST);
1728                        mSettings.writePackageListLPr(msg.arg1);
1729                    }
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1731                } break;
1732                case CHECK_PENDING_VERIFICATION: {
1733                    final int verificationId = msg.arg1;
1734                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1735
1736                    if ((state != null) && !state.timeoutExtended()) {
1737                        final InstallArgs args = state.getInstallArgs();
1738                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1739
1740                        Slog.i(TAG, "Verification timed out for " + originUri);
1741                        mPendingVerification.remove(verificationId);
1742
1743                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1744
1745                        final UserHandle user = args.getUser();
1746                        if (getDefaultVerificationResponse(user)
1747                                == PackageManager.VERIFICATION_ALLOW) {
1748                            Slog.i(TAG, "Continuing with installation of " + originUri);
1749                            state.setVerifierResponse(Binder.getCallingUid(),
1750                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    PackageManager.VERIFICATION_ALLOW, user);
1753                            try {
1754                                ret = args.copyApk(mContainerService, true);
1755                            } catch (RemoteException e) {
1756                                Slog.e(TAG, "Could not contact the ContainerService");
1757                            }
1758                        } else {
1759                            broadcastPackageVerified(verificationId, originUri,
1760                                    PackageManager.VERIFICATION_REJECT, user);
1761                        }
1762
1763                        Trace.asyncTraceEnd(
1764                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1765
1766                        processPendingInstall(args, ret);
1767                        mHandler.sendEmptyMessage(MCS_UNBIND);
1768                    }
1769                    break;
1770                }
1771                case PACKAGE_VERIFIED: {
1772                    final int verificationId = msg.arg1;
1773
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775                    if (state == null) {
1776                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1777                        break;
1778                    }
1779
1780                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1781
1782                    state.setVerifierResponse(response.callerUid, response.code);
1783
1784                    if (state.isVerificationComplete()) {
1785                        mPendingVerification.remove(verificationId);
1786
1787                        final InstallArgs args = state.getInstallArgs();
1788                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1789
1790                        int ret;
1791                        if (state.isInstallAllowed()) {
1792                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    response.code, state.getInstallArgs().getUser());
1795                            try {
1796                                ret = args.copyApk(mContainerService, true);
1797                            } catch (RemoteException e) {
1798                                Slog.e(TAG, "Could not contact the ContainerService");
1799                            }
1800                        } else {
1801                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1802                        }
1803
1804                        Trace.asyncTraceEnd(
1805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806
1807                        processPendingInstall(args, ret);
1808                        mHandler.sendEmptyMessage(MCS_UNBIND);
1809                    }
1810
1811                    break;
1812                }
1813                case START_INTENT_FILTER_VERIFICATIONS: {
1814                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1815                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1816                            params.replacing, params.pkg);
1817                    break;
1818                }
1819                case INTENT_FILTER_VERIFIED: {
1820                    final int verificationId = msg.arg1;
1821
1822                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1823                            verificationId);
1824                    if (state == null) {
1825                        Slog.w(TAG, "Invalid IntentFilter verification token "
1826                                + verificationId + " received");
1827                        break;
1828                    }
1829
1830                    final int userId = state.getUserId();
1831
1832                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1833                            "Processing IntentFilter verification with token:"
1834                            + verificationId + " and userId:" + userId);
1835
1836                    final IntentFilterVerificationResponse response =
1837                            (IntentFilterVerificationResponse) msg.obj;
1838
1839                    state.setVerifierResponse(response.callerUid, response.code);
1840
1841                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1842                            "IntentFilter verification with token:" + verificationId
1843                            + " and userId:" + userId
1844                            + " is settings verifier response with response code:"
1845                            + response.code);
1846
1847                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1848                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1849                                + response.getFailedDomainsString());
1850                    }
1851
1852                    if (state.isVerificationComplete()) {
1853                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1854                    } else {
1855                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                                "IntentFilter verification with token:" + verificationId
1857                                + " was not said to be complete");
1858                    }
1859
1860                    break;
1861                }
1862                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1863                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1864                            mInstantAppResolverConnection,
1865                            (InstantAppRequest) msg.obj,
1866                            mInstantAppInstallerActivity,
1867                            mHandler);
1868                }
1869            }
1870        }
1871    }
1872
1873    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1874            boolean killApp, String[] grantedPermissions,
1875            boolean launchedForRestore, String installerPackage,
1876            IPackageInstallObserver2 installObserver) {
1877        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1878            // Send the removed broadcasts
1879            if (res.removedInfo != null) {
1880                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1881            }
1882
1883            // Now that we successfully installed the package, grant runtime
1884            // permissions if requested before broadcasting the install. Also
1885            // for legacy apps in permission review mode we clear the permission
1886            // review flag which is used to emulate runtime permissions for
1887            // legacy apps.
1888            if (grantPermissions) {
1889                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1890            }
1891
1892            final boolean update = res.removedInfo != null
1893                    && res.removedInfo.removedPackage != null;
1894            final String origInstallerPackageName = res.removedInfo != null
1895                    ? res.removedInfo.installerPackageName : null;
1896
1897            // If this is the first time we have child packages for a disabled privileged
1898            // app that had no children, we grant requested runtime permissions to the new
1899            // children if the parent on the system image had them already granted.
1900            if (res.pkg.parentPackage != null) {
1901                synchronized (mPackages) {
1902                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1903                }
1904            }
1905
1906            synchronized (mPackages) {
1907                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1908            }
1909
1910            final String packageName = res.pkg.applicationInfo.packageName;
1911
1912            // Determine the set of users who are adding this package for
1913            // the first time vs. those who are seeing an update.
1914            int[] firstUsers = EMPTY_INT_ARRAY;
1915            int[] updateUsers = EMPTY_INT_ARRAY;
1916            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1917            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1918            for (int newUser : res.newUsers) {
1919                if (ps.getInstantApp(newUser)) {
1920                    continue;
1921                }
1922                if (allNewUsers) {
1923                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1924                    continue;
1925                }
1926                boolean isNew = true;
1927                for (int origUser : res.origUsers) {
1928                    if (origUser == newUser) {
1929                        isNew = false;
1930                        break;
1931                    }
1932                }
1933                if (isNew) {
1934                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1935                } else {
1936                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1937                }
1938            }
1939
1940            // Send installed broadcasts if the package is not a static shared lib.
1941            if (res.pkg.staticSharedLibName == null) {
1942                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1943
1944                // Send added for users that see the package for the first time
1945                // sendPackageAddedForNewUsers also deals with system apps
1946                int appId = UserHandle.getAppId(res.uid);
1947                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1948                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1949
1950                // Send added for users that don't see the package for the first time
1951                Bundle extras = new Bundle(1);
1952                extras.putInt(Intent.EXTRA_UID, res.uid);
1953                if (update) {
1954                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1955                }
1956                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1957                        extras, 0 /*flags*/,
1958                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1959                if (origInstallerPackageName != null) {
1960                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1961                            extras, 0 /*flags*/,
1962                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1963                }
1964
1965                // Send replaced for users that don't see the package for the first time
1966                if (update) {
1967                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1968                            packageName, extras, 0 /*flags*/,
1969                            null /*targetPackage*/, null /*finishedReceiver*/,
1970                            updateUsers);
1971                    if (origInstallerPackageName != null) {
1972                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1973                                extras, 0 /*flags*/,
1974                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1975                    }
1976                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1977                            null /*package*/, null /*extras*/, 0 /*flags*/,
1978                            packageName /*targetPackage*/,
1979                            null /*finishedReceiver*/, updateUsers);
1980                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1981                    // First-install and we did a restore, so we're responsible for the
1982                    // first-launch broadcast.
1983                    if (DEBUG_BACKUP) {
1984                        Slog.i(TAG, "Post-restore of " + packageName
1985                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1986                    }
1987                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1988                }
1989
1990                // Send broadcast package appeared if forward locked/external for all users
1991                // treat asec-hosted packages like removable media on upgrade
1992                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1993                    if (DEBUG_INSTALL) {
1994                        Slog.i(TAG, "upgrading pkg " + res.pkg
1995                                + " is ASEC-hosted -> AVAILABLE");
1996                    }
1997                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1998                    ArrayList<String> pkgList = new ArrayList<>(1);
1999                    pkgList.add(packageName);
2000                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2001                }
2002            }
2003
2004            // Work that needs to happen on first install within each user
2005            if (firstUsers != null && firstUsers.length > 0) {
2006                synchronized (mPackages) {
2007                    for (int userId : firstUsers) {
2008                        // If this app is a browser and it's newly-installed for some
2009                        // users, clear any default-browser state in those users. The
2010                        // app's nature doesn't depend on the user, so we can just check
2011                        // its browser nature in any user and generalize.
2012                        if (packageIsBrowser(packageName, userId)) {
2013                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2014                        }
2015
2016                        // We may also need to apply pending (restored) runtime
2017                        // permission grants within these users.
2018                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2019                    }
2020                }
2021            }
2022
2023            // Log current value of "unknown sources" setting
2024            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2025                    getUnknownSourcesSettings());
2026
2027            // Force a gc to clear up things
2028            Runtime.getRuntime().gc();
2029
2030            // Remove the replaced package's older resources safely now
2031            // We delete after a gc for applications  on sdcard.
2032            if (res.removedInfo != null && res.removedInfo.args != null) {
2033                synchronized (mInstallLock) {
2034                    res.removedInfo.args.doPostDeleteLI(true);
2035                }
2036            }
2037
2038            // Notify DexManager that the package was installed for new users.
2039            // The updated users should already be indexed and the package code paths
2040            // should not change.
2041            // Don't notify the manager for ephemeral apps as they are not expected to
2042            // survive long enough to benefit of background optimizations.
2043            for (int userId : firstUsers) {
2044                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2045                // There's a race currently where some install events may interleave with an uninstall.
2046                // This can lead to package info being null (b/36642664).
2047                if (info != null) {
2048                    mDexManager.notifyPackageInstalled(info, userId);
2049                }
2050            }
2051        }
2052
2053        // If someone is watching installs - notify them
2054        if (installObserver != null) {
2055            try {
2056                Bundle extras = extrasForInstallResult(res);
2057                installObserver.onPackageInstalled(res.name, res.returnCode,
2058                        res.returnMsg, extras);
2059            } catch (RemoteException e) {
2060                Slog.i(TAG, "Observer no longer exists.");
2061            }
2062        }
2063    }
2064
2065    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2066            PackageParser.Package pkg) {
2067        if (pkg.parentPackage == null) {
2068            return;
2069        }
2070        if (pkg.requestedPermissions == null) {
2071            return;
2072        }
2073        final PackageSetting disabledSysParentPs = mSettings
2074                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2075        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2076                || !disabledSysParentPs.isPrivileged()
2077                || (disabledSysParentPs.childPackageNames != null
2078                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2079            return;
2080        }
2081        final int[] allUserIds = sUserManager.getUserIds();
2082        final int permCount = pkg.requestedPermissions.size();
2083        for (int i = 0; i < permCount; i++) {
2084            String permission = pkg.requestedPermissions.get(i);
2085            BasePermission bp = mSettings.mPermissions.get(permission);
2086            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2087                continue;
2088            }
2089            for (int userId : allUserIds) {
2090                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2091                        permission, userId)) {
2092                    grantRuntimePermission(pkg.packageName, permission, userId);
2093                }
2094            }
2095        }
2096    }
2097
2098    private StorageEventListener mStorageListener = new StorageEventListener() {
2099        @Override
2100        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2101            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2102                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2103                    final String volumeUuid = vol.getFsUuid();
2104
2105                    // Clean up any users or apps that were removed or recreated
2106                    // while this volume was missing
2107                    sUserManager.reconcileUsers(volumeUuid);
2108                    reconcileApps(volumeUuid);
2109
2110                    // Clean up any install sessions that expired or were
2111                    // cancelled while this volume was missing
2112                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2113
2114                    loadPrivatePackages(vol);
2115
2116                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2117                    unloadPrivatePackages(vol);
2118                }
2119            }
2120
2121            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2122                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2123                    updateExternalMediaStatus(true, false);
2124                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2125                    updateExternalMediaStatus(false, false);
2126                }
2127            }
2128        }
2129
2130        @Override
2131        public void onVolumeForgotten(String fsUuid) {
2132            if (TextUtils.isEmpty(fsUuid)) {
2133                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2134                return;
2135            }
2136
2137            // Remove any apps installed on the forgotten volume
2138            synchronized (mPackages) {
2139                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2140                for (PackageSetting ps : packages) {
2141                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2142                    deletePackageVersioned(new VersionedPackage(ps.name,
2143                            PackageManager.VERSION_CODE_HIGHEST),
2144                            new LegacyPackageDeleteObserver(null).getBinder(),
2145                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2146                    // Try very hard to release any references to this package
2147                    // so we don't risk the system server being killed due to
2148                    // open FDs
2149                    AttributeCache.instance().removePackage(ps.name);
2150                }
2151
2152                mSettings.onVolumeForgotten(fsUuid);
2153                mSettings.writeLPr();
2154            }
2155        }
2156    };
2157
2158    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2159            String[] grantedPermissions) {
2160        for (int userId : userIds) {
2161            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2162        }
2163    }
2164
2165    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2166            String[] grantedPermissions) {
2167        SettingBase sb = (SettingBase) pkg.mExtras;
2168        if (sb == null) {
2169            return;
2170        }
2171
2172        PermissionsState permissionsState = sb.getPermissionsState();
2173
2174        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2175                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2176
2177        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2178                >= Build.VERSION_CODES.M;
2179
2180        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2181
2182        for (String permission : pkg.requestedPermissions) {
2183            final BasePermission bp;
2184            synchronized (mPackages) {
2185                bp = mSettings.mPermissions.get(permission);
2186            }
2187            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2188                    && (!instantApp || bp.isInstant())
2189                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2190                    && (grantedPermissions == null
2191                           || ArrayUtils.contains(grantedPermissions, permission))) {
2192                final int flags = permissionsState.getPermissionFlags(permission, userId);
2193                if (supportsRuntimePermissions) {
2194                    // Installer cannot change immutable permissions.
2195                    if ((flags & immutableFlags) == 0) {
2196                        grantRuntimePermission(pkg.packageName, permission, userId);
2197                    }
2198                } else if (mPermissionReviewRequired) {
2199                    // In permission review mode we clear the review flag when we
2200                    // are asked to install the app with all permissions granted.
2201                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2202                        updatePermissionFlags(permission, pkg.packageName,
2203                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2204                    }
2205                }
2206            }
2207        }
2208    }
2209
2210    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2211        Bundle extras = null;
2212        switch (res.returnCode) {
2213            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2214                extras = new Bundle();
2215                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2216                        res.origPermission);
2217                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2218                        res.origPackage);
2219                break;
2220            }
2221            case PackageManager.INSTALL_SUCCEEDED: {
2222                extras = new Bundle();
2223                extras.putBoolean(Intent.EXTRA_REPLACING,
2224                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2225                break;
2226            }
2227        }
2228        return extras;
2229    }
2230
2231    void scheduleWriteSettingsLocked() {
2232        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2233            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2234        }
2235    }
2236
2237    void scheduleWritePackageListLocked(int userId) {
2238        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2239            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2240            msg.arg1 = userId;
2241            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2242        }
2243    }
2244
2245    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2246        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2247        scheduleWritePackageRestrictionsLocked(userId);
2248    }
2249
2250    void scheduleWritePackageRestrictionsLocked(int userId) {
2251        final int[] userIds = (userId == UserHandle.USER_ALL)
2252                ? sUserManager.getUserIds() : new int[]{userId};
2253        for (int nextUserId : userIds) {
2254            if (!sUserManager.exists(nextUserId)) return;
2255            mDirtyUsers.add(nextUserId);
2256            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2257                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2258            }
2259        }
2260    }
2261
2262    public static PackageManagerService main(Context context, Installer installer,
2263            boolean factoryTest, boolean onlyCore) {
2264        // Self-check for initial settings.
2265        PackageManagerServiceCompilerMapping.checkProperties();
2266
2267        PackageManagerService m = new PackageManagerService(context, installer,
2268                factoryTest, onlyCore);
2269        m.enableSystemUserPackages();
2270        ServiceManager.addService("package", m);
2271        return m;
2272    }
2273
2274    private void enableSystemUserPackages() {
2275        if (!UserManager.isSplitSystemUser()) {
2276            return;
2277        }
2278        // For system user, enable apps based on the following conditions:
2279        // - app is whitelisted or belong to one of these groups:
2280        //   -- system app which has no launcher icons
2281        //   -- system app which has INTERACT_ACROSS_USERS permission
2282        //   -- system IME app
2283        // - app is not in the blacklist
2284        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2285        Set<String> enableApps = new ArraySet<>();
2286        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2287                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2288                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2289        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2290        enableApps.addAll(wlApps);
2291        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2292                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2293        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2294        enableApps.removeAll(blApps);
2295        Log.i(TAG, "Applications installed for system user: " + enableApps);
2296        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2297                UserHandle.SYSTEM);
2298        final int allAppsSize = allAps.size();
2299        synchronized (mPackages) {
2300            for (int i = 0; i < allAppsSize; i++) {
2301                String pName = allAps.get(i);
2302                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2303                // Should not happen, but we shouldn't be failing if it does
2304                if (pkgSetting == null) {
2305                    continue;
2306                }
2307                boolean install = enableApps.contains(pName);
2308                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2309                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2310                            + " for system user");
2311                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2312                }
2313            }
2314            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2315        }
2316    }
2317
2318    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2319        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2320                Context.DISPLAY_SERVICE);
2321        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2322    }
2323
2324    /**
2325     * Requests that files preopted on a secondary system partition be copied to the data partition
2326     * if possible.  Note that the actual copying of the files is accomplished by init for security
2327     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2328     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2329     */
2330    private static void requestCopyPreoptedFiles() {
2331        final int WAIT_TIME_MS = 100;
2332        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2333        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2334            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2335            // We will wait for up to 100 seconds.
2336            final long timeStart = SystemClock.uptimeMillis();
2337            final long timeEnd = timeStart + 100 * 1000;
2338            long timeNow = timeStart;
2339            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2340                try {
2341                    Thread.sleep(WAIT_TIME_MS);
2342                } catch (InterruptedException e) {
2343                    // Do nothing
2344                }
2345                timeNow = SystemClock.uptimeMillis();
2346                if (timeNow > timeEnd) {
2347                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2348                    Slog.wtf(TAG, "cppreopt did not finish!");
2349                    break;
2350                }
2351            }
2352
2353            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2354        }
2355    }
2356
2357    public PackageManagerService(Context context, Installer installer,
2358            boolean factoryTest, boolean onlyCore) {
2359        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2360        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2361        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2362                SystemClock.uptimeMillis());
2363
2364        if (mSdkVersion <= 0) {
2365            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2366        }
2367
2368        mContext = context;
2369
2370        mPermissionReviewRequired = context.getResources().getBoolean(
2371                R.bool.config_permissionReviewRequired);
2372
2373        mFactoryTest = factoryTest;
2374        mOnlyCore = onlyCore;
2375        mMetrics = new DisplayMetrics();
2376        mSettings = new Settings(mPackages);
2377        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2378                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2379        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2380                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2381        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2382                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2383        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2384                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2385        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2386                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2387        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2388                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2389
2390        String separateProcesses = SystemProperties.get("debug.separate_processes");
2391        if (separateProcesses != null && separateProcesses.length() > 0) {
2392            if ("*".equals(separateProcesses)) {
2393                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2394                mSeparateProcesses = null;
2395                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2396            } else {
2397                mDefParseFlags = 0;
2398                mSeparateProcesses = separateProcesses.split(",");
2399                Slog.w(TAG, "Running with debug.separate_processes: "
2400                        + separateProcesses);
2401            }
2402        } else {
2403            mDefParseFlags = 0;
2404            mSeparateProcesses = null;
2405        }
2406
2407        mInstaller = installer;
2408        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2409                "*dexopt*");
2410        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2411        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2412
2413        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2414                FgThread.get().getLooper());
2415
2416        getDefaultDisplayMetrics(context, mMetrics);
2417
2418        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2419        SystemConfig systemConfig = SystemConfig.getInstance();
2420        mGlobalGids = systemConfig.getGlobalGids();
2421        mSystemPermissions = systemConfig.getSystemPermissions();
2422        mAvailableFeatures = systemConfig.getAvailableFeatures();
2423        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2424
2425        mProtectedPackages = new ProtectedPackages(mContext);
2426
2427        synchronized (mInstallLock) {
2428        // writer
2429        synchronized (mPackages) {
2430            mHandlerThread = new ServiceThread(TAG,
2431                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2432            mHandlerThread.start();
2433            mHandler = new PackageHandler(mHandlerThread.getLooper());
2434            mProcessLoggingHandler = new ProcessLoggingHandler();
2435            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2436
2437            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2438            mInstantAppRegistry = new InstantAppRegistry(this);
2439
2440            File dataDir = Environment.getDataDirectory();
2441            mAppInstallDir = new File(dataDir, "app");
2442            mAppLib32InstallDir = new File(dataDir, "app-lib");
2443            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2444            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2445            sUserManager = new UserManagerService(context, this,
2446                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2447
2448            // Propagate permission configuration in to package manager.
2449            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2450                    = systemConfig.getPermissions();
2451            for (int i=0; i<permConfig.size(); i++) {
2452                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2453                BasePermission bp = mSettings.mPermissions.get(perm.name);
2454                if (bp == null) {
2455                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2456                    mSettings.mPermissions.put(perm.name, bp);
2457                }
2458                if (perm.gids != null) {
2459                    bp.setGids(perm.gids, perm.perUser);
2460                }
2461            }
2462
2463            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2464            final int builtInLibCount = libConfig.size();
2465            for (int i = 0; i < builtInLibCount; i++) {
2466                String name = libConfig.keyAt(i);
2467                String path = libConfig.valueAt(i);
2468                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2469                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2470            }
2471
2472            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2473
2474            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2475            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2476            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2477
2478            // Clean up orphaned packages for which the code path doesn't exist
2479            // and they are an update to a system app - caused by bug/32321269
2480            final int packageSettingCount = mSettings.mPackages.size();
2481            for (int i = packageSettingCount - 1; i >= 0; i--) {
2482                PackageSetting ps = mSettings.mPackages.valueAt(i);
2483                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2484                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2485                    mSettings.mPackages.removeAt(i);
2486                    mSettings.enableSystemPackageLPw(ps.name);
2487                }
2488            }
2489
2490            if (mFirstBoot) {
2491                requestCopyPreoptedFiles();
2492            }
2493
2494            String customResolverActivity = Resources.getSystem().getString(
2495                    R.string.config_customResolverActivity);
2496            if (TextUtils.isEmpty(customResolverActivity)) {
2497                customResolverActivity = null;
2498            } else {
2499                mCustomResolverComponentName = ComponentName.unflattenFromString(
2500                        customResolverActivity);
2501            }
2502
2503            long startTime = SystemClock.uptimeMillis();
2504
2505            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2506                    startTime);
2507
2508            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2509            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2510
2511            if (bootClassPath == null) {
2512                Slog.w(TAG, "No BOOTCLASSPATH found!");
2513            }
2514
2515            if (systemServerClassPath == null) {
2516                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2517            }
2518
2519            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2520
2521            final VersionInfo ver = mSettings.getInternalVersion();
2522            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2523            if (mIsUpgrade) {
2524                logCriticalInfo(Log.INFO,
2525                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2526            }
2527
2528            // when upgrading from pre-M, promote system app permissions from install to runtime
2529            mPromoteSystemApps =
2530                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2531
2532            // When upgrading from pre-N, we need to handle package extraction like first boot,
2533            // as there is no profiling data available.
2534            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2535
2536            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2537
2538            // save off the names of pre-existing system packages prior to scanning; we don't
2539            // want to automatically grant runtime permissions for new system apps
2540            if (mPromoteSystemApps) {
2541                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2542                while (pkgSettingIter.hasNext()) {
2543                    PackageSetting ps = pkgSettingIter.next();
2544                    if (isSystemApp(ps)) {
2545                        mExistingSystemPackages.add(ps.name);
2546                    }
2547                }
2548            }
2549
2550            mCacheDir = preparePackageParserCache(mIsUpgrade);
2551
2552            // Set flag to monitor and not change apk file paths when
2553            // scanning install directories.
2554            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2555
2556            if (mIsUpgrade || mFirstBoot) {
2557                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2558            }
2559
2560            // Collect vendor overlay packages. (Do this before scanning any apps.)
2561            // For security and version matching reason, only consider
2562            // overlay packages if they reside in the right directory.
2563            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2564                    | PackageParser.PARSE_IS_SYSTEM
2565                    | PackageParser.PARSE_IS_SYSTEM_DIR
2566                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2567
2568            mParallelPackageParserCallback.findStaticOverlayPackages();
2569
2570            // Find base frameworks (resource packages without code).
2571            scanDirTracedLI(frameworkDir, mDefParseFlags
2572                    | PackageParser.PARSE_IS_SYSTEM
2573                    | PackageParser.PARSE_IS_SYSTEM_DIR
2574                    | PackageParser.PARSE_IS_PRIVILEGED,
2575                    scanFlags | SCAN_NO_DEX, 0);
2576
2577            // Collected privileged system packages.
2578            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2579            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2580                    | PackageParser.PARSE_IS_SYSTEM
2581                    | PackageParser.PARSE_IS_SYSTEM_DIR
2582                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2583
2584            // Collect ordinary system packages.
2585            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2586            scanDirTracedLI(systemAppDir, mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2589
2590            // Collect all vendor packages.
2591            File vendorAppDir = new File("/vendor/app");
2592            try {
2593                vendorAppDir = vendorAppDir.getCanonicalFile();
2594            } catch (IOException e) {
2595                // failed to look up canonical path, continue with original one
2596            }
2597            scanDirTracedLI(vendorAppDir, mDefParseFlags
2598                    | PackageParser.PARSE_IS_SYSTEM
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2600
2601            // Collect all OEM packages.
2602            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2603            scanDirTracedLI(oemAppDir, mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2606
2607            // Prune any system packages that no longer exist.
2608            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2609            if (!mOnlyCore) {
2610                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2611                while (psit.hasNext()) {
2612                    PackageSetting ps = psit.next();
2613
2614                    /*
2615                     * If this is not a system app, it can't be a
2616                     * disable system app.
2617                     */
2618                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2619                        continue;
2620                    }
2621
2622                    /*
2623                     * If the package is scanned, it's not erased.
2624                     */
2625                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2626                    if (scannedPkg != null) {
2627                        /*
2628                         * If the system app is both scanned and in the
2629                         * disabled packages list, then it must have been
2630                         * added via OTA. Remove it from the currently
2631                         * scanned package so the previously user-installed
2632                         * application can be scanned.
2633                         */
2634                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2635                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2636                                    + ps.name + "; removing system app.  Last known codePath="
2637                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2638                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2639                                    + scannedPkg.mVersionCode);
2640                            removePackageLI(scannedPkg, true);
2641                            mExpectingBetter.put(ps.name, ps.codePath);
2642                        }
2643
2644                        continue;
2645                    }
2646
2647                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2648                        psit.remove();
2649                        logCriticalInfo(Log.WARN, "System package " + ps.name
2650                                + " no longer exists; it's data will be wiped");
2651                        // Actual deletion of code and data will be handled by later
2652                        // reconciliation step
2653                    } else {
2654                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2655                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2656                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2657                        }
2658                    }
2659                }
2660            }
2661
2662            //look for any incomplete package installations
2663            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2664            for (int i = 0; i < deletePkgsList.size(); i++) {
2665                // Actual deletion of code and data will be handled by later
2666                // reconciliation step
2667                final String packageName = deletePkgsList.get(i).name;
2668                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2669                synchronized (mPackages) {
2670                    mSettings.removePackageLPw(packageName);
2671                }
2672            }
2673
2674            //delete tmp files
2675            deleteTempPackageFiles();
2676
2677            // Remove any shared userIDs that have no associated packages
2678            mSettings.pruneSharedUsersLPw();
2679
2680            if (!mOnlyCore) {
2681                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2682                        SystemClock.uptimeMillis());
2683                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2684
2685                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2686                        | PackageParser.PARSE_FORWARD_LOCK,
2687                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2688
2689                /**
2690                 * Remove disable package settings for any updated system
2691                 * apps that were removed via an OTA. If they're not a
2692                 * previously-updated app, remove them completely.
2693                 * Otherwise, just revoke their system-level permissions.
2694                 */
2695                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2696                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2697                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2698
2699                    String msg;
2700                    if (deletedPkg == null) {
2701                        msg = "Updated system package " + deletedAppName
2702                                + " no longer exists; it's data will be wiped";
2703                        // Actual deletion of code and data will be handled by later
2704                        // reconciliation step
2705                    } else {
2706                        msg = "Updated system app + " + deletedAppName
2707                                + " no longer present; removing system privileges for "
2708                                + deletedAppName;
2709
2710                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2711
2712                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2713                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2714                    }
2715                    logCriticalInfo(Log.WARN, msg);
2716                }
2717
2718                /**
2719                 * Make sure all system apps that we expected to appear on
2720                 * the userdata partition actually showed up. If they never
2721                 * appeared, crawl back and revive the system version.
2722                 */
2723                for (int i = 0; i < mExpectingBetter.size(); i++) {
2724                    final String packageName = mExpectingBetter.keyAt(i);
2725                    if (!mPackages.containsKey(packageName)) {
2726                        final File scanFile = mExpectingBetter.valueAt(i);
2727
2728                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2729                                + " but never showed up; reverting to system");
2730
2731                        int reparseFlags = mDefParseFlags;
2732                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2733                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2734                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2735                                    | PackageParser.PARSE_IS_PRIVILEGED;
2736                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2737                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2738                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2739                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2740                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2741                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2742                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2743                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2744                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2745                        } else {
2746                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2747                            continue;
2748                        }
2749
2750                        mSettings.enableSystemPackageLPw(packageName);
2751
2752                        try {
2753                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2754                        } catch (PackageManagerException e) {
2755                            Slog.e(TAG, "Failed to parse original system package: "
2756                                    + e.getMessage());
2757                        }
2758                    }
2759                }
2760            }
2761            mExpectingBetter.clear();
2762
2763            // Resolve the storage manager.
2764            mStorageManagerPackage = getStorageManagerPackageName();
2765
2766            // Resolve protected action filters. Only the setup wizard is allowed to
2767            // have a high priority filter for these actions.
2768            mSetupWizardPackage = getSetupWizardPackageName();
2769            if (mProtectedFilters.size() > 0) {
2770                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2771                    Slog.i(TAG, "No setup wizard;"
2772                        + " All protected intents capped to priority 0");
2773                }
2774                for (ActivityIntentInfo filter : mProtectedFilters) {
2775                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2776                        if (DEBUG_FILTERS) {
2777                            Slog.i(TAG, "Found setup wizard;"
2778                                + " allow priority " + filter.getPriority() + ";"
2779                                + " package: " + filter.activity.info.packageName
2780                                + " activity: " + filter.activity.className
2781                                + " priority: " + filter.getPriority());
2782                        }
2783                        // skip setup wizard; allow it to keep the high priority filter
2784                        continue;
2785                    }
2786                    Slog.w(TAG, "Protected action; cap priority to 0;"
2787                            + " package: " + filter.activity.info.packageName
2788                            + " activity: " + filter.activity.className
2789                            + " origPrio: " + filter.getPriority());
2790                    filter.setPriority(0);
2791                }
2792            }
2793            mDeferProtectedFilters = false;
2794            mProtectedFilters.clear();
2795
2796            // Now that we know all of the shared libraries, update all clients to have
2797            // the correct library paths.
2798            updateAllSharedLibrariesLPw(null);
2799
2800            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2801                // NOTE: We ignore potential failures here during a system scan (like
2802                // the rest of the commands above) because there's precious little we
2803                // can do about it. A settings error is reported, though.
2804                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2805            }
2806
2807            // Now that we know all the packages we are keeping,
2808            // read and update their last usage times.
2809            mPackageUsage.read(mPackages);
2810            mCompilerStats.read();
2811
2812            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2813                    SystemClock.uptimeMillis());
2814            Slog.i(TAG, "Time to scan packages: "
2815                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2816                    + " seconds");
2817
2818            // If the platform SDK has changed since the last time we booted,
2819            // we need to re-grant app permission to catch any new ones that
2820            // appear.  This is really a hack, and means that apps can in some
2821            // cases get permissions that the user didn't initially explicitly
2822            // allow...  it would be nice to have some better way to handle
2823            // this situation.
2824            int updateFlags = UPDATE_PERMISSIONS_ALL;
2825            if (ver.sdkVersion != mSdkVersion) {
2826                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2827                        + mSdkVersion + "; regranting permissions for internal storage");
2828                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2829            }
2830            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2831            ver.sdkVersion = mSdkVersion;
2832
2833            // If this is the first boot or an update from pre-M, and it is a normal
2834            // boot, then we need to initialize the default preferred apps across
2835            // all defined users.
2836            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2837                for (UserInfo user : sUserManager.getUsers(true)) {
2838                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2839                    applyFactoryDefaultBrowserLPw(user.id);
2840                    primeDomainVerificationsLPw(user.id);
2841                }
2842            }
2843
2844            // Prepare storage for system user really early during boot,
2845            // since core system apps like SettingsProvider and SystemUI
2846            // can't wait for user to start
2847            final int storageFlags;
2848            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2849                storageFlags = StorageManager.FLAG_STORAGE_DE;
2850            } else {
2851                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2852            }
2853            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2854                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2855                    true /* onlyCoreApps */);
2856            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2857                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2858                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2859                traceLog.traceBegin("AppDataFixup");
2860                try {
2861                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2862                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2863                } catch (InstallerException e) {
2864                    Slog.w(TAG, "Trouble fixing GIDs", e);
2865                }
2866                traceLog.traceEnd();
2867
2868                traceLog.traceBegin("AppDataPrepare");
2869                if (deferPackages == null || deferPackages.isEmpty()) {
2870                    return;
2871                }
2872                int count = 0;
2873                for (String pkgName : deferPackages) {
2874                    PackageParser.Package pkg = null;
2875                    synchronized (mPackages) {
2876                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2877                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2878                            pkg = ps.pkg;
2879                        }
2880                    }
2881                    if (pkg != null) {
2882                        synchronized (mInstallLock) {
2883                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2884                                    true /* maybeMigrateAppData */);
2885                        }
2886                        count++;
2887                    }
2888                }
2889                traceLog.traceEnd();
2890                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2891            }, "prepareAppData");
2892
2893            // If this is first boot after an OTA, and a normal boot, then
2894            // we need to clear code cache directories.
2895            // Note that we do *not* clear the application profiles. These remain valid
2896            // across OTAs and are used to drive profile verification (post OTA) and
2897            // profile compilation (without waiting to collect a fresh set of profiles).
2898            if (mIsUpgrade && !onlyCore) {
2899                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2900                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2901                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2902                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2903                        // No apps are running this early, so no need to freeze
2904                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2905                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2906                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2907                    }
2908                }
2909                ver.fingerprint = Build.FINGERPRINT;
2910            }
2911
2912            checkDefaultBrowser();
2913
2914            // clear only after permissions and other defaults have been updated
2915            mExistingSystemPackages.clear();
2916            mPromoteSystemApps = false;
2917
2918            // All the changes are done during package scanning.
2919            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2920
2921            // can downgrade to reader
2922            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2923            mSettings.writeLPr();
2924            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2925
2926            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2927                    SystemClock.uptimeMillis());
2928
2929            if (!mOnlyCore) {
2930                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2931                mRequiredInstallerPackage = getRequiredInstallerLPr();
2932                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2933                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2934                if (mIntentFilterVerifierComponent != null) {
2935                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2936                            mIntentFilterVerifierComponent);
2937                } else {
2938                    mIntentFilterVerifier = null;
2939                }
2940                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2941                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2942                        SharedLibraryInfo.VERSION_UNDEFINED);
2943                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2944                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2945                        SharedLibraryInfo.VERSION_UNDEFINED);
2946            } else {
2947                mRequiredVerifierPackage = null;
2948                mRequiredInstallerPackage = null;
2949                mRequiredUninstallerPackage = null;
2950                mIntentFilterVerifierComponent = null;
2951                mIntentFilterVerifier = null;
2952                mServicesSystemSharedLibraryPackageName = null;
2953                mSharedSystemSharedLibraryPackageName = null;
2954            }
2955
2956            mInstallerService = new PackageInstallerService(context, this);
2957            final Pair<ComponentName, String> instantAppResolverComponent =
2958                    getInstantAppResolverLPr();
2959            if (instantAppResolverComponent != null) {
2960                if (DEBUG_EPHEMERAL) {
2961                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2962                }
2963                mInstantAppResolverConnection = new EphemeralResolverConnection(
2964                        mContext, instantAppResolverComponent.first,
2965                        instantAppResolverComponent.second);
2966                mInstantAppResolverSettingsComponent =
2967                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2968            } else {
2969                mInstantAppResolverConnection = null;
2970                mInstantAppResolverSettingsComponent = null;
2971            }
2972            updateInstantAppInstallerLocked(null);
2973
2974            // Read and update the usage of dex files.
2975            // Do this at the end of PM init so that all the packages have their
2976            // data directory reconciled.
2977            // At this point we know the code paths of the packages, so we can validate
2978            // the disk file and build the internal cache.
2979            // The usage file is expected to be small so loading and verifying it
2980            // should take a fairly small time compare to the other activities (e.g. package
2981            // scanning).
2982            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2983            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2984            for (int userId : currentUserIds) {
2985                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2986            }
2987            mDexManager.load(userPackages);
2988        } // synchronized (mPackages)
2989        } // synchronized (mInstallLock)
2990
2991        // Now after opening every single application zip, make sure they
2992        // are all flushed.  Not really needed, but keeps things nice and
2993        // tidy.
2994        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2995        Runtime.getRuntime().gc();
2996        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2997
2998        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2999        FallbackCategoryProvider.loadFallbacks();
3000        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3001
3002        // The initial scanning above does many calls into installd while
3003        // holding the mPackages lock, but we're mostly interested in yelling
3004        // once we have a booted system.
3005        mInstaller.setWarnIfHeld(mPackages);
3006
3007        // Expose private service for system components to use.
3008        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3009        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3010    }
3011
3012    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3013        // we're only interested in updating the installer appliction when 1) it's not
3014        // already set or 2) the modified package is the installer
3015        if (mInstantAppInstallerActivity != null
3016                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3017                        .equals(modifiedPackage)) {
3018            return;
3019        }
3020        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3021    }
3022
3023    private static File preparePackageParserCache(boolean isUpgrade) {
3024        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3025            return null;
3026        }
3027
3028        // Disable package parsing on eng builds to allow for faster incremental development.
3029        if ("eng".equals(Build.TYPE)) {
3030            return null;
3031        }
3032
3033        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3034            Slog.i(TAG, "Disabling package parser cache due to system property.");
3035            return null;
3036        }
3037
3038        // The base directory for the package parser cache lives under /data/system/.
3039        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3040                "package_cache");
3041        if (cacheBaseDir == null) {
3042            return null;
3043        }
3044
3045        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3046        // This also serves to "GC" unused entries when the package cache version changes (which
3047        // can only happen during upgrades).
3048        if (isUpgrade) {
3049            FileUtils.deleteContents(cacheBaseDir);
3050        }
3051
3052
3053        // Return the versioned package cache directory. This is something like
3054        // "/data/system/package_cache/1"
3055        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3056
3057        // The following is a workaround to aid development on non-numbered userdebug
3058        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3059        // the system partition is newer.
3060        //
3061        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3062        // that starts with "eng." to signify that this is an engineering build and not
3063        // destined for release.
3064        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3065            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3066
3067            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3068            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3069            // in general and should not be used for production changes. In this specific case,
3070            // we know that they will work.
3071            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3072            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3073                FileUtils.deleteContents(cacheBaseDir);
3074                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3075            }
3076        }
3077
3078        return cacheDir;
3079    }
3080
3081    @Override
3082    public boolean isFirstBoot() {
3083        return mFirstBoot;
3084    }
3085
3086    @Override
3087    public boolean isOnlyCoreApps() {
3088        return mOnlyCore;
3089    }
3090
3091    @Override
3092    public boolean isUpgrade() {
3093        return mIsUpgrade;
3094    }
3095
3096    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3097        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3098
3099        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3100                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3101                UserHandle.USER_SYSTEM);
3102        if (matches.size() == 1) {
3103            return matches.get(0).getComponentInfo().packageName;
3104        } else if (matches.size() == 0) {
3105            Log.e(TAG, "There should probably be a verifier, but, none were found");
3106            return null;
3107        }
3108        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3109    }
3110
3111    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3112        synchronized (mPackages) {
3113            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3114            if (libraryEntry == null) {
3115                throw new IllegalStateException("Missing required shared library:" + name);
3116            }
3117            return libraryEntry.apk;
3118        }
3119    }
3120
3121    private @NonNull String getRequiredInstallerLPr() {
3122        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3123        intent.addCategory(Intent.CATEGORY_DEFAULT);
3124        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3125
3126        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3127                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3128                UserHandle.USER_SYSTEM);
3129        if (matches.size() == 1) {
3130            ResolveInfo resolveInfo = matches.get(0);
3131            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3132                throw new RuntimeException("The installer must be a privileged app");
3133            }
3134            return matches.get(0).getComponentInfo().packageName;
3135        } else {
3136            throw new RuntimeException("There must be exactly one installer; found " + matches);
3137        }
3138    }
3139
3140    private @NonNull String getRequiredUninstallerLPr() {
3141        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3142        intent.addCategory(Intent.CATEGORY_DEFAULT);
3143        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3144
3145        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3146                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3147                UserHandle.USER_SYSTEM);
3148        if (resolveInfo == null ||
3149                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3150            throw new RuntimeException("There must be exactly one uninstaller; found "
3151                    + resolveInfo);
3152        }
3153        return resolveInfo.getComponentInfo().packageName;
3154    }
3155
3156    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3157        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3158
3159        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3160                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3161                UserHandle.USER_SYSTEM);
3162        ResolveInfo best = null;
3163        final int N = matches.size();
3164        for (int i = 0; i < N; i++) {
3165            final ResolveInfo cur = matches.get(i);
3166            final String packageName = cur.getComponentInfo().packageName;
3167            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3168                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3169                continue;
3170            }
3171
3172            if (best == null || cur.priority > best.priority) {
3173                best = cur;
3174            }
3175        }
3176
3177        if (best != null) {
3178            return best.getComponentInfo().getComponentName();
3179        }
3180        Slog.w(TAG, "Intent filter verifier not found");
3181        return null;
3182    }
3183
3184    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3185        final String[] packageArray =
3186                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3187        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3188            if (DEBUG_EPHEMERAL) {
3189                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3190            }
3191            return null;
3192        }
3193
3194        final int callingUid = Binder.getCallingUid();
3195        final int resolveFlags =
3196                MATCH_DIRECT_BOOT_AWARE
3197                | MATCH_DIRECT_BOOT_UNAWARE
3198                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3199        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3200        final Intent resolverIntent = new Intent(actionName);
3201        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3202                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3203        // temporarily look for the old action
3204        if (resolvers.size() == 0) {
3205            if (DEBUG_EPHEMERAL) {
3206                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3207            }
3208            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3209            resolverIntent.setAction(actionName);
3210            resolvers = queryIntentServicesInternal(resolverIntent, null,
3211                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3212        }
3213        final int N = resolvers.size();
3214        if (N == 0) {
3215            if (DEBUG_EPHEMERAL) {
3216                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3217            }
3218            return null;
3219        }
3220
3221        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3222        for (int i = 0; i < N; i++) {
3223            final ResolveInfo info = resolvers.get(i);
3224
3225            if (info.serviceInfo == null) {
3226                continue;
3227            }
3228
3229            final String packageName = info.serviceInfo.packageName;
3230            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3231                if (DEBUG_EPHEMERAL) {
3232                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3233                            + " pkg: " + packageName + ", info:" + info);
3234                }
3235                continue;
3236            }
3237
3238            if (DEBUG_EPHEMERAL) {
3239                Slog.v(TAG, "Ephemeral resolver found;"
3240                        + " pkg: " + packageName + ", info:" + info);
3241            }
3242            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3243        }
3244        if (DEBUG_EPHEMERAL) {
3245            Slog.v(TAG, "Ephemeral resolver NOT found");
3246        }
3247        return null;
3248    }
3249
3250    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3251        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3252        intent.addCategory(Intent.CATEGORY_DEFAULT);
3253        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3254
3255        final int resolveFlags =
3256                MATCH_DIRECT_BOOT_AWARE
3257                | MATCH_DIRECT_BOOT_UNAWARE
3258                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3259        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3260                resolveFlags, UserHandle.USER_SYSTEM);
3261        // temporarily look for the old action
3262        if (matches.isEmpty()) {
3263            if (DEBUG_EPHEMERAL) {
3264                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3265            }
3266            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3267            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3268                    resolveFlags, UserHandle.USER_SYSTEM);
3269        }
3270        Iterator<ResolveInfo> iter = matches.iterator();
3271        while (iter.hasNext()) {
3272            final ResolveInfo rInfo = iter.next();
3273            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3274            if (ps != null) {
3275                final PermissionsState permissionsState = ps.getPermissionsState();
3276                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3277                    continue;
3278                }
3279            }
3280            iter.remove();
3281        }
3282        if (matches.size() == 0) {
3283            return null;
3284        } else if (matches.size() == 1) {
3285            return (ActivityInfo) matches.get(0).getComponentInfo();
3286        } else {
3287            throw new RuntimeException(
3288                    "There must be at most one ephemeral installer; found " + matches);
3289        }
3290    }
3291
3292    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3293            @NonNull ComponentName resolver) {
3294        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3295                .addCategory(Intent.CATEGORY_DEFAULT)
3296                .setPackage(resolver.getPackageName());
3297        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3298        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3299                UserHandle.USER_SYSTEM);
3300        // temporarily look for the old action
3301        if (matches.isEmpty()) {
3302            if (DEBUG_EPHEMERAL) {
3303                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3304            }
3305            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3306            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3307                    UserHandle.USER_SYSTEM);
3308        }
3309        if (matches.isEmpty()) {
3310            return null;
3311        }
3312        return matches.get(0).getComponentInfo().getComponentName();
3313    }
3314
3315    private void primeDomainVerificationsLPw(int userId) {
3316        if (DEBUG_DOMAIN_VERIFICATION) {
3317            Slog.d(TAG, "Priming domain verifications in user " + userId);
3318        }
3319
3320        SystemConfig systemConfig = SystemConfig.getInstance();
3321        ArraySet<String> packages = systemConfig.getLinkedApps();
3322
3323        for (String packageName : packages) {
3324            PackageParser.Package pkg = mPackages.get(packageName);
3325            if (pkg != null) {
3326                if (!pkg.isSystemApp()) {
3327                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3328                    continue;
3329                }
3330
3331                ArraySet<String> domains = null;
3332                for (PackageParser.Activity a : pkg.activities) {
3333                    for (ActivityIntentInfo filter : a.intents) {
3334                        if (hasValidDomains(filter)) {
3335                            if (domains == null) {
3336                                domains = new ArraySet<String>();
3337                            }
3338                            domains.addAll(filter.getHostsList());
3339                        }
3340                    }
3341                }
3342
3343                if (domains != null && domains.size() > 0) {
3344                    if (DEBUG_DOMAIN_VERIFICATION) {
3345                        Slog.v(TAG, "      + " + packageName);
3346                    }
3347                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3348                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3349                    // and then 'always' in the per-user state actually used for intent resolution.
3350                    final IntentFilterVerificationInfo ivi;
3351                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3352                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3353                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3354                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3355                } else {
3356                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3357                            + "' does not handle web links");
3358                }
3359            } else {
3360                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3361            }
3362        }
3363
3364        scheduleWritePackageRestrictionsLocked(userId);
3365        scheduleWriteSettingsLocked();
3366    }
3367
3368    private void applyFactoryDefaultBrowserLPw(int userId) {
3369        // The default browser app's package name is stored in a string resource,
3370        // with a product-specific overlay used for vendor customization.
3371        String browserPkg = mContext.getResources().getString(
3372                com.android.internal.R.string.default_browser);
3373        if (!TextUtils.isEmpty(browserPkg)) {
3374            // non-empty string => required to be a known package
3375            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3376            if (ps == null) {
3377                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3378                browserPkg = null;
3379            } else {
3380                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3381            }
3382        }
3383
3384        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3385        // default.  If there's more than one, just leave everything alone.
3386        if (browserPkg == null) {
3387            calculateDefaultBrowserLPw(userId);
3388        }
3389    }
3390
3391    private void calculateDefaultBrowserLPw(int userId) {
3392        List<String> allBrowsers = resolveAllBrowserApps(userId);
3393        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3394        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3395    }
3396
3397    private List<String> resolveAllBrowserApps(int userId) {
3398        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3399        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3400                PackageManager.MATCH_ALL, userId);
3401
3402        final int count = list.size();
3403        List<String> result = new ArrayList<String>(count);
3404        for (int i=0; i<count; i++) {
3405            ResolveInfo info = list.get(i);
3406            if (info.activityInfo == null
3407                    || !info.handleAllWebDataURI
3408                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3409                    || result.contains(info.activityInfo.packageName)) {
3410                continue;
3411            }
3412            result.add(info.activityInfo.packageName);
3413        }
3414
3415        return result;
3416    }
3417
3418    private boolean packageIsBrowser(String packageName, int userId) {
3419        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3420                PackageManager.MATCH_ALL, userId);
3421        final int N = list.size();
3422        for (int i = 0; i < N; i++) {
3423            ResolveInfo info = list.get(i);
3424            if (packageName.equals(info.activityInfo.packageName)) {
3425                return true;
3426            }
3427        }
3428        return false;
3429    }
3430
3431    private void checkDefaultBrowser() {
3432        final int myUserId = UserHandle.myUserId();
3433        final String packageName = getDefaultBrowserPackageName(myUserId);
3434        if (packageName != null) {
3435            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3436            if (info == null) {
3437                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3438                synchronized (mPackages) {
3439                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3440                }
3441            }
3442        }
3443    }
3444
3445    @Override
3446    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3447            throws RemoteException {
3448        try {
3449            return super.onTransact(code, data, reply, flags);
3450        } catch (RuntimeException e) {
3451            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3452                Slog.wtf(TAG, "Package Manager Crash", e);
3453            }
3454            throw e;
3455        }
3456    }
3457
3458    static int[] appendInts(int[] cur, int[] add) {
3459        if (add == null) return cur;
3460        if (cur == null) return add;
3461        final int N = add.length;
3462        for (int i=0; i<N; i++) {
3463            cur = appendInt(cur, add[i]);
3464        }
3465        return cur;
3466    }
3467
3468    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3469        if (!sUserManager.exists(userId)) return null;
3470        if (ps == null) {
3471            return null;
3472        }
3473        final PackageParser.Package p = ps.pkg;
3474        if (p == null) {
3475            return null;
3476        }
3477        // Filter out ephemeral app metadata:
3478        //   * The system/shell/root can see metadata for any app
3479        //   * An installed app can see metadata for 1) other installed apps
3480        //     and 2) ephemeral apps that have explicitly interacted with it
3481        //   * Ephemeral apps can only see their own data and exposed installed apps
3482        //   * Holding a signature permission allows seeing instant apps
3483        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3484        if (callingAppId != Process.SYSTEM_UID
3485                && callingAppId != Process.SHELL_UID
3486                && callingAppId != Process.ROOT_UID
3487                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3488                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3489            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3490            if (instantAppPackageName != null) {
3491                // ephemeral apps can only get information on themselves or
3492                // installed apps that are exposed.
3493                if (!instantAppPackageName.equals(p.packageName)
3494                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3495                    return null;
3496                }
3497            } else {
3498                if (ps.getInstantApp(userId)) {
3499                    // only get access to the ephemeral app if we've been granted access
3500                    if (!mInstantAppRegistry.isInstantAccessGranted(
3501                            userId, callingAppId, ps.appId)) {
3502                        return null;
3503                    }
3504                }
3505            }
3506        }
3507
3508        final PermissionsState permissionsState = ps.getPermissionsState();
3509
3510        // Compute GIDs only if requested
3511        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3512                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3513        // Compute granted permissions only if package has requested permissions
3514        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3515                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3516        final PackageUserState state = ps.readUserState(userId);
3517
3518        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3519                && ps.isSystem()) {
3520            flags |= MATCH_ANY_USER;
3521        }
3522
3523        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3524                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3525
3526        if (packageInfo == null) {
3527            return null;
3528        }
3529
3530        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3531
3532        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3533                resolveExternalPackageNameLPr(p);
3534
3535        return packageInfo;
3536    }
3537
3538    @Override
3539    public void checkPackageStartable(String packageName, int userId) {
3540        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3541
3542        synchronized (mPackages) {
3543            final PackageSetting ps = mSettings.mPackages.get(packageName);
3544            if (ps == null) {
3545                throw new SecurityException("Package " + packageName + " was not found!");
3546            }
3547
3548            if (!ps.getInstalled(userId)) {
3549                throw new SecurityException(
3550                        "Package " + packageName + " was not installed for user " + userId + "!");
3551            }
3552
3553            if (mSafeMode && !ps.isSystem()) {
3554                throw new SecurityException("Package " + packageName + " not a system app!");
3555            }
3556
3557            if (mFrozenPackages.contains(packageName)) {
3558                throw new SecurityException("Package " + packageName + " is currently frozen!");
3559            }
3560
3561            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3562                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3563                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3564            }
3565        }
3566    }
3567
3568    @Override
3569    public boolean isPackageAvailable(String packageName, int userId) {
3570        if (!sUserManager.exists(userId)) return false;
3571        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3572                false /* requireFullPermission */, false /* checkShell */, "is package available");
3573        synchronized (mPackages) {
3574            PackageParser.Package p = mPackages.get(packageName);
3575            if (p != null) {
3576                final PackageSetting ps = (PackageSetting) p.mExtras;
3577                if (ps != null) {
3578                    final PackageUserState state = ps.readUserState(userId);
3579                    if (state != null) {
3580                        return PackageParser.isAvailable(state);
3581                    }
3582                }
3583            }
3584        }
3585        return false;
3586    }
3587
3588    @Override
3589    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3590        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3591                flags, userId);
3592    }
3593
3594    @Override
3595    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3596            int flags, int userId) {
3597        return getPackageInfoInternal(versionedPackage.getPackageName(),
3598                // TODO: We will change version code to long, so in the new API it is long
3599                (int) versionedPackage.getVersionCode(), flags, userId);
3600    }
3601
3602    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3603            int flags, int userId) {
3604        if (!sUserManager.exists(userId)) return null;
3605        flags = updateFlagsForPackage(flags, userId, packageName);
3606        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3607                false /* requireFullPermission */, false /* checkShell */, "get package info");
3608
3609        // reader
3610        synchronized (mPackages) {
3611            // Normalize package name to handle renamed packages and static libs
3612            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3613
3614            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3615            if (matchFactoryOnly) {
3616                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3617                if (ps != null) {
3618                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
3619                        return null;
3620                    }
3621                    return generatePackageInfo(ps, flags, userId);
3622                }
3623            }
3624
3625            PackageParser.Package p = mPackages.get(packageName);
3626            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3627                return null;
3628            }
3629            if (DEBUG_PACKAGE_INFO)
3630                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3631            if (p != null) {
3632                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3633                        Binder.getCallingUid(), userId, flags)) {
3634                    return null;
3635                }
3636                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3637            }
3638            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3639                final PackageSetting ps = mSettings.mPackages.get(packageName);
3640                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
3641                    return null;
3642                }
3643                return generatePackageInfo(ps, flags, userId);
3644            }
3645        }
3646        return null;
3647    }
3648
3649    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3650            int flags) {
3651        // Callers can access only the libs they depend on, otherwise they need to explicitly
3652        // ask for the shared libraries given the caller is allowed to access all static libs.
3653        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3654            // System/shell/root get to see all static libs
3655            final int appId = UserHandle.getAppId(uid);
3656            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3657                    || appId == Process.ROOT_UID) {
3658                return false;
3659            }
3660        }
3661
3662        // No package means no static lib as it is always on internal storage
3663        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3664            return false;
3665        }
3666
3667        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3668                ps.pkg.staticSharedLibVersion);
3669        if (libEntry == null) {
3670            return false;
3671        }
3672
3673        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3674        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3675        if (uidPackageNames == null) {
3676            return true;
3677        }
3678
3679        for (String uidPackageName : uidPackageNames) {
3680            if (ps.name.equals(uidPackageName)) {
3681                return false;
3682            }
3683            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3684            if (uidPs != null) {
3685                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3686                        libEntry.info.getName());
3687                if (index < 0) {
3688                    continue;
3689                }
3690                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3691                    return false;
3692                }
3693            }
3694        }
3695        return true;
3696    }
3697
3698    @Override
3699    public String[] currentToCanonicalPackageNames(String[] names) {
3700        String[] out = new String[names.length];
3701        // reader
3702        synchronized (mPackages) {
3703            for (int i=names.length-1; i>=0; i--) {
3704                PackageSetting ps = mSettings.mPackages.get(names[i]);
3705                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3706            }
3707        }
3708        return out;
3709    }
3710
3711    @Override
3712    public String[] canonicalToCurrentPackageNames(String[] names) {
3713        String[] out = new String[names.length];
3714        // reader
3715        synchronized (mPackages) {
3716            for (int i=names.length-1; i>=0; i--) {
3717                String cur = mSettings.getRenamedPackageLPr(names[i]);
3718                out[i] = cur != null ? cur : names[i];
3719            }
3720        }
3721        return out;
3722    }
3723
3724    @Override
3725    public int getPackageUid(String packageName, int flags, int userId) {
3726        if (!sUserManager.exists(userId)) return -1;
3727        flags = updateFlagsForPackage(flags, userId, packageName);
3728        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3729                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3730
3731        // reader
3732        synchronized (mPackages) {
3733            final PackageParser.Package p = mPackages.get(packageName);
3734            if (p != null && p.isMatch(flags)) {
3735                return UserHandle.getUid(userId, p.applicationInfo.uid);
3736            }
3737            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3738                final PackageSetting ps = mSettings.mPackages.get(packageName);
3739                if (ps != null && ps.isMatch(flags)) {
3740                    return UserHandle.getUid(userId, ps.appId);
3741                }
3742            }
3743        }
3744
3745        return -1;
3746    }
3747
3748    @Override
3749    public int[] getPackageGids(String packageName, int flags, int userId) {
3750        if (!sUserManager.exists(userId)) return null;
3751        flags = updateFlagsForPackage(flags, userId, packageName);
3752        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3753                false /* requireFullPermission */, false /* checkShell */,
3754                "getPackageGids");
3755
3756        // reader
3757        synchronized (mPackages) {
3758            final PackageParser.Package p = mPackages.get(packageName);
3759            if (p != null && p.isMatch(flags)) {
3760                PackageSetting ps = (PackageSetting) p.mExtras;
3761                // TODO: Shouldn't this be checking for package installed state for userId and
3762                // return null?
3763                return ps.getPermissionsState().computeGids(userId);
3764            }
3765            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3766                final PackageSetting ps = mSettings.mPackages.get(packageName);
3767                if (ps != null && ps.isMatch(flags)) {
3768                    return ps.getPermissionsState().computeGids(userId);
3769                }
3770            }
3771        }
3772
3773        return null;
3774    }
3775
3776    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3777        if (bp.perm != null) {
3778            return PackageParser.generatePermissionInfo(bp.perm, flags);
3779        }
3780        PermissionInfo pi = new PermissionInfo();
3781        pi.name = bp.name;
3782        pi.packageName = bp.sourcePackage;
3783        pi.nonLocalizedLabel = bp.name;
3784        pi.protectionLevel = bp.protectionLevel;
3785        return pi;
3786    }
3787
3788    @Override
3789    public PermissionInfo getPermissionInfo(String name, int flags) {
3790        // reader
3791        synchronized (mPackages) {
3792            final BasePermission p = mSettings.mPermissions.get(name);
3793            if (p != null) {
3794                return generatePermissionInfo(p, flags);
3795            }
3796            return null;
3797        }
3798    }
3799
3800    @Override
3801    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3802            int flags) {
3803        // reader
3804        synchronized (mPackages) {
3805            if (group != null && !mPermissionGroups.containsKey(group)) {
3806                // This is thrown as NameNotFoundException
3807                return null;
3808            }
3809
3810            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3811            for (BasePermission p : mSettings.mPermissions.values()) {
3812                if (group == null) {
3813                    if (p.perm == null || p.perm.info.group == null) {
3814                        out.add(generatePermissionInfo(p, flags));
3815                    }
3816                } else {
3817                    if (p.perm != null && group.equals(p.perm.info.group)) {
3818                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3819                    }
3820                }
3821            }
3822            return new ParceledListSlice<>(out);
3823        }
3824    }
3825
3826    @Override
3827    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3828        // reader
3829        synchronized (mPackages) {
3830            return PackageParser.generatePermissionGroupInfo(
3831                    mPermissionGroups.get(name), flags);
3832        }
3833    }
3834
3835    @Override
3836    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3837        // reader
3838        synchronized (mPackages) {
3839            final int N = mPermissionGroups.size();
3840            ArrayList<PermissionGroupInfo> out
3841                    = new ArrayList<PermissionGroupInfo>(N);
3842            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3843                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3844            }
3845            return new ParceledListSlice<>(out);
3846        }
3847    }
3848
3849    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3850            int uid, int userId) {
3851        if (!sUserManager.exists(userId)) return null;
3852        PackageSetting ps = mSettings.mPackages.get(packageName);
3853        if (ps != null) {
3854            if (filterSharedLibPackageLPr(ps, uid, userId, flags)) {
3855                return null;
3856            }
3857            if (ps.pkg == null) {
3858                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3859                if (pInfo != null) {
3860                    return pInfo.applicationInfo;
3861                }
3862                return null;
3863            }
3864            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3865                    ps.readUserState(userId), userId);
3866            if (ai != null) {
3867                rebaseEnabledOverlays(ai, userId);
3868                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3869            }
3870            return ai;
3871        }
3872        return null;
3873    }
3874
3875    @Override
3876    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3877        if (!sUserManager.exists(userId)) return null;
3878        flags = updateFlagsForApplication(flags, userId, packageName);
3879        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3880                false /* requireFullPermission */, false /* checkShell */, "get application info");
3881
3882        // writer
3883        synchronized (mPackages) {
3884            // Normalize package name to handle renamed packages and static libs
3885            packageName = resolveInternalPackageNameLPr(packageName,
3886                    PackageManager.VERSION_CODE_HIGHEST);
3887
3888            PackageParser.Package p = mPackages.get(packageName);
3889            if (DEBUG_PACKAGE_INFO) Log.v(
3890                    TAG, "getApplicationInfo " + packageName
3891                    + ": " + p);
3892            if (p != null) {
3893                PackageSetting ps = mSettings.mPackages.get(packageName);
3894                if (ps == null) return null;
3895                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
3896                    return null;
3897                }
3898                // Note: isEnabledLP() does not apply here - always return info
3899                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3900                        p, flags, ps.readUserState(userId), userId);
3901                if (ai != null) {
3902                    rebaseEnabledOverlays(ai, userId);
3903                    ai.packageName = resolveExternalPackageNameLPr(p);
3904                }
3905                return ai;
3906            }
3907            if ("android".equals(packageName)||"system".equals(packageName)) {
3908                return mAndroidApplication;
3909            }
3910            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3911                // Already generates the external package name
3912                return generateApplicationInfoFromSettingsLPw(packageName,
3913                        Binder.getCallingUid(), flags, userId);
3914            }
3915        }
3916        return null;
3917    }
3918
3919    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3920        List<String> paths = new ArrayList<>();
3921        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3922            mEnabledOverlayPaths.get(userId);
3923        if (userSpecificOverlays != null) {
3924            if (!"android".equals(ai.packageName)) {
3925                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3926                if (frameworkOverlays != null) {
3927                    paths.addAll(frameworkOverlays);
3928                }
3929            }
3930
3931            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3932            if (appOverlays != null) {
3933                paths.addAll(appOverlays);
3934            }
3935        }
3936        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3937    }
3938
3939    private String normalizePackageNameLPr(String packageName) {
3940        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3941        return normalizedPackageName != null ? normalizedPackageName : packageName;
3942    }
3943
3944    @Override
3945    public void deletePreloadsFileCache() {
3946        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3947            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3948        }
3949        File dir = Environment.getDataPreloadsFileCacheDirectory();
3950        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3951        FileUtils.deleteContents(dir);
3952    }
3953
3954    @Override
3955    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3956            final IPackageDataObserver observer) {
3957        mContext.enforceCallingOrSelfPermission(
3958                android.Manifest.permission.CLEAR_APP_CACHE, null);
3959        mHandler.post(() -> {
3960            boolean success = false;
3961            try {
3962                freeStorage(volumeUuid, freeStorageSize, 0);
3963                success = true;
3964            } catch (IOException e) {
3965                Slog.w(TAG, e);
3966            }
3967            if (observer != null) {
3968                try {
3969                    observer.onRemoveCompleted(null, success);
3970                } catch (RemoteException e) {
3971                    Slog.w(TAG, e);
3972                }
3973            }
3974        });
3975    }
3976
3977    @Override
3978    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3979            final IntentSender pi) {
3980        mContext.enforceCallingOrSelfPermission(
3981                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3982        mHandler.post(() -> {
3983            boolean success = false;
3984            try {
3985                freeStorage(volumeUuid, freeStorageSize, 0);
3986                success = true;
3987            } catch (IOException e) {
3988                Slog.w(TAG, e);
3989            }
3990            if (pi != null) {
3991                try {
3992                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3993                } catch (SendIntentException e) {
3994                    Slog.w(TAG, e);
3995                }
3996            }
3997        });
3998    }
3999
4000    /**
4001     * Blocking call to clear various types of cached data across the system
4002     * until the requested bytes are available.
4003     */
4004    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4005        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4006        final File file = storage.findPathForUuid(volumeUuid);
4007        if (file.getUsableSpace() >= bytes) return;
4008
4009        if (ENABLE_FREE_CACHE_V2) {
4010            final boolean aggressive = (storageFlags
4011                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4012            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4013                    volumeUuid);
4014
4015            // 1. Pre-flight to determine if we have any chance to succeed
4016            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4017            if (internalVolume && (aggressive || SystemProperties
4018                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4019                deletePreloadsFileCache();
4020                if (file.getUsableSpace() >= bytes) return;
4021            }
4022
4023            // 3. Consider parsed APK data (aggressive only)
4024            if (internalVolume && aggressive) {
4025                FileUtils.deleteContents(mCacheDir);
4026                if (file.getUsableSpace() >= bytes) return;
4027            }
4028
4029            // 4. Consider cached app data (above quotas)
4030            try {
4031                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
4032            } catch (InstallerException ignored) {
4033            }
4034            if (file.getUsableSpace() >= bytes) return;
4035
4036            // 5. Consider shared libraries with refcount=0 and age>2h
4037            // 6. Consider dexopt output (aggressive only)
4038            // 7. Consider ephemeral apps not used in last week
4039
4040            // 8. Consider cached app data (below quotas)
4041            try {
4042                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
4043                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4044            } catch (InstallerException ignored) {
4045            }
4046            if (file.getUsableSpace() >= bytes) return;
4047
4048            // 9. Consider DropBox entries
4049            // 10. Consider ephemeral cookies
4050
4051        } else {
4052            try {
4053                mInstaller.freeCache(volumeUuid, bytes, 0);
4054            } catch (InstallerException ignored) {
4055            }
4056            if (file.getUsableSpace() >= bytes) return;
4057        }
4058
4059        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4060    }
4061
4062    /**
4063     * Update given flags based on encryption status of current user.
4064     */
4065    private int updateFlags(int flags, int userId) {
4066        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4067                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4068            // Caller expressed an explicit opinion about what encryption
4069            // aware/unaware components they want to see, so fall through and
4070            // give them what they want
4071        } else {
4072            // Caller expressed no opinion, so match based on user state
4073            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4074                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4075            } else {
4076                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4077            }
4078        }
4079        return flags;
4080    }
4081
4082    private UserManagerInternal getUserManagerInternal() {
4083        if (mUserManagerInternal == null) {
4084            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4085        }
4086        return mUserManagerInternal;
4087    }
4088
4089    private DeviceIdleController.LocalService getDeviceIdleController() {
4090        if (mDeviceIdleController == null) {
4091            mDeviceIdleController =
4092                    LocalServices.getService(DeviceIdleController.LocalService.class);
4093        }
4094        return mDeviceIdleController;
4095    }
4096
4097    /**
4098     * Update given flags when being used to request {@link PackageInfo}.
4099     */
4100    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4101        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4102        boolean triaged = true;
4103        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4104                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4105            // Caller is asking for component details, so they'd better be
4106            // asking for specific encryption matching behavior, or be triaged
4107            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4108                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4109                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4110                triaged = false;
4111            }
4112        }
4113        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4114                | PackageManager.MATCH_SYSTEM_ONLY
4115                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4116            triaged = false;
4117        }
4118        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4119            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4120                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4121                    + Debug.getCallers(5));
4122        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4123                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4124            // If the caller wants all packages and has a restricted profile associated with it,
4125            // then match all users. This is to make sure that launchers that need to access work
4126            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4127            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4128            flags |= PackageManager.MATCH_ANY_USER;
4129        }
4130        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4131            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4132                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4133        }
4134        return updateFlags(flags, userId);
4135    }
4136
4137    /**
4138     * Update given flags when being used to request {@link ApplicationInfo}.
4139     */
4140    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4141        return updateFlagsForPackage(flags, userId, cookie);
4142    }
4143
4144    /**
4145     * Update given flags when being used to request {@link ComponentInfo}.
4146     */
4147    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4148        if (cookie instanceof Intent) {
4149            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4150                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4151            }
4152        }
4153
4154        boolean triaged = true;
4155        // Caller is asking for component details, so they'd better be
4156        // asking for specific encryption matching behavior, or be triaged
4157        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4158                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4159                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4160            triaged = false;
4161        }
4162        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4163            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4164                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4165        }
4166
4167        return updateFlags(flags, userId);
4168    }
4169
4170    /**
4171     * Update given intent when being used to request {@link ResolveInfo}.
4172     */
4173    private Intent updateIntentForResolve(Intent intent) {
4174        if (intent.getSelector() != null) {
4175            intent = intent.getSelector();
4176        }
4177        if (DEBUG_PREFERRED) {
4178            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4179        }
4180        return intent;
4181    }
4182
4183    /**
4184     * Update given flags when being used to request {@link ResolveInfo}.
4185     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4186     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4187     * flag set. However, this flag is only honoured in three circumstances:
4188     * <ul>
4189     * <li>when called from a system process</li>
4190     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4191     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4192     * action and a {@code android.intent.category.BROWSABLE} category</li>
4193     * </ul>
4194     */
4195    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4196        return updateFlagsForResolve(flags, userId, intent, callingUid,
4197                false /*includeInstantApps*/, false /*onlyExposedExplicitly*/);
4198    }
4199    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4200            boolean includeInstantApps) {
4201        return updateFlagsForResolve(flags, userId, intent, callingUid,
4202                includeInstantApps, false /*onlyExposedExplicitly*/);
4203    }
4204    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4205            boolean includeInstantApps, boolean onlyExposedExplicitly) {
4206        // Safe mode means we shouldn't match any third-party components
4207        if (mSafeMode) {
4208            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4209        }
4210        if (getInstantAppPackageName(callingUid) != null) {
4211            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4212            if (onlyExposedExplicitly) {
4213                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4214            }
4215            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4216            flags |= PackageManager.MATCH_INSTANT;
4217        } else {
4218            // Otherwise, prevent leaking ephemeral components
4219            final boolean isSpecialProcess =
4220                    callingUid == Process.SYSTEM_UID
4221                    || callingUid == Process.SHELL_UID
4222                    || callingUid == 0;
4223            final boolean allowMatchInstant =
4224                    (includeInstantApps
4225                            && Intent.ACTION_VIEW.equals(intent.getAction())
4226                            && hasWebURI(intent))
4227                    || isSpecialProcess
4228                    || mContext.checkCallingOrSelfPermission(
4229                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4230            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4231                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4232            if (!allowMatchInstant) {
4233                flags &= ~PackageManager.MATCH_INSTANT;
4234            }
4235        }
4236        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4237    }
4238
4239    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4240            int userId) {
4241        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4242        if (ret != null) {
4243            rebaseEnabledOverlays(ret.applicationInfo, userId);
4244        }
4245        return ret;
4246    }
4247
4248    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4249            PackageUserState state, int userId) {
4250        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4251        if (ai != null) {
4252            rebaseEnabledOverlays(ai.applicationInfo, userId);
4253        }
4254        return ai;
4255    }
4256
4257    @Override
4258    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4259        if (!sUserManager.exists(userId)) return null;
4260        flags = updateFlagsForComponent(flags, userId, component);
4261        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4262                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4263        synchronized (mPackages) {
4264            PackageParser.Activity a = mActivities.mActivities.get(component);
4265
4266            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4267            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4268                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4269                if (ps == null) return null;
4270                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4271            }
4272            if (mResolveComponentName.equals(component)) {
4273                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4274                        userId);
4275            }
4276        }
4277        return null;
4278    }
4279
4280    @Override
4281    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4282            String resolvedType) {
4283        synchronized (mPackages) {
4284            if (component.equals(mResolveComponentName)) {
4285                // The resolver supports EVERYTHING!
4286                return true;
4287            }
4288            PackageParser.Activity a = mActivities.mActivities.get(component);
4289            if (a == null) {
4290                return false;
4291            }
4292            for (int i=0; i<a.intents.size(); i++) {
4293                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4294                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4295                    return true;
4296                }
4297            }
4298            return false;
4299        }
4300    }
4301
4302    @Override
4303    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4304        if (!sUserManager.exists(userId)) return null;
4305        flags = updateFlagsForComponent(flags, userId, component);
4306        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4307                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4308        synchronized (mPackages) {
4309            PackageParser.Activity a = mReceivers.mActivities.get(component);
4310            if (DEBUG_PACKAGE_INFO) Log.v(
4311                TAG, "getReceiverInfo " + component + ": " + a);
4312            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4313                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4314                if (ps == null) return null;
4315                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4316            }
4317        }
4318        return null;
4319    }
4320
4321    @Override
4322    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4323        if (!sUserManager.exists(userId)) return null;
4324        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4325
4326        flags = updateFlagsForPackage(flags, userId, null);
4327
4328        final boolean canSeeStaticLibraries =
4329                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4330                        == PERMISSION_GRANTED
4331                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4332                        == PERMISSION_GRANTED
4333                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4334                        == PERMISSION_GRANTED
4335                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4336                        == PERMISSION_GRANTED;
4337
4338        synchronized (mPackages) {
4339            List<SharedLibraryInfo> result = null;
4340
4341            final int libCount = mSharedLibraries.size();
4342            for (int i = 0; i < libCount; i++) {
4343                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4344                if (versionedLib == null) {
4345                    continue;
4346                }
4347
4348                final int versionCount = versionedLib.size();
4349                for (int j = 0; j < versionCount; j++) {
4350                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4351                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4352                        break;
4353                    }
4354                    final long identity = Binder.clearCallingIdentity();
4355                    try {
4356                        PackageInfo packageInfo = getPackageInfoVersioned(
4357                                libInfo.getDeclaringPackage(), flags, userId);
4358                        if (packageInfo == null) {
4359                            continue;
4360                        }
4361                    } finally {
4362                        Binder.restoreCallingIdentity(identity);
4363                    }
4364
4365                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4366                            libInfo.getVersion(), libInfo.getType(),
4367                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4368                            flags, userId));
4369
4370                    if (result == null) {
4371                        result = new ArrayList<>();
4372                    }
4373                    result.add(resLibInfo);
4374                }
4375            }
4376
4377            return result != null ? new ParceledListSlice<>(result) : null;
4378        }
4379    }
4380
4381    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4382            SharedLibraryInfo libInfo, int flags, int userId) {
4383        List<VersionedPackage> versionedPackages = null;
4384        final int packageCount = mSettings.mPackages.size();
4385        for (int i = 0; i < packageCount; i++) {
4386            PackageSetting ps = mSettings.mPackages.valueAt(i);
4387
4388            if (ps == null) {
4389                continue;
4390            }
4391
4392            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4393                continue;
4394            }
4395
4396            final String libName = libInfo.getName();
4397            if (libInfo.isStatic()) {
4398                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4399                if (libIdx < 0) {
4400                    continue;
4401                }
4402                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4403                    continue;
4404                }
4405                if (versionedPackages == null) {
4406                    versionedPackages = new ArrayList<>();
4407                }
4408                // If the dependent is a static shared lib, use the public package name
4409                String dependentPackageName = ps.name;
4410                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4411                    dependentPackageName = ps.pkg.manifestPackageName;
4412                }
4413                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4414            } else if (ps.pkg != null) {
4415                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4416                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4417                    if (versionedPackages == null) {
4418                        versionedPackages = new ArrayList<>();
4419                    }
4420                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4421                }
4422            }
4423        }
4424
4425        return versionedPackages;
4426    }
4427
4428    @Override
4429    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4430        if (!sUserManager.exists(userId)) return null;
4431        flags = updateFlagsForComponent(flags, userId, component);
4432        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4433                false /* requireFullPermission */, false /* checkShell */, "get service info");
4434        synchronized (mPackages) {
4435            PackageParser.Service s = mServices.mServices.get(component);
4436            if (DEBUG_PACKAGE_INFO) Log.v(
4437                TAG, "getServiceInfo " + component + ": " + s);
4438            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4439                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4440                if (ps == null) return null;
4441                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4442                        ps.readUserState(userId), userId);
4443                if (si != null) {
4444                    rebaseEnabledOverlays(si.applicationInfo, userId);
4445                }
4446                return si;
4447            }
4448        }
4449        return null;
4450    }
4451
4452    @Override
4453    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4454        if (!sUserManager.exists(userId)) return null;
4455        flags = updateFlagsForComponent(flags, userId, component);
4456        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4457                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4458        synchronized (mPackages) {
4459            PackageParser.Provider p = mProviders.mProviders.get(component);
4460            if (DEBUG_PACKAGE_INFO) Log.v(
4461                TAG, "getProviderInfo " + component + ": " + p);
4462            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4463                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4464                if (ps == null) return null;
4465                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4466                        ps.readUserState(userId), userId);
4467                if (pi != null) {
4468                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4469                }
4470                return pi;
4471            }
4472        }
4473        return null;
4474    }
4475
4476    @Override
4477    public String[] getSystemSharedLibraryNames() {
4478        synchronized (mPackages) {
4479            Set<String> libs = null;
4480            final int libCount = mSharedLibraries.size();
4481            for (int i = 0; i < libCount; i++) {
4482                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4483                if (versionedLib == null) {
4484                    continue;
4485                }
4486                final int versionCount = versionedLib.size();
4487                for (int j = 0; j < versionCount; j++) {
4488                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4489                    if (!libEntry.info.isStatic()) {
4490                        if (libs == null) {
4491                            libs = new ArraySet<>();
4492                        }
4493                        libs.add(libEntry.info.getName());
4494                        break;
4495                    }
4496                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4497                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4498                            UserHandle.getUserId(Binder.getCallingUid()),
4499                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4500                        if (libs == null) {
4501                            libs = new ArraySet<>();
4502                        }
4503                        libs.add(libEntry.info.getName());
4504                        break;
4505                    }
4506                }
4507            }
4508
4509            if (libs != null) {
4510                String[] libsArray = new String[libs.size()];
4511                libs.toArray(libsArray);
4512                return libsArray;
4513            }
4514
4515            return null;
4516        }
4517    }
4518
4519    @Override
4520    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4521        synchronized (mPackages) {
4522            return mServicesSystemSharedLibraryPackageName;
4523        }
4524    }
4525
4526    @Override
4527    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4528        synchronized (mPackages) {
4529            return mSharedSystemSharedLibraryPackageName;
4530        }
4531    }
4532
4533    private void updateSequenceNumberLP(String packageName, int[] userList) {
4534        for (int i = userList.length - 1; i >= 0; --i) {
4535            final int userId = userList[i];
4536            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4537            if (changedPackages == null) {
4538                changedPackages = new SparseArray<>();
4539                mChangedPackages.put(userId, changedPackages);
4540            }
4541            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4542            if (sequenceNumbers == null) {
4543                sequenceNumbers = new HashMap<>();
4544                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4545            }
4546            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4547            if (sequenceNumber != null) {
4548                changedPackages.remove(sequenceNumber);
4549            }
4550            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4551            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4552        }
4553        mChangedPackagesSequenceNumber++;
4554    }
4555
4556    @Override
4557    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4558        synchronized (mPackages) {
4559            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4560                return null;
4561            }
4562            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4563            if (changedPackages == null) {
4564                return null;
4565            }
4566            final List<String> packageNames =
4567                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4568            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4569                final String packageName = changedPackages.get(i);
4570                if (packageName != null) {
4571                    packageNames.add(packageName);
4572                }
4573            }
4574            return packageNames.isEmpty()
4575                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4576        }
4577    }
4578
4579    @Override
4580    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4581        ArrayList<FeatureInfo> res;
4582        synchronized (mAvailableFeatures) {
4583            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4584            res.addAll(mAvailableFeatures.values());
4585        }
4586        final FeatureInfo fi = new FeatureInfo();
4587        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4588                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4589        res.add(fi);
4590
4591        return new ParceledListSlice<>(res);
4592    }
4593
4594    @Override
4595    public boolean hasSystemFeature(String name, int version) {
4596        synchronized (mAvailableFeatures) {
4597            final FeatureInfo feat = mAvailableFeatures.get(name);
4598            if (feat == null) {
4599                return false;
4600            } else {
4601                return feat.version >= version;
4602            }
4603        }
4604    }
4605
4606    @Override
4607    public int checkPermission(String permName, String pkgName, int userId) {
4608        if (!sUserManager.exists(userId)) {
4609            return PackageManager.PERMISSION_DENIED;
4610        }
4611
4612        synchronized (mPackages) {
4613            final PackageParser.Package p = mPackages.get(pkgName);
4614            if (p != null && p.mExtras != null) {
4615                final PackageSetting ps = (PackageSetting) p.mExtras;
4616                final PermissionsState permissionsState = ps.getPermissionsState();
4617                if (permissionsState.hasPermission(permName, userId)) {
4618                    return PackageManager.PERMISSION_GRANTED;
4619                }
4620                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4621                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4622                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4623                    return PackageManager.PERMISSION_GRANTED;
4624                }
4625            }
4626        }
4627
4628        return PackageManager.PERMISSION_DENIED;
4629    }
4630
4631    @Override
4632    public int checkUidPermission(String permName, int uid) {
4633        final int userId = UserHandle.getUserId(uid);
4634
4635        if (!sUserManager.exists(userId)) {
4636            return PackageManager.PERMISSION_DENIED;
4637        }
4638
4639        synchronized (mPackages) {
4640            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4641            if (obj != null) {
4642                final SettingBase ps = (SettingBase) obj;
4643                final PermissionsState permissionsState = ps.getPermissionsState();
4644                if (permissionsState.hasPermission(permName, userId)) {
4645                    return PackageManager.PERMISSION_GRANTED;
4646                }
4647                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4648                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4649                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4650                    return PackageManager.PERMISSION_GRANTED;
4651                }
4652            } else {
4653                ArraySet<String> perms = mSystemPermissions.get(uid);
4654                if (perms != null) {
4655                    if (perms.contains(permName)) {
4656                        return PackageManager.PERMISSION_GRANTED;
4657                    }
4658                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4659                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4660                        return PackageManager.PERMISSION_GRANTED;
4661                    }
4662                }
4663            }
4664        }
4665
4666        return PackageManager.PERMISSION_DENIED;
4667    }
4668
4669    @Override
4670    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4671        if (UserHandle.getCallingUserId() != userId) {
4672            mContext.enforceCallingPermission(
4673                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4674                    "isPermissionRevokedByPolicy for user " + userId);
4675        }
4676
4677        if (checkPermission(permission, packageName, userId)
4678                == PackageManager.PERMISSION_GRANTED) {
4679            return false;
4680        }
4681
4682        final long identity = Binder.clearCallingIdentity();
4683        try {
4684            final int flags = getPermissionFlags(permission, packageName, userId);
4685            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4686        } finally {
4687            Binder.restoreCallingIdentity(identity);
4688        }
4689    }
4690
4691    @Override
4692    public String getPermissionControllerPackageName() {
4693        synchronized (mPackages) {
4694            return mRequiredInstallerPackage;
4695        }
4696    }
4697
4698    /**
4699     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4700     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4701     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4702     * @param message the message to log on security exception
4703     */
4704    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4705            boolean checkShell, String message) {
4706        if (userId < 0) {
4707            throw new IllegalArgumentException("Invalid userId " + userId);
4708        }
4709        if (checkShell) {
4710            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4711        }
4712        if (userId == UserHandle.getUserId(callingUid)) return;
4713        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4714            if (requireFullPermission) {
4715                mContext.enforceCallingOrSelfPermission(
4716                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4717            } else {
4718                try {
4719                    mContext.enforceCallingOrSelfPermission(
4720                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4721                } catch (SecurityException se) {
4722                    mContext.enforceCallingOrSelfPermission(
4723                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4724                }
4725            }
4726        }
4727    }
4728
4729    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4730        if (callingUid == Process.SHELL_UID) {
4731            if (userHandle >= 0
4732                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4733                throw new SecurityException("Shell does not have permission to access user "
4734                        + userHandle);
4735            } else if (userHandle < 0) {
4736                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4737                        + Debug.getCallers(3));
4738            }
4739        }
4740    }
4741
4742    private BasePermission findPermissionTreeLP(String permName) {
4743        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4744            if (permName.startsWith(bp.name) &&
4745                    permName.length() > bp.name.length() &&
4746                    permName.charAt(bp.name.length()) == '.') {
4747                return bp;
4748            }
4749        }
4750        return null;
4751    }
4752
4753    private BasePermission checkPermissionTreeLP(String permName) {
4754        if (permName != null) {
4755            BasePermission bp = findPermissionTreeLP(permName);
4756            if (bp != null) {
4757                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4758                    return bp;
4759                }
4760                throw new SecurityException("Calling uid "
4761                        + Binder.getCallingUid()
4762                        + " is not allowed to add to permission tree "
4763                        + bp.name + " owned by uid " + bp.uid);
4764            }
4765        }
4766        throw new SecurityException("No permission tree found for " + permName);
4767    }
4768
4769    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4770        if (s1 == null) {
4771            return s2 == null;
4772        }
4773        if (s2 == null) {
4774            return false;
4775        }
4776        if (s1.getClass() != s2.getClass()) {
4777            return false;
4778        }
4779        return s1.equals(s2);
4780    }
4781
4782    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4783        if (pi1.icon != pi2.icon) return false;
4784        if (pi1.logo != pi2.logo) return false;
4785        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4786        if (!compareStrings(pi1.name, pi2.name)) return false;
4787        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4788        // We'll take care of setting this one.
4789        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4790        // These are not currently stored in settings.
4791        //if (!compareStrings(pi1.group, pi2.group)) return false;
4792        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4793        //if (pi1.labelRes != pi2.labelRes) return false;
4794        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4795        return true;
4796    }
4797
4798    int permissionInfoFootprint(PermissionInfo info) {
4799        int size = info.name.length();
4800        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4801        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4802        return size;
4803    }
4804
4805    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4806        int size = 0;
4807        for (BasePermission perm : mSettings.mPermissions.values()) {
4808            if (perm.uid == tree.uid) {
4809                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4810            }
4811        }
4812        return size;
4813    }
4814
4815    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4816        // We calculate the max size of permissions defined by this uid and throw
4817        // if that plus the size of 'info' would exceed our stated maximum.
4818        if (tree.uid != Process.SYSTEM_UID) {
4819            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4820            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4821                throw new SecurityException("Permission tree size cap exceeded");
4822            }
4823        }
4824    }
4825
4826    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4827        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4828            throw new SecurityException("Label must be specified in permission");
4829        }
4830        BasePermission tree = checkPermissionTreeLP(info.name);
4831        BasePermission bp = mSettings.mPermissions.get(info.name);
4832        boolean added = bp == null;
4833        boolean changed = true;
4834        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4835        if (added) {
4836            enforcePermissionCapLocked(info, tree);
4837            bp = new BasePermission(info.name, tree.sourcePackage,
4838                    BasePermission.TYPE_DYNAMIC);
4839        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4840            throw new SecurityException(
4841                    "Not allowed to modify non-dynamic permission "
4842                    + info.name);
4843        } else {
4844            if (bp.protectionLevel == fixedLevel
4845                    && bp.perm.owner.equals(tree.perm.owner)
4846                    && bp.uid == tree.uid
4847                    && comparePermissionInfos(bp.perm.info, info)) {
4848                changed = false;
4849            }
4850        }
4851        bp.protectionLevel = fixedLevel;
4852        info = new PermissionInfo(info);
4853        info.protectionLevel = fixedLevel;
4854        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4855        bp.perm.info.packageName = tree.perm.info.packageName;
4856        bp.uid = tree.uid;
4857        if (added) {
4858            mSettings.mPermissions.put(info.name, bp);
4859        }
4860        if (changed) {
4861            if (!async) {
4862                mSettings.writeLPr();
4863            } else {
4864                scheduleWriteSettingsLocked();
4865            }
4866        }
4867        return added;
4868    }
4869
4870    @Override
4871    public boolean addPermission(PermissionInfo info) {
4872        synchronized (mPackages) {
4873            return addPermissionLocked(info, false);
4874        }
4875    }
4876
4877    @Override
4878    public boolean addPermissionAsync(PermissionInfo info) {
4879        synchronized (mPackages) {
4880            return addPermissionLocked(info, true);
4881        }
4882    }
4883
4884    @Override
4885    public void removePermission(String name) {
4886        synchronized (mPackages) {
4887            checkPermissionTreeLP(name);
4888            BasePermission bp = mSettings.mPermissions.get(name);
4889            if (bp != null) {
4890                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4891                    throw new SecurityException(
4892                            "Not allowed to modify non-dynamic permission "
4893                            + name);
4894                }
4895                mSettings.mPermissions.remove(name);
4896                mSettings.writeLPr();
4897            }
4898        }
4899    }
4900
4901    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4902            BasePermission bp) {
4903        int index = pkg.requestedPermissions.indexOf(bp.name);
4904        if (index == -1) {
4905            throw new SecurityException("Package " + pkg.packageName
4906                    + " has not requested permission " + bp.name);
4907        }
4908        if (!bp.isRuntime() && !bp.isDevelopment()) {
4909            throw new SecurityException("Permission " + bp.name
4910                    + " is not a changeable permission type");
4911        }
4912    }
4913
4914    @Override
4915    public void grantRuntimePermission(String packageName, String name, final int userId) {
4916        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4917    }
4918
4919    private void grantRuntimePermission(String packageName, String name, final int userId,
4920            boolean overridePolicy) {
4921        if (!sUserManager.exists(userId)) {
4922            Log.e(TAG, "No such user:" + userId);
4923            return;
4924        }
4925
4926        mContext.enforceCallingOrSelfPermission(
4927                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4928                "grantRuntimePermission");
4929
4930        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4931                true /* requireFullPermission */, true /* checkShell */,
4932                "grantRuntimePermission");
4933
4934        final int uid;
4935        final SettingBase sb;
4936
4937        synchronized (mPackages) {
4938            final PackageParser.Package pkg = mPackages.get(packageName);
4939            if (pkg == null) {
4940                throw new IllegalArgumentException("Unknown package: " + packageName);
4941            }
4942
4943            final BasePermission bp = mSettings.mPermissions.get(name);
4944            if (bp == null) {
4945                throw new IllegalArgumentException("Unknown permission: " + name);
4946            }
4947
4948            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4949
4950            // If a permission review is required for legacy apps we represent
4951            // their permissions as always granted runtime ones since we need
4952            // to keep the review required permission flag per user while an
4953            // install permission's state is shared across all users.
4954            if (mPermissionReviewRequired
4955                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4956                    && bp.isRuntime()) {
4957                return;
4958            }
4959
4960            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4961            sb = (SettingBase) pkg.mExtras;
4962            if (sb == null) {
4963                throw new IllegalArgumentException("Unknown package: " + packageName);
4964            }
4965
4966            final PermissionsState permissionsState = sb.getPermissionsState();
4967
4968            final int flags = permissionsState.getPermissionFlags(name, userId);
4969            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4970                throw new SecurityException("Cannot grant system fixed permission "
4971                        + name + " for package " + packageName);
4972            }
4973            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4974                throw new SecurityException("Cannot grant policy fixed permission "
4975                        + name + " for package " + packageName);
4976            }
4977
4978            if (bp.isDevelopment()) {
4979                // Development permissions must be handled specially, since they are not
4980                // normal runtime permissions.  For now they apply to all users.
4981                if (permissionsState.grantInstallPermission(bp) !=
4982                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4983                    scheduleWriteSettingsLocked();
4984                }
4985                return;
4986            }
4987
4988            final PackageSetting ps = mSettings.mPackages.get(packageName);
4989            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4990                throw new SecurityException("Cannot grant non-ephemeral permission"
4991                        + name + " for package " + packageName);
4992            }
4993
4994            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4995                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4996                return;
4997            }
4998
4999            final int result = permissionsState.grantRuntimePermission(bp, userId);
5000            switch (result) {
5001                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5002                    return;
5003                }
5004
5005                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5006                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5007                    mHandler.post(new Runnable() {
5008                        @Override
5009                        public void run() {
5010                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5011                        }
5012                    });
5013                }
5014                break;
5015            }
5016
5017            if (bp.isRuntime()) {
5018                logPermissionGranted(mContext, name, packageName);
5019            }
5020
5021            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5022
5023            // Not critical if that is lost - app has to request again.
5024            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5025        }
5026
5027        // Only need to do this if user is initialized. Otherwise it's a new user
5028        // and there are no processes running as the user yet and there's no need
5029        // to make an expensive call to remount processes for the changed permissions.
5030        if (READ_EXTERNAL_STORAGE.equals(name)
5031                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5032            final long token = Binder.clearCallingIdentity();
5033            try {
5034                if (sUserManager.isInitialized(userId)) {
5035                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5036                            StorageManagerInternal.class);
5037                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5038                }
5039            } finally {
5040                Binder.restoreCallingIdentity(token);
5041            }
5042        }
5043    }
5044
5045    @Override
5046    public void revokeRuntimePermission(String packageName, String name, int userId) {
5047        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5048    }
5049
5050    private void revokeRuntimePermission(String packageName, String name, int userId,
5051            boolean overridePolicy) {
5052        if (!sUserManager.exists(userId)) {
5053            Log.e(TAG, "No such user:" + userId);
5054            return;
5055        }
5056
5057        mContext.enforceCallingOrSelfPermission(
5058                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5059                "revokeRuntimePermission");
5060
5061        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5062                true /* requireFullPermission */, true /* checkShell */,
5063                "revokeRuntimePermission");
5064
5065        final int appId;
5066
5067        synchronized (mPackages) {
5068            final PackageParser.Package pkg = mPackages.get(packageName);
5069            if (pkg == null) {
5070                throw new IllegalArgumentException("Unknown package: " + packageName);
5071            }
5072
5073            final BasePermission bp = mSettings.mPermissions.get(name);
5074            if (bp == null) {
5075                throw new IllegalArgumentException("Unknown permission: " + name);
5076            }
5077
5078            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5079
5080            // If a permission review is required for legacy apps we represent
5081            // their permissions as always granted runtime ones since we need
5082            // to keep the review required permission flag per user while an
5083            // install permission's state is shared across all users.
5084            if (mPermissionReviewRequired
5085                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5086                    && bp.isRuntime()) {
5087                return;
5088            }
5089
5090            SettingBase sb = (SettingBase) pkg.mExtras;
5091            if (sb == null) {
5092                throw new IllegalArgumentException("Unknown package: " + packageName);
5093            }
5094
5095            final PermissionsState permissionsState = sb.getPermissionsState();
5096
5097            final int flags = permissionsState.getPermissionFlags(name, userId);
5098            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5099                throw new SecurityException("Cannot revoke system fixed permission "
5100                        + name + " for package " + packageName);
5101            }
5102            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5103                throw new SecurityException("Cannot revoke policy fixed permission "
5104                        + name + " for package " + packageName);
5105            }
5106
5107            if (bp.isDevelopment()) {
5108                // Development permissions must be handled specially, since they are not
5109                // normal runtime permissions.  For now they apply to all users.
5110                if (permissionsState.revokeInstallPermission(bp) !=
5111                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5112                    scheduleWriteSettingsLocked();
5113                }
5114                return;
5115            }
5116
5117            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5118                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5119                return;
5120            }
5121
5122            if (bp.isRuntime()) {
5123                logPermissionRevoked(mContext, name, packageName);
5124            }
5125
5126            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5127
5128            // Critical, after this call app should never have the permission.
5129            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5130
5131            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5132        }
5133
5134        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5135    }
5136
5137    /**
5138     * Get the first event id for the permission.
5139     *
5140     * <p>There are four events for each permission: <ul>
5141     *     <li>Request permission: first id + 0</li>
5142     *     <li>Grant permission: first id + 1</li>
5143     *     <li>Request for permission denied: first id + 2</li>
5144     *     <li>Revoke permission: first id + 3</li>
5145     * </ul></p>
5146     *
5147     * @param name name of the permission
5148     *
5149     * @return The first event id for the permission
5150     */
5151    private static int getBaseEventId(@NonNull String name) {
5152        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5153
5154        if (eventIdIndex == -1) {
5155            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5156                    || "user".equals(Build.TYPE)) {
5157                Log.i(TAG, "Unknown permission " + name);
5158
5159                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5160            } else {
5161                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5162                //
5163                // Also update
5164                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5165                // - metrics_constants.proto
5166                throw new IllegalStateException("Unknown permission " + name);
5167            }
5168        }
5169
5170        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5171    }
5172
5173    /**
5174     * Log that a permission was revoked.
5175     *
5176     * @param context Context of the caller
5177     * @param name name of the permission
5178     * @param packageName package permission if for
5179     */
5180    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5181            @NonNull String packageName) {
5182        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5183    }
5184
5185    /**
5186     * Log that a permission request was granted.
5187     *
5188     * @param context Context of the caller
5189     * @param name name of the permission
5190     * @param packageName package permission if for
5191     */
5192    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5193            @NonNull String packageName) {
5194        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5195    }
5196
5197    @Override
5198    public void resetRuntimePermissions() {
5199        mContext.enforceCallingOrSelfPermission(
5200                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5201                "revokeRuntimePermission");
5202
5203        int callingUid = Binder.getCallingUid();
5204        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5205            mContext.enforceCallingOrSelfPermission(
5206                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5207                    "resetRuntimePermissions");
5208        }
5209
5210        synchronized (mPackages) {
5211            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5212            for (int userId : UserManagerService.getInstance().getUserIds()) {
5213                final int packageCount = mPackages.size();
5214                for (int i = 0; i < packageCount; i++) {
5215                    PackageParser.Package pkg = mPackages.valueAt(i);
5216                    if (!(pkg.mExtras instanceof PackageSetting)) {
5217                        continue;
5218                    }
5219                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5220                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5221                }
5222            }
5223        }
5224    }
5225
5226    @Override
5227    public int getPermissionFlags(String name, String packageName, int userId) {
5228        if (!sUserManager.exists(userId)) {
5229            return 0;
5230        }
5231
5232        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5233
5234        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5235                true /* requireFullPermission */, false /* checkShell */,
5236                "getPermissionFlags");
5237
5238        synchronized (mPackages) {
5239            final PackageParser.Package pkg = mPackages.get(packageName);
5240            if (pkg == null) {
5241                return 0;
5242            }
5243
5244            final BasePermission bp = mSettings.mPermissions.get(name);
5245            if (bp == null) {
5246                return 0;
5247            }
5248
5249            SettingBase sb = (SettingBase) pkg.mExtras;
5250            if (sb == null) {
5251                return 0;
5252            }
5253
5254            PermissionsState permissionsState = sb.getPermissionsState();
5255            return permissionsState.getPermissionFlags(name, userId);
5256        }
5257    }
5258
5259    @Override
5260    public void updatePermissionFlags(String name, String packageName, int flagMask,
5261            int flagValues, int userId) {
5262        if (!sUserManager.exists(userId)) {
5263            return;
5264        }
5265
5266        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5267
5268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5269                true /* requireFullPermission */, true /* checkShell */,
5270                "updatePermissionFlags");
5271
5272        // Only the system can change these flags and nothing else.
5273        if (getCallingUid() != Process.SYSTEM_UID) {
5274            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5275            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5276            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5277            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5278            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5279        }
5280
5281        synchronized (mPackages) {
5282            final PackageParser.Package pkg = mPackages.get(packageName);
5283            if (pkg == null) {
5284                throw new IllegalArgumentException("Unknown package: " + packageName);
5285            }
5286
5287            final BasePermission bp = mSettings.mPermissions.get(name);
5288            if (bp == null) {
5289                throw new IllegalArgumentException("Unknown permission: " + name);
5290            }
5291
5292            SettingBase sb = (SettingBase) pkg.mExtras;
5293            if (sb == null) {
5294                throw new IllegalArgumentException("Unknown package: " + packageName);
5295            }
5296
5297            PermissionsState permissionsState = sb.getPermissionsState();
5298
5299            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5300
5301            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5302                // Install and runtime permissions are stored in different places,
5303                // so figure out what permission changed and persist the change.
5304                if (permissionsState.getInstallPermissionState(name) != null) {
5305                    scheduleWriteSettingsLocked();
5306                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5307                        || hadState) {
5308                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5309                }
5310            }
5311        }
5312    }
5313
5314    /**
5315     * Update the permission flags for all packages and runtime permissions of a user in order
5316     * to allow device or profile owner to remove POLICY_FIXED.
5317     */
5318    @Override
5319    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5320        if (!sUserManager.exists(userId)) {
5321            return;
5322        }
5323
5324        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5325
5326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5327                true /* requireFullPermission */, true /* checkShell */,
5328                "updatePermissionFlagsForAllApps");
5329
5330        // Only the system can change system fixed flags.
5331        if (getCallingUid() != Process.SYSTEM_UID) {
5332            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5333            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5334        }
5335
5336        synchronized (mPackages) {
5337            boolean changed = false;
5338            final int packageCount = mPackages.size();
5339            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5340                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5341                SettingBase sb = (SettingBase) pkg.mExtras;
5342                if (sb == null) {
5343                    continue;
5344                }
5345                PermissionsState permissionsState = sb.getPermissionsState();
5346                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5347                        userId, flagMask, flagValues);
5348            }
5349            if (changed) {
5350                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5351            }
5352        }
5353    }
5354
5355    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5356        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5357                != PackageManager.PERMISSION_GRANTED
5358            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5359                != PackageManager.PERMISSION_GRANTED) {
5360            throw new SecurityException(message + " requires "
5361                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5362                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5363        }
5364    }
5365
5366    @Override
5367    public boolean shouldShowRequestPermissionRationale(String permissionName,
5368            String packageName, int userId) {
5369        if (UserHandle.getCallingUserId() != userId) {
5370            mContext.enforceCallingPermission(
5371                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5372                    "canShowRequestPermissionRationale for user " + userId);
5373        }
5374
5375        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5376        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5377            return false;
5378        }
5379
5380        if (checkPermission(permissionName, packageName, userId)
5381                == PackageManager.PERMISSION_GRANTED) {
5382            return false;
5383        }
5384
5385        final int flags;
5386
5387        final long identity = Binder.clearCallingIdentity();
5388        try {
5389            flags = getPermissionFlags(permissionName,
5390                    packageName, userId);
5391        } finally {
5392            Binder.restoreCallingIdentity(identity);
5393        }
5394
5395        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5396                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5397                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5398
5399        if ((flags & fixedFlags) != 0) {
5400            return false;
5401        }
5402
5403        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5404    }
5405
5406    @Override
5407    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5408        mContext.enforceCallingOrSelfPermission(
5409                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5410                "addOnPermissionsChangeListener");
5411
5412        synchronized (mPackages) {
5413            mOnPermissionChangeListeners.addListenerLocked(listener);
5414        }
5415    }
5416
5417    @Override
5418    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5419        synchronized (mPackages) {
5420            mOnPermissionChangeListeners.removeListenerLocked(listener);
5421        }
5422    }
5423
5424    @Override
5425    public boolean isProtectedBroadcast(String actionName) {
5426        synchronized (mPackages) {
5427            if (mProtectedBroadcasts.contains(actionName)) {
5428                return true;
5429            } else if (actionName != null) {
5430                // TODO: remove these terrible hacks
5431                if (actionName.startsWith("android.net.netmon.lingerExpired")
5432                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5433                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5434                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5435                    return true;
5436                }
5437            }
5438        }
5439        return false;
5440    }
5441
5442    @Override
5443    public int checkSignatures(String pkg1, String pkg2) {
5444        synchronized (mPackages) {
5445            final PackageParser.Package p1 = mPackages.get(pkg1);
5446            final PackageParser.Package p2 = mPackages.get(pkg2);
5447            if (p1 == null || p1.mExtras == null
5448                    || p2 == null || p2.mExtras == null) {
5449                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5450            }
5451            return compareSignatures(p1.mSignatures, p2.mSignatures);
5452        }
5453    }
5454
5455    @Override
5456    public int checkUidSignatures(int uid1, int uid2) {
5457        // Map to base uids.
5458        uid1 = UserHandle.getAppId(uid1);
5459        uid2 = UserHandle.getAppId(uid2);
5460        // reader
5461        synchronized (mPackages) {
5462            Signature[] s1;
5463            Signature[] s2;
5464            Object obj = mSettings.getUserIdLPr(uid1);
5465            if (obj != null) {
5466                if (obj instanceof SharedUserSetting) {
5467                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5468                } else if (obj instanceof PackageSetting) {
5469                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5470                } else {
5471                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5472                }
5473            } else {
5474                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5475            }
5476            obj = mSettings.getUserIdLPr(uid2);
5477            if (obj != null) {
5478                if (obj instanceof SharedUserSetting) {
5479                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5480                } else if (obj instanceof PackageSetting) {
5481                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5482                } else {
5483                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5484                }
5485            } else {
5486                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5487            }
5488            return compareSignatures(s1, s2);
5489        }
5490    }
5491
5492    /**
5493     * This method should typically only be used when granting or revoking
5494     * permissions, since the app may immediately restart after this call.
5495     * <p>
5496     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5497     * guard your work against the app being relaunched.
5498     */
5499    private void killUid(int appId, int userId, String reason) {
5500        final long identity = Binder.clearCallingIdentity();
5501        try {
5502            IActivityManager am = ActivityManager.getService();
5503            if (am != null) {
5504                try {
5505                    am.killUid(appId, userId, reason);
5506                } catch (RemoteException e) {
5507                    /* ignore - same process */
5508                }
5509            }
5510        } finally {
5511            Binder.restoreCallingIdentity(identity);
5512        }
5513    }
5514
5515    /**
5516     * Compares two sets of signatures. Returns:
5517     * <br />
5518     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5519     * <br />
5520     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5521     * <br />
5522     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5523     * <br />
5524     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5525     * <br />
5526     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5527     */
5528    static int compareSignatures(Signature[] s1, Signature[] s2) {
5529        if (s1 == null) {
5530            return s2 == null
5531                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5532                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5533        }
5534
5535        if (s2 == null) {
5536            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5537        }
5538
5539        if (s1.length != s2.length) {
5540            return PackageManager.SIGNATURE_NO_MATCH;
5541        }
5542
5543        // Since both signature sets are of size 1, we can compare without HashSets.
5544        if (s1.length == 1) {
5545            return s1[0].equals(s2[0]) ?
5546                    PackageManager.SIGNATURE_MATCH :
5547                    PackageManager.SIGNATURE_NO_MATCH;
5548        }
5549
5550        ArraySet<Signature> set1 = new ArraySet<Signature>();
5551        for (Signature sig : s1) {
5552            set1.add(sig);
5553        }
5554        ArraySet<Signature> set2 = new ArraySet<Signature>();
5555        for (Signature sig : s2) {
5556            set2.add(sig);
5557        }
5558        // Make sure s2 contains all signatures in s1.
5559        if (set1.equals(set2)) {
5560            return PackageManager.SIGNATURE_MATCH;
5561        }
5562        return PackageManager.SIGNATURE_NO_MATCH;
5563    }
5564
5565    /**
5566     * If the database version for this type of package (internal storage or
5567     * external storage) is less than the version where package signatures
5568     * were updated, return true.
5569     */
5570    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5571        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5572        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5573    }
5574
5575    /**
5576     * Used for backward compatibility to make sure any packages with
5577     * certificate chains get upgraded to the new style. {@code existingSigs}
5578     * will be in the old format (since they were stored on disk from before the
5579     * system upgrade) and {@code scannedSigs} will be in the newer format.
5580     */
5581    private int compareSignaturesCompat(PackageSignatures existingSigs,
5582            PackageParser.Package scannedPkg) {
5583        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5584            return PackageManager.SIGNATURE_NO_MATCH;
5585        }
5586
5587        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5588        for (Signature sig : existingSigs.mSignatures) {
5589            existingSet.add(sig);
5590        }
5591        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5592        for (Signature sig : scannedPkg.mSignatures) {
5593            try {
5594                Signature[] chainSignatures = sig.getChainSignatures();
5595                for (Signature chainSig : chainSignatures) {
5596                    scannedCompatSet.add(chainSig);
5597                }
5598            } catch (CertificateEncodingException e) {
5599                scannedCompatSet.add(sig);
5600            }
5601        }
5602        /*
5603         * Make sure the expanded scanned set contains all signatures in the
5604         * existing one.
5605         */
5606        if (scannedCompatSet.equals(existingSet)) {
5607            // Migrate the old signatures to the new scheme.
5608            existingSigs.assignSignatures(scannedPkg.mSignatures);
5609            // The new KeySets will be re-added later in the scanning process.
5610            synchronized (mPackages) {
5611                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5612            }
5613            return PackageManager.SIGNATURE_MATCH;
5614        }
5615        return PackageManager.SIGNATURE_NO_MATCH;
5616    }
5617
5618    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5619        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5620        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5621    }
5622
5623    private int compareSignaturesRecover(PackageSignatures existingSigs,
5624            PackageParser.Package scannedPkg) {
5625        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5626            return PackageManager.SIGNATURE_NO_MATCH;
5627        }
5628
5629        String msg = null;
5630        try {
5631            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5632                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5633                        + scannedPkg.packageName);
5634                return PackageManager.SIGNATURE_MATCH;
5635            }
5636        } catch (CertificateException e) {
5637            msg = e.getMessage();
5638        }
5639
5640        logCriticalInfo(Log.INFO,
5641                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5642        return PackageManager.SIGNATURE_NO_MATCH;
5643    }
5644
5645    @Override
5646    public List<String> getAllPackages() {
5647        synchronized (mPackages) {
5648            return new ArrayList<String>(mPackages.keySet());
5649        }
5650    }
5651
5652    @Override
5653    public String[] getPackagesForUid(int uid) {
5654        final int userId = UserHandle.getUserId(uid);
5655        uid = UserHandle.getAppId(uid);
5656        // reader
5657        synchronized (mPackages) {
5658            Object obj = mSettings.getUserIdLPr(uid);
5659            if (obj instanceof SharedUserSetting) {
5660                final SharedUserSetting sus = (SharedUserSetting) obj;
5661                final int N = sus.packages.size();
5662                String[] res = new String[N];
5663                final Iterator<PackageSetting> it = sus.packages.iterator();
5664                int i = 0;
5665                while (it.hasNext()) {
5666                    PackageSetting ps = it.next();
5667                    if (ps.getInstalled(userId)) {
5668                        res[i++] = ps.name;
5669                    } else {
5670                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5671                    }
5672                }
5673                return res;
5674            } else if (obj instanceof PackageSetting) {
5675                final PackageSetting ps = (PackageSetting) obj;
5676                if (ps.getInstalled(userId)) {
5677                    return new String[]{ps.name};
5678                }
5679            }
5680        }
5681        return null;
5682    }
5683
5684    @Override
5685    public String getNameForUid(int uid) {
5686        // reader
5687        synchronized (mPackages) {
5688            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5689            if (obj instanceof SharedUserSetting) {
5690                final SharedUserSetting sus = (SharedUserSetting) obj;
5691                return sus.name + ":" + sus.userId;
5692            } else if (obj instanceof PackageSetting) {
5693                final PackageSetting ps = (PackageSetting) obj;
5694                return ps.name;
5695            }
5696        }
5697        return null;
5698    }
5699
5700    @Override
5701    public int getUidForSharedUser(String sharedUserName) {
5702        if(sharedUserName == null) {
5703            return -1;
5704        }
5705        // reader
5706        synchronized (mPackages) {
5707            SharedUserSetting suid;
5708            try {
5709                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5710                if (suid != null) {
5711                    return suid.userId;
5712                }
5713            } catch (PackageManagerException ignore) {
5714                // can't happen, but, still need to catch it
5715            }
5716            return -1;
5717        }
5718    }
5719
5720    @Override
5721    public int getFlagsForUid(int uid) {
5722        synchronized (mPackages) {
5723            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5724            if (obj instanceof SharedUserSetting) {
5725                final SharedUserSetting sus = (SharedUserSetting) obj;
5726                return sus.pkgFlags;
5727            } else if (obj instanceof PackageSetting) {
5728                final PackageSetting ps = (PackageSetting) obj;
5729                return ps.pkgFlags;
5730            }
5731        }
5732        return 0;
5733    }
5734
5735    @Override
5736    public int getPrivateFlagsForUid(int uid) {
5737        synchronized (mPackages) {
5738            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5739            if (obj instanceof SharedUserSetting) {
5740                final SharedUserSetting sus = (SharedUserSetting) obj;
5741                return sus.pkgPrivateFlags;
5742            } else if (obj instanceof PackageSetting) {
5743                final PackageSetting ps = (PackageSetting) obj;
5744                return ps.pkgPrivateFlags;
5745            }
5746        }
5747        return 0;
5748    }
5749
5750    @Override
5751    public boolean isUidPrivileged(int uid) {
5752        uid = UserHandle.getAppId(uid);
5753        // reader
5754        synchronized (mPackages) {
5755            Object obj = mSettings.getUserIdLPr(uid);
5756            if (obj instanceof SharedUserSetting) {
5757                final SharedUserSetting sus = (SharedUserSetting) obj;
5758                final Iterator<PackageSetting> it = sus.packages.iterator();
5759                while (it.hasNext()) {
5760                    if (it.next().isPrivileged()) {
5761                        return true;
5762                    }
5763                }
5764            } else if (obj instanceof PackageSetting) {
5765                final PackageSetting ps = (PackageSetting) obj;
5766                return ps.isPrivileged();
5767            }
5768        }
5769        return false;
5770    }
5771
5772    @Override
5773    public String[] getAppOpPermissionPackages(String permissionName) {
5774        synchronized (mPackages) {
5775            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5776            if (pkgs == null) {
5777                return null;
5778            }
5779            return pkgs.toArray(new String[pkgs.size()]);
5780        }
5781    }
5782
5783    @Override
5784    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5785            int flags, int userId) {
5786        return resolveIntentInternal(
5787                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5788    }
5789
5790    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5791            int flags, int userId, boolean resolveForStart) {
5792        try {
5793            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5794
5795            if (!sUserManager.exists(userId)) return null;
5796            final int callingUid = Binder.getCallingUid();
5797            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5798            enforceCrossUserPermission(callingUid, userId,
5799                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5800
5801            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5802            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5803                    flags, userId, resolveForStart);
5804            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5805
5806            final ResolveInfo bestChoice =
5807                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5808            return bestChoice;
5809        } finally {
5810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5811        }
5812    }
5813
5814    @Override
5815    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5816        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5817            throw new SecurityException(
5818                    "findPersistentPreferredActivity can only be run by the system");
5819        }
5820        if (!sUserManager.exists(userId)) {
5821            return null;
5822        }
5823        final int callingUid = Binder.getCallingUid();
5824        intent = updateIntentForResolve(intent);
5825        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5826        final int flags = updateFlagsForResolve(
5827                0, userId, intent, callingUid, false /*includeInstantApps*/);
5828        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5829                userId);
5830        synchronized (mPackages) {
5831            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5832                    userId);
5833        }
5834    }
5835
5836    @Override
5837    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5838            IntentFilter filter, int match, ComponentName activity) {
5839        final int userId = UserHandle.getCallingUserId();
5840        if (DEBUG_PREFERRED) {
5841            Log.v(TAG, "setLastChosenActivity intent=" + intent
5842                + " resolvedType=" + resolvedType
5843                + " flags=" + flags
5844                + " filter=" + filter
5845                + " match=" + match
5846                + " activity=" + activity);
5847            filter.dump(new PrintStreamPrinter(System.out), "    ");
5848        }
5849        intent.setComponent(null);
5850        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5851                userId);
5852        // Find any earlier preferred or last chosen entries and nuke them
5853        findPreferredActivity(intent, resolvedType,
5854                flags, query, 0, false, true, false, userId);
5855        // Add the new activity as the last chosen for this filter
5856        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5857                "Setting last chosen");
5858    }
5859
5860    @Override
5861    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5862        final int userId = UserHandle.getCallingUserId();
5863        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5864        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5865                userId);
5866        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5867                false, false, false, userId);
5868    }
5869
5870    /**
5871     * Returns whether or not instant apps have been disabled remotely.
5872     */
5873    private boolean isEphemeralDisabled() {
5874        return mEphemeralAppsDisabled;
5875    }
5876
5877    private boolean isInstantAppAllowed(
5878            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5879            boolean skipPackageCheck) {
5880        if (mInstantAppResolverConnection == null) {
5881            return false;
5882        }
5883        if (mInstantAppInstallerActivity == null) {
5884            return false;
5885        }
5886        if (intent.getComponent() != null) {
5887            return false;
5888        }
5889        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5890            return false;
5891        }
5892        if (!skipPackageCheck && intent.getPackage() != null) {
5893            return false;
5894        }
5895        final boolean isWebUri = hasWebURI(intent);
5896        if (!isWebUri || intent.getData().getHost() == null) {
5897            return false;
5898        }
5899        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5900        // Or if there's already an ephemeral app installed that handles the action
5901        synchronized (mPackages) {
5902            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5903            for (int n = 0; n < count; n++) {
5904                final ResolveInfo info = resolvedActivities.get(n);
5905                final String packageName = info.activityInfo.packageName;
5906                final PackageSetting ps = mSettings.mPackages.get(packageName);
5907                if (ps != null) {
5908                    // only check domain verification status if the app is not a browser
5909                    if (!info.handleAllWebDataURI) {
5910                        // Try to get the status from User settings first
5911                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5912                        final int status = (int) (packedStatus >> 32);
5913                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5914                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5915                            if (DEBUG_EPHEMERAL) {
5916                                Slog.v(TAG, "DENY instant app;"
5917                                    + " pkg: " + packageName + ", status: " + status);
5918                            }
5919                            return false;
5920                        }
5921                    }
5922                    if (ps.getInstantApp(userId)) {
5923                        if (DEBUG_EPHEMERAL) {
5924                            Slog.v(TAG, "DENY instant app installed;"
5925                                    + " pkg: " + packageName);
5926                        }
5927                        return false;
5928                    }
5929                }
5930            }
5931        }
5932        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5933        return true;
5934    }
5935
5936    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5937            Intent origIntent, String resolvedType, String callingPackage,
5938            Bundle verificationBundle, int userId) {
5939        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5940                new InstantAppRequest(responseObj, origIntent, resolvedType,
5941                        callingPackage, userId, verificationBundle));
5942        mHandler.sendMessage(msg);
5943    }
5944
5945    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5946            int flags, List<ResolveInfo> query, int userId) {
5947        if (query != null) {
5948            final int N = query.size();
5949            if (N == 1) {
5950                return query.get(0);
5951            } else if (N > 1) {
5952                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5953                // If there is more than one activity with the same priority,
5954                // then let the user decide between them.
5955                ResolveInfo r0 = query.get(0);
5956                ResolveInfo r1 = query.get(1);
5957                if (DEBUG_INTENT_MATCHING || debug) {
5958                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5959                            + r1.activityInfo.name + "=" + r1.priority);
5960                }
5961                // If the first activity has a higher priority, or a different
5962                // default, then it is always desirable to pick it.
5963                if (r0.priority != r1.priority
5964                        || r0.preferredOrder != r1.preferredOrder
5965                        || r0.isDefault != r1.isDefault) {
5966                    return query.get(0);
5967                }
5968                // If we have saved a preference for a preferred activity for
5969                // this Intent, use that.
5970                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5971                        flags, query, r0.priority, true, false, debug, userId);
5972                if (ri != null) {
5973                    return ri;
5974                }
5975                // If we have an ephemeral app, use it
5976                for (int i = 0; i < N; i++) {
5977                    ri = query.get(i);
5978                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5979                        final String packageName = ri.activityInfo.packageName;
5980                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5981                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5982                        final int status = (int)(packedStatus >> 32);
5983                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5984                            return ri;
5985                        }
5986                    }
5987                }
5988                ri = new ResolveInfo(mResolveInfo);
5989                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5990                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5991                // If all of the options come from the same package, show the application's
5992                // label and icon instead of the generic resolver's.
5993                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5994                // and then throw away the ResolveInfo itself, meaning that the caller loses
5995                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5996                // a fallback for this case; we only set the target package's resources on
5997                // the ResolveInfo, not the ActivityInfo.
5998                final String intentPackage = intent.getPackage();
5999                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6000                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6001                    ri.resolvePackageName = intentPackage;
6002                    if (userNeedsBadging(userId)) {
6003                        ri.noResourceId = true;
6004                    } else {
6005                        ri.icon = appi.icon;
6006                    }
6007                    ri.iconResourceId = appi.icon;
6008                    ri.labelRes = appi.labelRes;
6009                }
6010                ri.activityInfo.applicationInfo = new ApplicationInfo(
6011                        ri.activityInfo.applicationInfo);
6012                if (userId != 0) {
6013                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6014                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6015                }
6016                // Make sure that the resolver is displayable in car mode
6017                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6018                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6019                return ri;
6020            }
6021        }
6022        return null;
6023    }
6024
6025    /**
6026     * Return true if the given list is not empty and all of its contents have
6027     * an activityInfo with the given package name.
6028     */
6029    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6030        if (ArrayUtils.isEmpty(list)) {
6031            return false;
6032        }
6033        for (int i = 0, N = list.size(); i < N; i++) {
6034            final ResolveInfo ri = list.get(i);
6035            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6036            if (ai == null || !packageName.equals(ai.packageName)) {
6037                return false;
6038            }
6039        }
6040        return true;
6041    }
6042
6043    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6044            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6045        final int N = query.size();
6046        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6047                .get(userId);
6048        // Get the list of persistent preferred activities that handle the intent
6049        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6050        List<PersistentPreferredActivity> pprefs = ppir != null
6051                ? ppir.queryIntent(intent, resolvedType,
6052                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6053                        userId)
6054                : null;
6055        if (pprefs != null && pprefs.size() > 0) {
6056            final int M = pprefs.size();
6057            for (int i=0; i<M; i++) {
6058                final PersistentPreferredActivity ppa = pprefs.get(i);
6059                if (DEBUG_PREFERRED || debug) {
6060                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6061                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6062                            + "\n  component=" + ppa.mComponent);
6063                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6064                }
6065                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6066                        flags | MATCH_DISABLED_COMPONENTS, userId);
6067                if (DEBUG_PREFERRED || debug) {
6068                    Slog.v(TAG, "Found persistent preferred activity:");
6069                    if (ai != null) {
6070                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6071                    } else {
6072                        Slog.v(TAG, "  null");
6073                    }
6074                }
6075                if (ai == null) {
6076                    // This previously registered persistent preferred activity
6077                    // component is no longer known. Ignore it and do NOT remove it.
6078                    continue;
6079                }
6080                for (int j=0; j<N; j++) {
6081                    final ResolveInfo ri = query.get(j);
6082                    if (!ri.activityInfo.applicationInfo.packageName
6083                            .equals(ai.applicationInfo.packageName)) {
6084                        continue;
6085                    }
6086                    if (!ri.activityInfo.name.equals(ai.name)) {
6087                        continue;
6088                    }
6089                    //  Found a persistent preference that can handle the intent.
6090                    if (DEBUG_PREFERRED || debug) {
6091                        Slog.v(TAG, "Returning persistent preferred activity: " +
6092                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6093                    }
6094                    return ri;
6095                }
6096            }
6097        }
6098        return null;
6099    }
6100
6101    // TODO: handle preferred activities missing while user has amnesia
6102    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6103            List<ResolveInfo> query, int priority, boolean always,
6104            boolean removeMatches, boolean debug, int userId) {
6105        if (!sUserManager.exists(userId)) return null;
6106        final int callingUid = Binder.getCallingUid();
6107        flags = updateFlagsForResolve(
6108                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6109        intent = updateIntentForResolve(intent);
6110        // writer
6111        synchronized (mPackages) {
6112            // Try to find a matching persistent preferred activity.
6113            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6114                    debug, userId);
6115
6116            // If a persistent preferred activity matched, use it.
6117            if (pri != null) {
6118                return pri;
6119            }
6120
6121            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6122            // Get the list of preferred activities that handle the intent
6123            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6124            List<PreferredActivity> prefs = pir != null
6125                    ? pir.queryIntent(intent, resolvedType,
6126                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6127                            userId)
6128                    : null;
6129            if (prefs != null && prefs.size() > 0) {
6130                boolean changed = false;
6131                try {
6132                    // First figure out how good the original match set is.
6133                    // We will only allow preferred activities that came
6134                    // from the same match quality.
6135                    int match = 0;
6136
6137                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6138
6139                    final int N = query.size();
6140                    for (int j=0; j<N; j++) {
6141                        final ResolveInfo ri = query.get(j);
6142                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6143                                + ": 0x" + Integer.toHexString(match));
6144                        if (ri.match > match) {
6145                            match = ri.match;
6146                        }
6147                    }
6148
6149                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6150                            + Integer.toHexString(match));
6151
6152                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6153                    final int M = prefs.size();
6154                    for (int i=0; i<M; i++) {
6155                        final PreferredActivity pa = prefs.get(i);
6156                        if (DEBUG_PREFERRED || debug) {
6157                            Slog.v(TAG, "Checking PreferredActivity ds="
6158                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6159                                    + "\n  component=" + pa.mPref.mComponent);
6160                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6161                        }
6162                        if (pa.mPref.mMatch != match) {
6163                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6164                                    + Integer.toHexString(pa.mPref.mMatch));
6165                            continue;
6166                        }
6167                        // If it's not an "always" type preferred activity and that's what we're
6168                        // looking for, skip it.
6169                        if (always && !pa.mPref.mAlways) {
6170                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6171                            continue;
6172                        }
6173                        final ActivityInfo ai = getActivityInfo(
6174                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6175                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6176                                userId);
6177                        if (DEBUG_PREFERRED || debug) {
6178                            Slog.v(TAG, "Found preferred activity:");
6179                            if (ai != null) {
6180                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6181                            } else {
6182                                Slog.v(TAG, "  null");
6183                            }
6184                        }
6185                        if (ai == null) {
6186                            // This previously registered preferred activity
6187                            // component is no longer known.  Most likely an update
6188                            // to the app was installed and in the new version this
6189                            // component no longer exists.  Clean it up by removing
6190                            // it from the preferred activities list, and skip it.
6191                            Slog.w(TAG, "Removing dangling preferred activity: "
6192                                    + pa.mPref.mComponent);
6193                            pir.removeFilter(pa);
6194                            changed = true;
6195                            continue;
6196                        }
6197                        for (int j=0; j<N; j++) {
6198                            final ResolveInfo ri = query.get(j);
6199                            if (!ri.activityInfo.applicationInfo.packageName
6200                                    .equals(ai.applicationInfo.packageName)) {
6201                                continue;
6202                            }
6203                            if (!ri.activityInfo.name.equals(ai.name)) {
6204                                continue;
6205                            }
6206
6207                            if (removeMatches) {
6208                                pir.removeFilter(pa);
6209                                changed = true;
6210                                if (DEBUG_PREFERRED) {
6211                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6212                                }
6213                                break;
6214                            }
6215
6216                            // Okay we found a previously set preferred or last chosen app.
6217                            // If the result set is different from when this
6218                            // was created, we need to clear it and re-ask the
6219                            // user their preference, if we're looking for an "always" type entry.
6220                            if (always && !pa.mPref.sameSet(query)) {
6221                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6222                                        + intent + " type " + resolvedType);
6223                                if (DEBUG_PREFERRED) {
6224                                    Slog.v(TAG, "Removing preferred activity since set changed "
6225                                            + pa.mPref.mComponent);
6226                                }
6227                                pir.removeFilter(pa);
6228                                // Re-add the filter as a "last chosen" entry (!always)
6229                                PreferredActivity lastChosen = new PreferredActivity(
6230                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6231                                pir.addFilter(lastChosen);
6232                                changed = true;
6233                                return null;
6234                            }
6235
6236                            // Yay! Either the set matched or we're looking for the last chosen
6237                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6238                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6239                            return ri;
6240                        }
6241                    }
6242                } finally {
6243                    if (changed) {
6244                        if (DEBUG_PREFERRED) {
6245                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6246                        }
6247                        scheduleWritePackageRestrictionsLocked(userId);
6248                    }
6249                }
6250            }
6251        }
6252        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6253        return null;
6254    }
6255
6256    /*
6257     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6258     */
6259    @Override
6260    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6261            int targetUserId) {
6262        mContext.enforceCallingOrSelfPermission(
6263                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6264        List<CrossProfileIntentFilter> matches =
6265                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6266        if (matches != null) {
6267            int size = matches.size();
6268            for (int i = 0; i < size; i++) {
6269                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6270            }
6271        }
6272        if (hasWebURI(intent)) {
6273            // cross-profile app linking works only towards the parent.
6274            final int callingUid = Binder.getCallingUid();
6275            final UserInfo parent = getProfileParent(sourceUserId);
6276            synchronized(mPackages) {
6277                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6278                        false /*includeInstantApps*/);
6279                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6280                        intent, resolvedType, flags, sourceUserId, parent.id);
6281                return xpDomainInfo != null;
6282            }
6283        }
6284        return false;
6285    }
6286
6287    private UserInfo getProfileParent(int userId) {
6288        final long identity = Binder.clearCallingIdentity();
6289        try {
6290            return sUserManager.getProfileParent(userId);
6291        } finally {
6292            Binder.restoreCallingIdentity(identity);
6293        }
6294    }
6295
6296    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6297            String resolvedType, int userId) {
6298        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6299        if (resolver != null) {
6300            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6301        }
6302        return null;
6303    }
6304
6305    @Override
6306    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6307            String resolvedType, int flags, int userId) {
6308        try {
6309            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6310
6311            return new ParceledListSlice<>(
6312                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6313        } finally {
6314            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6315        }
6316    }
6317
6318    /**
6319     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6320     * instant, returns {@code null}.
6321     */
6322    private String getInstantAppPackageName(int callingUid) {
6323        // If the caller is an isolated app use the owner's uid for the lookup.
6324        if (Process.isIsolated(callingUid)) {
6325            callingUid = mIsolatedOwners.get(callingUid);
6326        }
6327        final int appId = UserHandle.getAppId(callingUid);
6328        synchronized (mPackages) {
6329            final Object obj = mSettings.getUserIdLPr(appId);
6330            if (obj instanceof PackageSetting) {
6331                final PackageSetting ps = (PackageSetting) obj;
6332                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6333                return isInstantApp ? ps.pkg.packageName : null;
6334            }
6335        }
6336        return null;
6337    }
6338
6339    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6340            String resolvedType, int flags, int userId) {
6341        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6342    }
6343
6344    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6345            String resolvedType, int flags, int userId, boolean resolveForStart) {
6346        if (!sUserManager.exists(userId)) return Collections.emptyList();
6347        final int callingUid = Binder.getCallingUid();
6348        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6349        enforceCrossUserPermission(callingUid, userId,
6350                false /* requireFullPermission */, false /* checkShell */,
6351                "query intent activities");
6352        final String pkgName = intent.getPackage();
6353        ComponentName comp = intent.getComponent();
6354        if (comp == null) {
6355            if (intent.getSelector() != null) {
6356                intent = intent.getSelector();
6357                comp = intent.getComponent();
6358            }
6359        }
6360
6361        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
6362                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6363        if (comp != null) {
6364            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6365            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6366            if (ai != null) {
6367                // When specifying an explicit component, we prevent the activity from being
6368                // used when either 1) the calling package is normal and the activity is within
6369                // an ephemeral application or 2) the calling package is ephemeral and the
6370                // activity is not visible to ephemeral applications.
6371                final boolean matchInstantApp =
6372                        (flags & PackageManager.MATCH_INSTANT) != 0;
6373                final boolean matchVisibleToInstantAppOnly =
6374                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6375                final boolean matchExplicitlyVisibleOnly =
6376                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6377                final boolean isCallerInstantApp =
6378                        instantAppPkgName != null;
6379                final boolean isTargetSameInstantApp =
6380                        comp.getPackageName().equals(instantAppPkgName);
6381                final boolean isTargetInstantApp =
6382                        (ai.applicationInfo.privateFlags
6383                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6384                final boolean isTargetVisibleToInstantApp =
6385                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6386                final boolean isTargetExplicitlyVisibleToInstantApp =
6387                        isTargetVisibleToInstantApp
6388                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6389                final boolean isTargetHiddenFromInstantApp =
6390                        !isTargetVisibleToInstantApp
6391                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6392                final boolean blockResolution =
6393                        !isTargetSameInstantApp
6394                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6395                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6396                                        && isTargetHiddenFromInstantApp));
6397                if (!blockResolution) {
6398                    final ResolveInfo ri = new ResolveInfo();
6399                    ri.activityInfo = ai;
6400                    list.add(ri);
6401                }
6402            }
6403            return applyPostResolutionFilter(list, instantAppPkgName);
6404        }
6405
6406        // reader
6407        boolean sortResult = false;
6408        boolean addEphemeral = false;
6409        List<ResolveInfo> result;
6410        final boolean ephemeralDisabled = isEphemeralDisabled();
6411        synchronized (mPackages) {
6412            if (pkgName == null) {
6413                List<CrossProfileIntentFilter> matchingFilters =
6414                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6415                // Check for results that need to skip the current profile.
6416                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6417                        resolvedType, flags, userId);
6418                if (xpResolveInfo != null) {
6419                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6420                    xpResult.add(xpResolveInfo);
6421                    return applyPostResolutionFilter(
6422                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6423                }
6424
6425                // Check for results in the current profile.
6426                result = filterIfNotSystemUser(mActivities.queryIntent(
6427                        intent, resolvedType, flags, userId), userId);
6428                addEphemeral = !ephemeralDisabled
6429                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6430                // Check for cross profile results.
6431                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6432                xpResolveInfo = queryCrossProfileIntents(
6433                        matchingFilters, intent, resolvedType, flags, userId,
6434                        hasNonNegativePriorityResult);
6435                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6436                    boolean isVisibleToUser = filterIfNotSystemUser(
6437                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6438                    if (isVisibleToUser) {
6439                        result.add(xpResolveInfo);
6440                        sortResult = true;
6441                    }
6442                }
6443                if (hasWebURI(intent)) {
6444                    CrossProfileDomainInfo xpDomainInfo = null;
6445                    final UserInfo parent = getProfileParent(userId);
6446                    if (parent != null) {
6447                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6448                                flags, userId, parent.id);
6449                    }
6450                    if (xpDomainInfo != null) {
6451                        if (xpResolveInfo != null) {
6452                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6453                            // in the result.
6454                            result.remove(xpResolveInfo);
6455                        }
6456                        if (result.size() == 0 && !addEphemeral) {
6457                            // No result in current profile, but found candidate in parent user.
6458                            // And we are not going to add emphemeral app, so we can return the
6459                            // result straight away.
6460                            result.add(xpDomainInfo.resolveInfo);
6461                            return applyPostResolutionFilter(result, instantAppPkgName);
6462                        }
6463                    } else if (result.size() <= 1 && !addEphemeral) {
6464                        // No result in parent user and <= 1 result in current profile, and we
6465                        // are not going to add emphemeral app, so we can return the result without
6466                        // further processing.
6467                        return applyPostResolutionFilter(result, instantAppPkgName);
6468                    }
6469                    // We have more than one candidate (combining results from current and parent
6470                    // profile), so we need filtering and sorting.
6471                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6472                            intent, flags, result, xpDomainInfo, userId);
6473                    sortResult = true;
6474                }
6475            } else {
6476                final PackageParser.Package pkg = mPackages.get(pkgName);
6477                result = null;
6478                if (pkg != null) {
6479                    result = filterIfNotSystemUser(
6480                            mActivities.queryIntentForPackage(
6481                                    intent, resolvedType, flags, pkg.activities, userId),
6482                            userId);
6483                }
6484                if (result == null || result.size() == 0) {
6485                    // the caller wants to resolve for a particular package; however, there
6486                    // were no installed results, so, try to find an ephemeral result
6487                    addEphemeral = !ephemeralDisabled
6488                            && isInstantAppAllowed(
6489                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6490                    if (result == null) {
6491                        result = new ArrayList<>();
6492                    }
6493                }
6494            }
6495        }
6496        if (addEphemeral) {
6497            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6498        }
6499        if (sortResult) {
6500            Collections.sort(result, mResolvePrioritySorter);
6501        }
6502        return applyPostResolutionFilter(result, instantAppPkgName);
6503    }
6504
6505    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6506            String resolvedType, int flags, int userId) {
6507        // first, check to see if we've got an instant app already installed
6508        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6509        ResolveInfo localInstantApp = null;
6510        boolean blockResolution = false;
6511        if (!alreadyResolvedLocally) {
6512            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6513                    flags
6514                        | PackageManager.GET_RESOLVED_FILTER
6515                        | PackageManager.MATCH_INSTANT
6516                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6517                    userId);
6518            for (int i = instantApps.size() - 1; i >= 0; --i) {
6519                final ResolveInfo info = instantApps.get(i);
6520                final String packageName = info.activityInfo.packageName;
6521                final PackageSetting ps = mSettings.mPackages.get(packageName);
6522                if (ps.getInstantApp(userId)) {
6523                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6524                    final int status = (int)(packedStatus >> 32);
6525                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6526                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6527                        // there's a local instant application installed, but, the user has
6528                        // chosen to never use it; skip resolution and don't acknowledge
6529                        // an instant application is even available
6530                        if (DEBUG_EPHEMERAL) {
6531                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6532                        }
6533                        blockResolution = true;
6534                        break;
6535                    } else {
6536                        // we have a locally installed instant application; skip resolution
6537                        // but acknowledge there's an instant application available
6538                        if (DEBUG_EPHEMERAL) {
6539                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6540                        }
6541                        localInstantApp = info;
6542                        break;
6543                    }
6544                }
6545            }
6546        }
6547        // no app installed, let's see if one's available
6548        AuxiliaryResolveInfo auxiliaryResponse = null;
6549        if (!blockResolution) {
6550            if (localInstantApp == null) {
6551                // we don't have an instant app locally, resolve externally
6552                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6553                final InstantAppRequest requestObject = new InstantAppRequest(
6554                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6555                        null /*callingPackage*/, userId, null /*verificationBundle*/);
6556                auxiliaryResponse =
6557                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6558                                mContext, mInstantAppResolverConnection, requestObject);
6559                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6560            } else {
6561                // we have an instant application locally, but, we can't admit that since
6562                // callers shouldn't be able to determine prior browsing. create a dummy
6563                // auxiliary response so the downstream code behaves as if there's an
6564                // instant application available externally. when it comes time to start
6565                // the instant application, we'll do the right thing.
6566                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6567                auxiliaryResponse = new AuxiliaryResolveInfo(
6568                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
6569            }
6570        }
6571        if (auxiliaryResponse != null) {
6572            if (DEBUG_EPHEMERAL) {
6573                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6574            }
6575            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6576            final PackageSetting ps =
6577                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6578            if (ps != null) {
6579                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6580                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6581                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6582                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6583                // make sure this resolver is the default
6584                ephemeralInstaller.isDefault = true;
6585                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6586                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6587                // add a non-generic filter
6588                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6589                ephemeralInstaller.filter.addDataPath(
6590                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6591                ephemeralInstaller.isInstantAppAvailable = true;
6592                result.add(ephemeralInstaller);
6593            }
6594        }
6595        return result;
6596    }
6597
6598    private static class CrossProfileDomainInfo {
6599        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6600        ResolveInfo resolveInfo;
6601        /* Best domain verification status of the activities found in the other profile */
6602        int bestDomainVerificationStatus;
6603    }
6604
6605    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6606            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6607        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6608                sourceUserId)) {
6609            return null;
6610        }
6611        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6612                resolvedType, flags, parentUserId);
6613
6614        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6615            return null;
6616        }
6617        CrossProfileDomainInfo result = null;
6618        int size = resultTargetUser.size();
6619        for (int i = 0; i < size; i++) {
6620            ResolveInfo riTargetUser = resultTargetUser.get(i);
6621            // Intent filter verification is only for filters that specify a host. So don't return
6622            // those that handle all web uris.
6623            if (riTargetUser.handleAllWebDataURI) {
6624                continue;
6625            }
6626            String packageName = riTargetUser.activityInfo.packageName;
6627            PackageSetting ps = mSettings.mPackages.get(packageName);
6628            if (ps == null) {
6629                continue;
6630            }
6631            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6632            int status = (int)(verificationState >> 32);
6633            if (result == null) {
6634                result = new CrossProfileDomainInfo();
6635                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6636                        sourceUserId, parentUserId);
6637                result.bestDomainVerificationStatus = status;
6638            } else {
6639                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6640                        result.bestDomainVerificationStatus);
6641            }
6642        }
6643        // Don't consider matches with status NEVER across profiles.
6644        if (result != null && result.bestDomainVerificationStatus
6645                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6646            return null;
6647        }
6648        return result;
6649    }
6650
6651    /**
6652     * Verification statuses are ordered from the worse to the best, except for
6653     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6654     */
6655    private int bestDomainVerificationStatus(int status1, int status2) {
6656        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6657            return status2;
6658        }
6659        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6660            return status1;
6661        }
6662        return (int) MathUtils.max(status1, status2);
6663    }
6664
6665    private boolean isUserEnabled(int userId) {
6666        long callingId = Binder.clearCallingIdentity();
6667        try {
6668            UserInfo userInfo = sUserManager.getUserInfo(userId);
6669            return userInfo != null && userInfo.isEnabled();
6670        } finally {
6671            Binder.restoreCallingIdentity(callingId);
6672        }
6673    }
6674
6675    /**
6676     * Filter out activities with systemUserOnly flag set, when current user is not System.
6677     *
6678     * @return filtered list
6679     */
6680    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6681        if (userId == UserHandle.USER_SYSTEM) {
6682            return resolveInfos;
6683        }
6684        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6685            ResolveInfo info = resolveInfos.get(i);
6686            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6687                resolveInfos.remove(i);
6688            }
6689        }
6690        return resolveInfos;
6691    }
6692
6693    /**
6694     * Filters out ephemeral activities.
6695     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6696     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6697     *
6698     * @param resolveInfos The pre-filtered list of resolved activities
6699     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6700     *          is performed.
6701     * @return A filtered list of resolved activities.
6702     */
6703    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6704            String ephemeralPkgName) {
6705        // TODO: When adding on-demand split support for non-instant apps, remove this check
6706        // and always apply post filtering
6707        if (ephemeralPkgName == null) {
6708            return resolveInfos;
6709        }
6710        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6711            final ResolveInfo info = resolveInfos.get(i);
6712            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6713            // allow activities that are defined in the provided package
6714            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6715                if (info.activityInfo.splitName != null
6716                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6717                                info.activityInfo.splitName)) {
6718                    // requested activity is defined in a split that hasn't been installed yet.
6719                    // add the installer to the resolve list
6720                    if (DEBUG_EPHEMERAL) {
6721                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6722                    }
6723                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6724                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6725                            info.activityInfo.packageName, info.activityInfo.splitName,
6726                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
6727                    // make sure this resolver is the default
6728                    installerInfo.isDefault = true;
6729                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6730                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6731                    // add a non-generic filter
6732                    installerInfo.filter = new IntentFilter();
6733                    // load resources from the correct package
6734                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6735                    resolveInfos.set(i, installerInfo);
6736                }
6737                continue;
6738            }
6739            // allow activities that have been explicitly exposed to ephemeral apps
6740            if (!isEphemeralApp
6741                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6742                continue;
6743            }
6744            resolveInfos.remove(i);
6745        }
6746        return resolveInfos;
6747    }
6748
6749    /**
6750     * @param resolveInfos list of resolve infos in descending priority order
6751     * @return if the list contains a resolve info with non-negative priority
6752     */
6753    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6754        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6755    }
6756
6757    private static boolean hasWebURI(Intent intent) {
6758        if (intent.getData() == null) {
6759            return false;
6760        }
6761        final String scheme = intent.getScheme();
6762        if (TextUtils.isEmpty(scheme)) {
6763            return false;
6764        }
6765        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6766    }
6767
6768    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6769            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6770            int userId) {
6771        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6772
6773        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6774            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6775                    candidates.size());
6776        }
6777
6778        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6779        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6780        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6781        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6782        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6783        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6784
6785        synchronized (mPackages) {
6786            final int count = candidates.size();
6787            // First, try to use linked apps. Partition the candidates into four lists:
6788            // one for the final results, one for the "do not use ever", one for "undefined status"
6789            // and finally one for "browser app type".
6790            for (int n=0; n<count; n++) {
6791                ResolveInfo info = candidates.get(n);
6792                String packageName = info.activityInfo.packageName;
6793                PackageSetting ps = mSettings.mPackages.get(packageName);
6794                if (ps != null) {
6795                    // Add to the special match all list (Browser use case)
6796                    if (info.handleAllWebDataURI) {
6797                        matchAllList.add(info);
6798                        continue;
6799                    }
6800                    // Try to get the status from User settings first
6801                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6802                    int status = (int)(packedStatus >> 32);
6803                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6804                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6805                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6806                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6807                                    + " : linkgen=" + linkGeneration);
6808                        }
6809                        // Use link-enabled generation as preferredOrder, i.e.
6810                        // prefer newly-enabled over earlier-enabled.
6811                        info.preferredOrder = linkGeneration;
6812                        alwaysList.add(info);
6813                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6814                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6815                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6816                        }
6817                        neverList.add(info);
6818                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6819                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6820                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6821                        }
6822                        alwaysAskList.add(info);
6823                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6824                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6825                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6826                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6827                        }
6828                        undefinedList.add(info);
6829                    }
6830                }
6831            }
6832
6833            // We'll want to include browser possibilities in a few cases
6834            boolean includeBrowser = false;
6835
6836            // First try to add the "always" resolution(s) for the current user, if any
6837            if (alwaysList.size() > 0) {
6838                result.addAll(alwaysList);
6839            } else {
6840                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6841                result.addAll(undefinedList);
6842                // Maybe add one for the other profile.
6843                if (xpDomainInfo != null && (
6844                        xpDomainInfo.bestDomainVerificationStatus
6845                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6846                    result.add(xpDomainInfo.resolveInfo);
6847                }
6848                includeBrowser = true;
6849            }
6850
6851            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6852            // If there were 'always' entries their preferred order has been set, so we also
6853            // back that off to make the alternatives equivalent
6854            if (alwaysAskList.size() > 0) {
6855                for (ResolveInfo i : result) {
6856                    i.preferredOrder = 0;
6857                }
6858                result.addAll(alwaysAskList);
6859                includeBrowser = true;
6860            }
6861
6862            if (includeBrowser) {
6863                // Also add browsers (all of them or only the default one)
6864                if (DEBUG_DOMAIN_VERIFICATION) {
6865                    Slog.v(TAG, "   ...including browsers in candidate set");
6866                }
6867                if ((matchFlags & MATCH_ALL) != 0) {
6868                    result.addAll(matchAllList);
6869                } else {
6870                    // Browser/generic handling case.  If there's a default browser, go straight
6871                    // to that (but only if there is no other higher-priority match).
6872                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6873                    int maxMatchPrio = 0;
6874                    ResolveInfo defaultBrowserMatch = null;
6875                    final int numCandidates = matchAllList.size();
6876                    for (int n = 0; n < numCandidates; n++) {
6877                        ResolveInfo info = matchAllList.get(n);
6878                        // track the highest overall match priority...
6879                        if (info.priority > maxMatchPrio) {
6880                            maxMatchPrio = info.priority;
6881                        }
6882                        // ...and the highest-priority default browser match
6883                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6884                            if (defaultBrowserMatch == null
6885                                    || (defaultBrowserMatch.priority < info.priority)) {
6886                                if (debug) {
6887                                    Slog.v(TAG, "Considering default browser match " + info);
6888                                }
6889                                defaultBrowserMatch = info;
6890                            }
6891                        }
6892                    }
6893                    if (defaultBrowserMatch != null
6894                            && defaultBrowserMatch.priority >= maxMatchPrio
6895                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6896                    {
6897                        if (debug) {
6898                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6899                        }
6900                        result.add(defaultBrowserMatch);
6901                    } else {
6902                        result.addAll(matchAllList);
6903                    }
6904                }
6905
6906                // If there is nothing selected, add all candidates and remove the ones that the user
6907                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6908                if (result.size() == 0) {
6909                    result.addAll(candidates);
6910                    result.removeAll(neverList);
6911                }
6912            }
6913        }
6914        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6915            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6916                    result.size());
6917            for (ResolveInfo info : result) {
6918                Slog.v(TAG, "  + " + info.activityInfo);
6919            }
6920        }
6921        return result;
6922    }
6923
6924    // Returns a packed value as a long:
6925    //
6926    // high 'int'-sized word: link status: undefined/ask/never/always.
6927    // low 'int'-sized word: relative priority among 'always' results.
6928    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6929        long result = ps.getDomainVerificationStatusForUser(userId);
6930        // if none available, get the master status
6931        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6932            if (ps.getIntentFilterVerificationInfo() != null) {
6933                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6934            }
6935        }
6936        return result;
6937    }
6938
6939    private ResolveInfo querySkipCurrentProfileIntents(
6940            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6941            int flags, int sourceUserId) {
6942        if (matchingFilters != null) {
6943            int size = matchingFilters.size();
6944            for (int i = 0; i < size; i ++) {
6945                CrossProfileIntentFilter filter = matchingFilters.get(i);
6946                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6947                    // Checking if there are activities in the target user that can handle the
6948                    // intent.
6949                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6950                            resolvedType, flags, sourceUserId);
6951                    if (resolveInfo != null) {
6952                        return resolveInfo;
6953                    }
6954                }
6955            }
6956        }
6957        return null;
6958    }
6959
6960    // Return matching ResolveInfo in target user if any.
6961    private ResolveInfo queryCrossProfileIntents(
6962            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6963            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6964        if (matchingFilters != null) {
6965            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6966            // match the same intent. For performance reasons, it is better not to
6967            // run queryIntent twice for the same userId
6968            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6969            int size = matchingFilters.size();
6970            for (int i = 0; i < size; i++) {
6971                CrossProfileIntentFilter filter = matchingFilters.get(i);
6972                int targetUserId = filter.getTargetUserId();
6973                boolean skipCurrentProfile =
6974                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6975                boolean skipCurrentProfileIfNoMatchFound =
6976                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6977                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6978                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6979                    // Checking if there are activities in the target user that can handle the
6980                    // intent.
6981                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6982                            resolvedType, flags, sourceUserId);
6983                    if (resolveInfo != null) return resolveInfo;
6984                    alreadyTriedUserIds.put(targetUserId, true);
6985                }
6986            }
6987        }
6988        return null;
6989    }
6990
6991    /**
6992     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6993     * will forward the intent to the filter's target user.
6994     * Otherwise, returns null.
6995     */
6996    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6997            String resolvedType, int flags, int sourceUserId) {
6998        int targetUserId = filter.getTargetUserId();
6999        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7000                resolvedType, flags, targetUserId);
7001        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7002            // If all the matches in the target profile are suspended, return null.
7003            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7004                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7005                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7006                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7007                            targetUserId);
7008                }
7009            }
7010        }
7011        return null;
7012    }
7013
7014    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7015            int sourceUserId, int targetUserId) {
7016        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7017        long ident = Binder.clearCallingIdentity();
7018        boolean targetIsProfile;
7019        try {
7020            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7021        } finally {
7022            Binder.restoreCallingIdentity(ident);
7023        }
7024        String className;
7025        if (targetIsProfile) {
7026            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7027        } else {
7028            className = FORWARD_INTENT_TO_PARENT;
7029        }
7030        ComponentName forwardingActivityComponentName = new ComponentName(
7031                mAndroidApplication.packageName, className);
7032        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7033                sourceUserId);
7034        if (!targetIsProfile) {
7035            forwardingActivityInfo.showUserIcon = targetUserId;
7036            forwardingResolveInfo.noResourceId = true;
7037        }
7038        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7039        forwardingResolveInfo.priority = 0;
7040        forwardingResolveInfo.preferredOrder = 0;
7041        forwardingResolveInfo.match = 0;
7042        forwardingResolveInfo.isDefault = true;
7043        forwardingResolveInfo.filter = filter;
7044        forwardingResolveInfo.targetUserId = targetUserId;
7045        return forwardingResolveInfo;
7046    }
7047
7048    @Override
7049    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7050            Intent[] specifics, String[] specificTypes, Intent intent,
7051            String resolvedType, int flags, int userId) {
7052        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7053                specificTypes, intent, resolvedType, flags, userId));
7054    }
7055
7056    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7057            Intent[] specifics, String[] specificTypes, Intent intent,
7058            String resolvedType, int flags, int userId) {
7059        if (!sUserManager.exists(userId)) return Collections.emptyList();
7060        final int callingUid = Binder.getCallingUid();
7061        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7062                false /*includeInstantApps*/);
7063        enforceCrossUserPermission(callingUid, userId,
7064                false /*requireFullPermission*/, false /*checkShell*/,
7065                "query intent activity options");
7066        final String resultsAction = intent.getAction();
7067
7068        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7069                | PackageManager.GET_RESOLVED_FILTER, userId);
7070
7071        if (DEBUG_INTENT_MATCHING) {
7072            Log.v(TAG, "Query " + intent + ": " + results);
7073        }
7074
7075        int specificsPos = 0;
7076        int N;
7077
7078        // todo: note that the algorithm used here is O(N^2).  This
7079        // isn't a problem in our current environment, but if we start running
7080        // into situations where we have more than 5 or 10 matches then this
7081        // should probably be changed to something smarter...
7082
7083        // First we go through and resolve each of the specific items
7084        // that were supplied, taking care of removing any corresponding
7085        // duplicate items in the generic resolve list.
7086        if (specifics != null) {
7087            for (int i=0; i<specifics.length; i++) {
7088                final Intent sintent = specifics[i];
7089                if (sintent == null) {
7090                    continue;
7091                }
7092
7093                if (DEBUG_INTENT_MATCHING) {
7094                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7095                }
7096
7097                String action = sintent.getAction();
7098                if (resultsAction != null && resultsAction.equals(action)) {
7099                    // If this action was explicitly requested, then don't
7100                    // remove things that have it.
7101                    action = null;
7102                }
7103
7104                ResolveInfo ri = null;
7105                ActivityInfo ai = null;
7106
7107                ComponentName comp = sintent.getComponent();
7108                if (comp == null) {
7109                    ri = resolveIntent(
7110                        sintent,
7111                        specificTypes != null ? specificTypes[i] : null,
7112                            flags, userId);
7113                    if (ri == null) {
7114                        continue;
7115                    }
7116                    if (ri == mResolveInfo) {
7117                        // ACK!  Must do something better with this.
7118                    }
7119                    ai = ri.activityInfo;
7120                    comp = new ComponentName(ai.applicationInfo.packageName,
7121                            ai.name);
7122                } else {
7123                    ai = getActivityInfo(comp, flags, userId);
7124                    if (ai == null) {
7125                        continue;
7126                    }
7127                }
7128
7129                // Look for any generic query activities that are duplicates
7130                // of this specific one, and remove them from the results.
7131                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7132                N = results.size();
7133                int j;
7134                for (j=specificsPos; j<N; j++) {
7135                    ResolveInfo sri = results.get(j);
7136                    if ((sri.activityInfo.name.equals(comp.getClassName())
7137                            && sri.activityInfo.applicationInfo.packageName.equals(
7138                                    comp.getPackageName()))
7139                        || (action != null && sri.filter.matchAction(action))) {
7140                        results.remove(j);
7141                        if (DEBUG_INTENT_MATCHING) Log.v(
7142                            TAG, "Removing duplicate item from " + j
7143                            + " due to specific " + specificsPos);
7144                        if (ri == null) {
7145                            ri = sri;
7146                        }
7147                        j--;
7148                        N--;
7149                    }
7150                }
7151
7152                // Add this specific item to its proper place.
7153                if (ri == null) {
7154                    ri = new ResolveInfo();
7155                    ri.activityInfo = ai;
7156                }
7157                results.add(specificsPos, ri);
7158                ri.specificIndex = i;
7159                specificsPos++;
7160            }
7161        }
7162
7163        // Now we go through the remaining generic results and remove any
7164        // duplicate actions that are found here.
7165        N = results.size();
7166        for (int i=specificsPos; i<N-1; i++) {
7167            final ResolveInfo rii = results.get(i);
7168            if (rii.filter == null) {
7169                continue;
7170            }
7171
7172            // Iterate over all of the actions of this result's intent
7173            // filter...  typically this should be just one.
7174            final Iterator<String> it = rii.filter.actionsIterator();
7175            if (it == null) {
7176                continue;
7177            }
7178            while (it.hasNext()) {
7179                final String action = it.next();
7180                if (resultsAction != null && resultsAction.equals(action)) {
7181                    // If this action was explicitly requested, then don't
7182                    // remove things that have it.
7183                    continue;
7184                }
7185                for (int j=i+1; j<N; j++) {
7186                    final ResolveInfo rij = results.get(j);
7187                    if (rij.filter != null && rij.filter.hasAction(action)) {
7188                        results.remove(j);
7189                        if (DEBUG_INTENT_MATCHING) Log.v(
7190                            TAG, "Removing duplicate item from " + j
7191                            + " due to action " + action + " at " + i);
7192                        j--;
7193                        N--;
7194                    }
7195                }
7196            }
7197
7198            // If the caller didn't request filter information, drop it now
7199            // so we don't have to marshall/unmarshall it.
7200            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7201                rii.filter = null;
7202            }
7203        }
7204
7205        // Filter out the caller activity if so requested.
7206        if (caller != null) {
7207            N = results.size();
7208            for (int i=0; i<N; i++) {
7209                ActivityInfo ainfo = results.get(i).activityInfo;
7210                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7211                        && caller.getClassName().equals(ainfo.name)) {
7212                    results.remove(i);
7213                    break;
7214                }
7215            }
7216        }
7217
7218        // If the caller didn't request filter information,
7219        // drop them now so we don't have to
7220        // marshall/unmarshall it.
7221        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7222            N = results.size();
7223            for (int i=0; i<N; i++) {
7224                results.get(i).filter = null;
7225            }
7226        }
7227
7228        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7229        return results;
7230    }
7231
7232    @Override
7233    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7234            String resolvedType, int flags, int userId) {
7235        return new ParceledListSlice<>(
7236                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7237    }
7238
7239    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7240            String resolvedType, int flags, int userId) {
7241        if (!sUserManager.exists(userId)) return Collections.emptyList();
7242        final int callingUid = Binder.getCallingUid();
7243        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7244                false /*includeInstantApps*/);
7245        ComponentName comp = intent.getComponent();
7246        if (comp == null) {
7247            if (intent.getSelector() != null) {
7248                intent = intent.getSelector();
7249                comp = intent.getComponent();
7250            }
7251        }
7252        if (comp != null) {
7253            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7254            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7255            if (ai != null) {
7256                ResolveInfo ri = new ResolveInfo();
7257                ri.activityInfo = ai;
7258                list.add(ri);
7259            }
7260            return list;
7261        }
7262
7263        // reader
7264        synchronized (mPackages) {
7265            String pkgName = intent.getPackage();
7266            if (pkgName == null) {
7267                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7268            }
7269            final PackageParser.Package pkg = mPackages.get(pkgName);
7270            if (pkg != null) {
7271                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7272                        userId);
7273            }
7274            return Collections.emptyList();
7275        }
7276    }
7277
7278    @Override
7279    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7280        final int callingUid = Binder.getCallingUid();
7281        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7282    }
7283
7284    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7285            int userId, int callingUid) {
7286        if (!sUserManager.exists(userId)) return null;
7287        flags = updateFlagsForResolve(
7288                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7289        List<ResolveInfo> query = queryIntentServicesInternal(
7290                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7291        if (query != null) {
7292            if (query.size() >= 1) {
7293                // If there is more than one service with the same priority,
7294                // just arbitrarily pick the first one.
7295                return query.get(0);
7296            }
7297        }
7298        return null;
7299    }
7300
7301    @Override
7302    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7303            String resolvedType, int flags, int userId) {
7304        final int callingUid = Binder.getCallingUid();
7305        return new ParceledListSlice<>(queryIntentServicesInternal(
7306                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7307    }
7308
7309    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7310            String resolvedType, int flags, int userId, int callingUid,
7311            boolean includeInstantApps) {
7312        if (!sUserManager.exists(userId)) return Collections.emptyList();
7313        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7314        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7315        ComponentName comp = intent.getComponent();
7316        if (comp == null) {
7317            if (intent.getSelector() != null) {
7318                intent = intent.getSelector();
7319                comp = intent.getComponent();
7320            }
7321        }
7322        if (comp != null) {
7323            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7324            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7325            if (si != null) {
7326                // When specifying an explicit component, we prevent the service from being
7327                // used when either 1) the service is in an instant application and the
7328                // caller is not the same instant application or 2) the calling package is
7329                // ephemeral and the activity is not visible to ephemeral applications.
7330                final boolean matchInstantApp =
7331                        (flags & PackageManager.MATCH_INSTANT) != 0;
7332                final boolean matchVisibleToInstantAppOnly =
7333                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7334                final boolean isCallerInstantApp =
7335                        instantAppPkgName != null;
7336                final boolean isTargetSameInstantApp =
7337                        comp.getPackageName().equals(instantAppPkgName);
7338                final boolean isTargetInstantApp =
7339                        (si.applicationInfo.privateFlags
7340                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7341                final boolean isTargetHiddenFromInstantApp =
7342                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7343                final boolean blockResolution =
7344                        !isTargetSameInstantApp
7345                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7346                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7347                                        && isTargetHiddenFromInstantApp));
7348                if (!blockResolution) {
7349                    final ResolveInfo ri = new ResolveInfo();
7350                    ri.serviceInfo = si;
7351                    list.add(ri);
7352                }
7353            }
7354            return list;
7355        }
7356
7357        // reader
7358        synchronized (mPackages) {
7359            String pkgName = intent.getPackage();
7360            if (pkgName == null) {
7361                return applyPostServiceResolutionFilter(
7362                        mServices.queryIntent(intent, resolvedType, flags, userId),
7363                        instantAppPkgName);
7364            }
7365            final PackageParser.Package pkg = mPackages.get(pkgName);
7366            if (pkg != null) {
7367                return applyPostServiceResolutionFilter(
7368                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7369                                userId),
7370                        instantAppPkgName);
7371            }
7372            return Collections.emptyList();
7373        }
7374    }
7375
7376    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7377            String instantAppPkgName) {
7378        // TODO: When adding on-demand split support for non-instant apps, remove this check
7379        // and always apply post filtering
7380        if (instantAppPkgName == null) {
7381            return resolveInfos;
7382        }
7383        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7384            final ResolveInfo info = resolveInfos.get(i);
7385            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7386            // allow services that are defined in the provided package
7387            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7388                if (info.serviceInfo.splitName != null
7389                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7390                                info.serviceInfo.splitName)) {
7391                    // requested service is defined in a split that hasn't been installed yet.
7392                    // add the installer to the resolve list
7393                    if (DEBUG_EPHEMERAL) {
7394                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7395                    }
7396                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7397                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7398                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7399                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7400                    // make sure this resolver is the default
7401                    installerInfo.isDefault = true;
7402                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7403                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7404                    // add a non-generic filter
7405                    installerInfo.filter = new IntentFilter();
7406                    // load resources from the correct package
7407                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7408                    resolveInfos.set(i, installerInfo);
7409                }
7410                continue;
7411            }
7412            // allow services that have been explicitly exposed to ephemeral apps
7413            if (!isEphemeralApp
7414                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7415                continue;
7416            }
7417            resolveInfos.remove(i);
7418        }
7419        return resolveInfos;
7420    }
7421
7422    @Override
7423    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7424            String resolvedType, int flags, int userId) {
7425        return new ParceledListSlice<>(
7426                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7427    }
7428
7429    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7430            Intent intent, String resolvedType, int flags, int userId) {
7431        if (!sUserManager.exists(userId)) return Collections.emptyList();
7432        final int callingUid = Binder.getCallingUid();
7433        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7434        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7435                false /*includeInstantApps*/);
7436        ComponentName comp = intent.getComponent();
7437        if (comp == null) {
7438            if (intent.getSelector() != null) {
7439                intent = intent.getSelector();
7440                comp = intent.getComponent();
7441            }
7442        }
7443        if (comp != null) {
7444            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7445            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7446            if (pi != null) {
7447                // When specifying an explicit component, we prevent the provider from being
7448                // used when either 1) the provider is in an instant application and the
7449                // caller is not the same instant application or 2) the calling package is an
7450                // instant application and the provider is not visible to instant applications.
7451                final boolean matchInstantApp =
7452                        (flags & PackageManager.MATCH_INSTANT) != 0;
7453                final boolean matchVisibleToInstantAppOnly =
7454                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7455                final boolean isCallerInstantApp =
7456                        instantAppPkgName != null;
7457                final boolean isTargetSameInstantApp =
7458                        comp.getPackageName().equals(instantAppPkgName);
7459                final boolean isTargetInstantApp =
7460                        (pi.applicationInfo.privateFlags
7461                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7462                final boolean isTargetHiddenFromInstantApp =
7463                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7464                final boolean blockResolution =
7465                        !isTargetSameInstantApp
7466                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7467                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7468                                        && isTargetHiddenFromInstantApp));
7469                if (!blockResolution) {
7470                    final ResolveInfo ri = new ResolveInfo();
7471                    ri.providerInfo = pi;
7472                    list.add(ri);
7473                }
7474            }
7475            return list;
7476        }
7477
7478        // reader
7479        synchronized (mPackages) {
7480            String pkgName = intent.getPackage();
7481            if (pkgName == null) {
7482                return applyPostContentProviderResolutionFilter(
7483                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7484                        instantAppPkgName);
7485            }
7486            final PackageParser.Package pkg = mPackages.get(pkgName);
7487            if (pkg != null) {
7488                return applyPostContentProviderResolutionFilter(
7489                        mProviders.queryIntentForPackage(
7490                        intent, resolvedType, flags, pkg.providers, userId),
7491                        instantAppPkgName);
7492            }
7493            return Collections.emptyList();
7494        }
7495    }
7496
7497    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7498            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7499        // TODO: When adding on-demand split support for non-instant applications, remove
7500        // this check and always apply post filtering
7501        if (instantAppPkgName == null) {
7502            return resolveInfos;
7503        }
7504        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7505            final ResolveInfo info = resolveInfos.get(i);
7506            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7507            // allow providers that are defined in the provided package
7508            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7509                if (info.providerInfo.splitName != null
7510                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7511                                info.providerInfo.splitName)) {
7512                    // requested provider is defined in a split that hasn't been installed yet.
7513                    // add the installer to the resolve list
7514                    if (DEBUG_EPHEMERAL) {
7515                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7516                    }
7517                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7518                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7519                            info.providerInfo.packageName, info.providerInfo.splitName,
7520                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
7521                    // make sure this resolver is the default
7522                    installerInfo.isDefault = true;
7523                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7524                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7525                    // add a non-generic filter
7526                    installerInfo.filter = new IntentFilter();
7527                    // load resources from the correct package
7528                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7529                    resolveInfos.set(i, installerInfo);
7530                }
7531                continue;
7532            }
7533            // allow providers that have been explicitly exposed to instant applications
7534            if (!isEphemeralApp
7535                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7536                continue;
7537            }
7538            resolveInfos.remove(i);
7539        }
7540        return resolveInfos;
7541    }
7542
7543    @Override
7544    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7545        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7546        flags = updateFlagsForPackage(flags, userId, null);
7547        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7548        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7549                true /* requireFullPermission */, false /* checkShell */,
7550                "get installed packages");
7551
7552        // writer
7553        synchronized (mPackages) {
7554            ArrayList<PackageInfo> list;
7555            if (listUninstalled) {
7556                list = new ArrayList<>(mSettings.mPackages.size());
7557                for (PackageSetting ps : mSettings.mPackages.values()) {
7558                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7559                        continue;
7560                    }
7561                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7562                    if (pi != null) {
7563                        list.add(pi);
7564                    }
7565                }
7566            } else {
7567                list = new ArrayList<>(mPackages.size());
7568                for (PackageParser.Package p : mPackages.values()) {
7569                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7570                            Binder.getCallingUid(), userId, flags)) {
7571                        continue;
7572                    }
7573                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7574                            p.mExtras, flags, userId);
7575                    if (pi != null) {
7576                        list.add(pi);
7577                    }
7578                }
7579            }
7580
7581            return new ParceledListSlice<>(list);
7582        }
7583    }
7584
7585    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7586            String[] permissions, boolean[] tmp, int flags, int userId) {
7587        int numMatch = 0;
7588        final PermissionsState permissionsState = ps.getPermissionsState();
7589        for (int i=0; i<permissions.length; i++) {
7590            final String permission = permissions[i];
7591            if (permissionsState.hasPermission(permission, userId)) {
7592                tmp[i] = true;
7593                numMatch++;
7594            } else {
7595                tmp[i] = false;
7596            }
7597        }
7598        if (numMatch == 0) {
7599            return;
7600        }
7601        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7602
7603        // The above might return null in cases of uninstalled apps or install-state
7604        // skew across users/profiles.
7605        if (pi != null) {
7606            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7607                if (numMatch == permissions.length) {
7608                    pi.requestedPermissions = permissions;
7609                } else {
7610                    pi.requestedPermissions = new String[numMatch];
7611                    numMatch = 0;
7612                    for (int i=0; i<permissions.length; i++) {
7613                        if (tmp[i]) {
7614                            pi.requestedPermissions[numMatch] = permissions[i];
7615                            numMatch++;
7616                        }
7617                    }
7618                }
7619            }
7620            list.add(pi);
7621        }
7622    }
7623
7624    @Override
7625    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7626            String[] permissions, int flags, int userId) {
7627        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7628        flags = updateFlagsForPackage(flags, userId, permissions);
7629        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7630                true /* requireFullPermission */, false /* checkShell */,
7631                "get packages holding permissions");
7632        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7633
7634        // writer
7635        synchronized (mPackages) {
7636            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7637            boolean[] tmpBools = new boolean[permissions.length];
7638            if (listUninstalled) {
7639                for (PackageSetting ps : mSettings.mPackages.values()) {
7640                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7641                            userId);
7642                }
7643            } else {
7644                for (PackageParser.Package pkg : mPackages.values()) {
7645                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7646                    if (ps != null) {
7647                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7648                                userId);
7649                    }
7650                }
7651            }
7652
7653            return new ParceledListSlice<PackageInfo>(list);
7654        }
7655    }
7656
7657    @Override
7658    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7659        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7660        flags = updateFlagsForApplication(flags, userId, null);
7661        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7662
7663        // writer
7664        synchronized (mPackages) {
7665            ArrayList<ApplicationInfo> list;
7666            if (listUninstalled) {
7667                list = new ArrayList<>(mSettings.mPackages.size());
7668                for (PackageSetting ps : mSettings.mPackages.values()) {
7669                    ApplicationInfo ai;
7670                    int effectiveFlags = flags;
7671                    if (ps.isSystem()) {
7672                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7673                    }
7674                    if (ps.pkg != null) {
7675                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7676                            continue;
7677                        }
7678                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7679                                ps.readUserState(userId), userId);
7680                        if (ai != null) {
7681                            rebaseEnabledOverlays(ai, userId);
7682                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7683                        }
7684                    } else {
7685                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7686                        // and already converts to externally visible package name
7687                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7688                                Binder.getCallingUid(), effectiveFlags, userId);
7689                    }
7690                    if (ai != null) {
7691                        list.add(ai);
7692                    }
7693                }
7694            } else {
7695                list = new ArrayList<>(mPackages.size());
7696                for (PackageParser.Package p : mPackages.values()) {
7697                    if (p.mExtras != null) {
7698                        PackageSetting ps = (PackageSetting) p.mExtras;
7699                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7700                            continue;
7701                        }
7702                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7703                                ps.readUserState(userId), userId);
7704                        if (ai != null) {
7705                            rebaseEnabledOverlays(ai, userId);
7706                            ai.packageName = resolveExternalPackageNameLPr(p);
7707                            list.add(ai);
7708                        }
7709                    }
7710                }
7711            }
7712
7713            return new ParceledListSlice<>(list);
7714        }
7715    }
7716
7717    @Override
7718    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7719        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7720            return null;
7721        }
7722
7723        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7724                "getEphemeralApplications");
7725        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7726                true /* requireFullPermission */, false /* checkShell */,
7727                "getEphemeralApplications");
7728        synchronized (mPackages) {
7729            List<InstantAppInfo> instantApps = mInstantAppRegistry
7730                    .getInstantAppsLPr(userId);
7731            if (instantApps != null) {
7732                return new ParceledListSlice<>(instantApps);
7733            }
7734        }
7735        return null;
7736    }
7737
7738    @Override
7739    public boolean isInstantApp(String packageName, int userId) {
7740        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7741                true /* requireFullPermission */, false /* checkShell */,
7742                "isInstantApp");
7743        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7744            return false;
7745        }
7746        int uid = Binder.getCallingUid();
7747        if (Process.isIsolated(uid)) {
7748            uid = mIsolatedOwners.get(uid);
7749        }
7750
7751        synchronized (mPackages) {
7752            final PackageSetting ps = mSettings.mPackages.get(packageName);
7753            PackageParser.Package pkg = mPackages.get(packageName);
7754            final boolean returnAllowed =
7755                    ps != null
7756                    && (isCallerSameApp(packageName, uid)
7757                            || mContext.checkCallingOrSelfPermission(
7758                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7759                                            == PERMISSION_GRANTED
7760                            || mInstantAppRegistry.isInstantAccessGranted(
7761                                    userId, UserHandle.getAppId(uid), ps.appId));
7762            if (returnAllowed) {
7763                return ps.getInstantApp(userId);
7764            }
7765        }
7766        return false;
7767    }
7768
7769    @Override
7770    public byte[] getInstantAppCookie(String packageName, int userId) {
7771        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7772            return null;
7773        }
7774
7775        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7776                true /* requireFullPermission */, false /* checkShell */,
7777                "getInstantAppCookie");
7778        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7779            return null;
7780        }
7781        synchronized (mPackages) {
7782            return mInstantAppRegistry.getInstantAppCookieLPw(
7783                    packageName, userId);
7784        }
7785    }
7786
7787    @Override
7788    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7789        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7790            return true;
7791        }
7792
7793        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7794                true /* requireFullPermission */, true /* checkShell */,
7795                "setInstantAppCookie");
7796        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7797            return false;
7798        }
7799        synchronized (mPackages) {
7800            return mInstantAppRegistry.setInstantAppCookieLPw(
7801                    packageName, cookie, userId);
7802        }
7803    }
7804
7805    @Override
7806    public Bitmap getInstantAppIcon(String packageName, int userId) {
7807        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7808            return null;
7809        }
7810
7811        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7812                "getInstantAppIcon");
7813
7814        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7815                true /* requireFullPermission */, false /* checkShell */,
7816                "getInstantAppIcon");
7817
7818        synchronized (mPackages) {
7819            return mInstantAppRegistry.getInstantAppIconLPw(
7820                    packageName, userId);
7821        }
7822    }
7823
7824    private boolean isCallerSameApp(String packageName, int uid) {
7825        PackageParser.Package pkg = mPackages.get(packageName);
7826        return pkg != null
7827                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7828    }
7829
7830    @Override
7831    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7832        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7833    }
7834
7835    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7836        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7837
7838        // reader
7839        synchronized (mPackages) {
7840            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7841            final int userId = UserHandle.getCallingUserId();
7842            while (i.hasNext()) {
7843                final PackageParser.Package p = i.next();
7844                if (p.applicationInfo == null) continue;
7845
7846                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7847                        && !p.applicationInfo.isDirectBootAware();
7848                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7849                        && p.applicationInfo.isDirectBootAware();
7850
7851                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7852                        && (!mSafeMode || isSystemApp(p))
7853                        && (matchesUnaware || matchesAware)) {
7854                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7855                    if (ps != null) {
7856                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7857                                ps.readUserState(userId), userId);
7858                        if (ai != null) {
7859                            rebaseEnabledOverlays(ai, userId);
7860                            finalList.add(ai);
7861                        }
7862                    }
7863                }
7864            }
7865        }
7866
7867        return finalList;
7868    }
7869
7870    @Override
7871    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7872        if (!sUserManager.exists(userId)) return null;
7873        flags = updateFlagsForComponent(flags, userId, name);
7874        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7875        // reader
7876        synchronized (mPackages) {
7877            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7878            PackageSetting ps = provider != null
7879                    ? mSettings.mPackages.get(provider.owner.packageName)
7880                    : null;
7881            if (ps != null) {
7882                final boolean isInstantApp = ps.getInstantApp(userId);
7883                // normal application; filter out instant application provider
7884                if (instantAppPkgName == null && isInstantApp) {
7885                    return null;
7886                }
7887                // instant application; filter out other instant applications
7888                if (instantAppPkgName != null
7889                        && isInstantApp
7890                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7891                    return null;
7892                }
7893                // instant application; filter out non-exposed provider
7894                if (instantAppPkgName != null
7895                        && !isInstantApp
7896                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7897                    return null;
7898                }
7899                // provider not enabled
7900                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7901                    return null;
7902                }
7903                return PackageParser.generateProviderInfo(
7904                        provider, flags, ps.readUserState(userId), userId);
7905            }
7906            return null;
7907        }
7908    }
7909
7910    /**
7911     * @deprecated
7912     */
7913    @Deprecated
7914    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7915        // reader
7916        synchronized (mPackages) {
7917            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7918                    .entrySet().iterator();
7919            final int userId = UserHandle.getCallingUserId();
7920            while (i.hasNext()) {
7921                Map.Entry<String, PackageParser.Provider> entry = i.next();
7922                PackageParser.Provider p = entry.getValue();
7923                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7924
7925                if (ps != null && p.syncable
7926                        && (!mSafeMode || (p.info.applicationInfo.flags
7927                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7928                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7929                            ps.readUserState(userId), userId);
7930                    if (info != null) {
7931                        outNames.add(entry.getKey());
7932                        outInfo.add(info);
7933                    }
7934                }
7935            }
7936        }
7937    }
7938
7939    @Override
7940    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7941            int uid, int flags, String metaDataKey) {
7942        final int userId = processName != null ? UserHandle.getUserId(uid)
7943                : UserHandle.getCallingUserId();
7944        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7945        flags = updateFlagsForComponent(flags, userId, processName);
7946
7947        ArrayList<ProviderInfo> finalList = null;
7948        // reader
7949        synchronized (mPackages) {
7950            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7951            while (i.hasNext()) {
7952                final PackageParser.Provider p = i.next();
7953                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7954                if (ps != null && p.info.authority != null
7955                        && (processName == null
7956                                || (p.info.processName.equals(processName)
7957                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7958                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7959
7960                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7961                    // parameter.
7962                    if (metaDataKey != null
7963                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7964                        continue;
7965                    }
7966
7967                    if (finalList == null) {
7968                        finalList = new ArrayList<ProviderInfo>(3);
7969                    }
7970                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7971                            ps.readUserState(userId), userId);
7972                    if (info != null) {
7973                        finalList.add(info);
7974                    }
7975                }
7976            }
7977        }
7978
7979        if (finalList != null) {
7980            Collections.sort(finalList, mProviderInitOrderSorter);
7981            return new ParceledListSlice<ProviderInfo>(finalList);
7982        }
7983
7984        return ParceledListSlice.emptyList();
7985    }
7986
7987    @Override
7988    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7989        // reader
7990        synchronized (mPackages) {
7991            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7992            return PackageParser.generateInstrumentationInfo(i, flags);
7993        }
7994    }
7995
7996    @Override
7997    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7998            String targetPackage, int flags) {
7999        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8000    }
8001
8002    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8003            int flags) {
8004        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8005
8006        // reader
8007        synchronized (mPackages) {
8008            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8009            while (i.hasNext()) {
8010                final PackageParser.Instrumentation p = i.next();
8011                if (targetPackage == null
8012                        || targetPackage.equals(p.info.targetPackage)) {
8013                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8014                            flags);
8015                    if (ii != null) {
8016                        finalList.add(ii);
8017                    }
8018                }
8019            }
8020        }
8021
8022        return finalList;
8023    }
8024
8025    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8026        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8027        try {
8028            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8029        } finally {
8030            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8031        }
8032    }
8033
8034    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8035        final File[] files = dir.listFiles();
8036        if (ArrayUtils.isEmpty(files)) {
8037            Log.d(TAG, "No files in app dir " + dir);
8038            return;
8039        }
8040
8041        if (DEBUG_PACKAGE_SCANNING) {
8042            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8043                    + " flags=0x" + Integer.toHexString(parseFlags));
8044        }
8045        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8046                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8047                mParallelPackageParserCallback);
8048
8049        // Submit files for parsing in parallel
8050        int fileCount = 0;
8051        for (File file : files) {
8052            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8053                    && !PackageInstallerService.isStageName(file.getName());
8054            if (!isPackage) {
8055                // Ignore entries which are not packages
8056                continue;
8057            }
8058            parallelPackageParser.submit(file, parseFlags);
8059            fileCount++;
8060        }
8061
8062        // Process results one by one
8063        for (; fileCount > 0; fileCount--) {
8064            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8065            Throwable throwable = parseResult.throwable;
8066            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8067
8068            if (throwable == null) {
8069                // Static shared libraries have synthetic package names
8070                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8071                    renameStaticSharedLibraryPackage(parseResult.pkg);
8072                }
8073                try {
8074                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8075                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8076                                currentTime, null);
8077                    }
8078                } catch (PackageManagerException e) {
8079                    errorCode = e.error;
8080                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8081                }
8082            } else if (throwable instanceof PackageParser.PackageParserException) {
8083                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8084                        throwable;
8085                errorCode = e.error;
8086                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8087            } else {
8088                throw new IllegalStateException("Unexpected exception occurred while parsing "
8089                        + parseResult.scanFile, throwable);
8090            }
8091
8092            // Delete invalid userdata apps
8093            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8094                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8095                logCriticalInfo(Log.WARN,
8096                        "Deleting invalid package at " + parseResult.scanFile);
8097                removeCodePathLI(parseResult.scanFile);
8098            }
8099        }
8100        parallelPackageParser.close();
8101    }
8102
8103    private static File getSettingsProblemFile() {
8104        File dataDir = Environment.getDataDirectory();
8105        File systemDir = new File(dataDir, "system");
8106        File fname = new File(systemDir, "uiderrors.txt");
8107        return fname;
8108    }
8109
8110    static void reportSettingsProblem(int priority, String msg) {
8111        logCriticalInfo(priority, msg);
8112    }
8113
8114    public static void logCriticalInfo(int priority, String msg) {
8115        Slog.println(priority, TAG, msg);
8116        EventLogTags.writePmCriticalInfo(msg);
8117        try {
8118            File fname = getSettingsProblemFile();
8119            FileOutputStream out = new FileOutputStream(fname, true);
8120            PrintWriter pw = new FastPrintWriter(out);
8121            SimpleDateFormat formatter = new SimpleDateFormat();
8122            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8123            pw.println(dateString + ": " + msg);
8124            pw.close();
8125            FileUtils.setPermissions(
8126                    fname.toString(),
8127                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8128                    -1, -1);
8129        } catch (java.io.IOException e) {
8130        }
8131    }
8132
8133    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8134        if (srcFile.isDirectory()) {
8135            final File baseFile = new File(pkg.baseCodePath);
8136            long maxModifiedTime = baseFile.lastModified();
8137            if (pkg.splitCodePaths != null) {
8138                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8139                    final File splitFile = new File(pkg.splitCodePaths[i]);
8140                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8141                }
8142            }
8143            return maxModifiedTime;
8144        }
8145        return srcFile.lastModified();
8146    }
8147
8148    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8149            final int policyFlags) throws PackageManagerException {
8150        // When upgrading from pre-N MR1, verify the package time stamp using the package
8151        // directory and not the APK file.
8152        final long lastModifiedTime = mIsPreNMR1Upgrade
8153                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8154        if (ps != null
8155                && ps.codePath.equals(srcFile)
8156                && ps.timeStamp == lastModifiedTime
8157                && !isCompatSignatureUpdateNeeded(pkg)
8158                && !isRecoverSignatureUpdateNeeded(pkg)) {
8159            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8160            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8161            ArraySet<PublicKey> signingKs;
8162            synchronized (mPackages) {
8163                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8164            }
8165            if (ps.signatures.mSignatures != null
8166                    && ps.signatures.mSignatures.length != 0
8167                    && signingKs != null) {
8168                // Optimization: reuse the existing cached certificates
8169                // if the package appears to be unchanged.
8170                pkg.mSignatures = ps.signatures.mSignatures;
8171                pkg.mSigningKeys = signingKs;
8172                return;
8173            }
8174
8175            Slog.w(TAG, "PackageSetting for " + ps.name
8176                    + " is missing signatures.  Collecting certs again to recover them.");
8177        } else {
8178            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8179        }
8180
8181        try {
8182            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8183            PackageParser.collectCertificates(pkg, policyFlags);
8184        } catch (PackageParserException e) {
8185            throw PackageManagerException.from(e);
8186        } finally {
8187            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8188        }
8189    }
8190
8191    /**
8192     *  Traces a package scan.
8193     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8194     */
8195    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8196            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8197        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8198        try {
8199            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8200        } finally {
8201            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8202        }
8203    }
8204
8205    /**
8206     *  Scans a package and returns the newly parsed package.
8207     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8208     */
8209    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8210            long currentTime, UserHandle user) throws PackageManagerException {
8211        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8212        PackageParser pp = new PackageParser();
8213        pp.setSeparateProcesses(mSeparateProcesses);
8214        pp.setOnlyCoreApps(mOnlyCore);
8215        pp.setDisplayMetrics(mMetrics);
8216        pp.setCallback(mPackageParserCallback);
8217
8218        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8219            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8220        }
8221
8222        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8223        final PackageParser.Package pkg;
8224        try {
8225            pkg = pp.parsePackage(scanFile, parseFlags);
8226        } catch (PackageParserException e) {
8227            throw PackageManagerException.from(e);
8228        } finally {
8229            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8230        }
8231
8232        // Static shared libraries have synthetic package names
8233        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8234            renameStaticSharedLibraryPackage(pkg);
8235        }
8236
8237        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8238    }
8239
8240    /**
8241     *  Scans a package and returns the newly parsed package.
8242     *  @throws PackageManagerException on a parse error.
8243     */
8244    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8245            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8246            throws PackageManagerException {
8247        // If the package has children and this is the first dive in the function
8248        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8249        // packages (parent and children) would be successfully scanned before the
8250        // actual scan since scanning mutates internal state and we want to atomically
8251        // install the package and its children.
8252        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8253            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8254                scanFlags |= SCAN_CHECK_ONLY;
8255            }
8256        } else {
8257            scanFlags &= ~SCAN_CHECK_ONLY;
8258        }
8259
8260        // Scan the parent
8261        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8262                scanFlags, currentTime, user);
8263
8264        // Scan the children
8265        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8266        for (int i = 0; i < childCount; i++) {
8267            PackageParser.Package childPackage = pkg.childPackages.get(i);
8268            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8269                    currentTime, user);
8270        }
8271
8272
8273        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8274            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8275        }
8276
8277        return scannedPkg;
8278    }
8279
8280    /**
8281     *  Scans a package and returns the newly parsed package.
8282     *  @throws PackageManagerException on a parse error.
8283     */
8284    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8285            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8286            throws PackageManagerException {
8287        PackageSetting ps = null;
8288        PackageSetting updatedPkg;
8289        // reader
8290        synchronized (mPackages) {
8291            // Look to see if we already know about this package.
8292            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8293            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8294                // This package has been renamed to its original name.  Let's
8295                // use that.
8296                ps = mSettings.getPackageLPr(oldName);
8297            }
8298            // If there was no original package, see one for the real package name.
8299            if (ps == null) {
8300                ps = mSettings.getPackageLPr(pkg.packageName);
8301            }
8302            // Check to see if this package could be hiding/updating a system
8303            // package.  Must look for it either under the original or real
8304            // package name depending on our state.
8305            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8306            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8307
8308            // If this is a package we don't know about on the system partition, we
8309            // may need to remove disabled child packages on the system partition
8310            // or may need to not add child packages if the parent apk is updated
8311            // on the data partition and no longer defines this child package.
8312            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8313                // If this is a parent package for an updated system app and this system
8314                // app got an OTA update which no longer defines some of the child packages
8315                // we have to prune them from the disabled system packages.
8316                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8317                if (disabledPs != null) {
8318                    final int scannedChildCount = (pkg.childPackages != null)
8319                            ? pkg.childPackages.size() : 0;
8320                    final int disabledChildCount = disabledPs.childPackageNames != null
8321                            ? disabledPs.childPackageNames.size() : 0;
8322                    for (int i = 0; i < disabledChildCount; i++) {
8323                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8324                        boolean disabledPackageAvailable = false;
8325                        for (int j = 0; j < scannedChildCount; j++) {
8326                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8327                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8328                                disabledPackageAvailable = true;
8329                                break;
8330                            }
8331                         }
8332                         if (!disabledPackageAvailable) {
8333                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8334                         }
8335                    }
8336                }
8337            }
8338        }
8339
8340        boolean updatedPkgBetter = false;
8341        // First check if this is a system package that may involve an update
8342        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8343            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8344            // it needs to drop FLAG_PRIVILEGED.
8345            if (locationIsPrivileged(scanFile)) {
8346                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8347            } else {
8348                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8349            }
8350
8351            if (ps != null && !ps.codePath.equals(scanFile)) {
8352                // The path has changed from what was last scanned...  check the
8353                // version of the new path against what we have stored to determine
8354                // what to do.
8355                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8356                if (pkg.mVersionCode <= ps.versionCode) {
8357                    // The system package has been updated and the code path does not match
8358                    // Ignore entry. Skip it.
8359                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8360                            + " ignored: updated version " + ps.versionCode
8361                            + " better than this " + pkg.mVersionCode);
8362                    if (!updatedPkg.codePath.equals(scanFile)) {
8363                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8364                                + ps.name + " changing from " + updatedPkg.codePathString
8365                                + " to " + scanFile);
8366                        updatedPkg.codePath = scanFile;
8367                        updatedPkg.codePathString = scanFile.toString();
8368                        updatedPkg.resourcePath = scanFile;
8369                        updatedPkg.resourcePathString = scanFile.toString();
8370                    }
8371                    updatedPkg.pkg = pkg;
8372                    updatedPkg.versionCode = pkg.mVersionCode;
8373
8374                    // Update the disabled system child packages to point to the package too.
8375                    final int childCount = updatedPkg.childPackageNames != null
8376                            ? updatedPkg.childPackageNames.size() : 0;
8377                    for (int i = 0; i < childCount; i++) {
8378                        String childPackageName = updatedPkg.childPackageNames.get(i);
8379                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8380                                childPackageName);
8381                        if (updatedChildPkg != null) {
8382                            updatedChildPkg.pkg = pkg;
8383                            updatedChildPkg.versionCode = pkg.mVersionCode;
8384                        }
8385                    }
8386
8387                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8388                            + scanFile + " ignored: updated version " + ps.versionCode
8389                            + " better than this " + pkg.mVersionCode);
8390                } else {
8391                    // The current app on the system partition is better than
8392                    // what we have updated to on the data partition; switch
8393                    // back to the system partition version.
8394                    // At this point, its safely assumed that package installation for
8395                    // apps in system partition will go through. If not there won't be a working
8396                    // version of the app
8397                    // writer
8398                    synchronized (mPackages) {
8399                        // Just remove the loaded entries from package lists.
8400                        mPackages.remove(ps.name);
8401                    }
8402
8403                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8404                            + " reverting from " + ps.codePathString
8405                            + ": new version " + pkg.mVersionCode
8406                            + " better than installed " + ps.versionCode);
8407
8408                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8409                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8410                    synchronized (mInstallLock) {
8411                        args.cleanUpResourcesLI();
8412                    }
8413                    synchronized (mPackages) {
8414                        mSettings.enableSystemPackageLPw(ps.name);
8415                    }
8416                    updatedPkgBetter = true;
8417                }
8418            }
8419        }
8420
8421        if (updatedPkg != null) {
8422            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8423            // initially
8424            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8425
8426            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8427            // flag set initially
8428            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8429                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8430            }
8431        }
8432
8433        // Verify certificates against what was last scanned
8434        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8435
8436        /*
8437         * A new system app appeared, but we already had a non-system one of the
8438         * same name installed earlier.
8439         */
8440        boolean shouldHideSystemApp = false;
8441        if (updatedPkg == null && ps != null
8442                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8443            /*
8444             * Check to make sure the signatures match first. If they don't,
8445             * wipe the installed application and its data.
8446             */
8447            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8448                    != PackageManager.SIGNATURE_MATCH) {
8449                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8450                        + " signatures don't match existing userdata copy; removing");
8451                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8452                        "scanPackageInternalLI")) {
8453                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8454                }
8455                ps = null;
8456            } else {
8457                /*
8458                 * If the newly-added system app is an older version than the
8459                 * already installed version, hide it. It will be scanned later
8460                 * and re-added like an update.
8461                 */
8462                if (pkg.mVersionCode <= ps.versionCode) {
8463                    shouldHideSystemApp = true;
8464                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8465                            + " but new version " + pkg.mVersionCode + " better than installed "
8466                            + ps.versionCode + "; hiding system");
8467                } else {
8468                    /*
8469                     * The newly found system app is a newer version that the
8470                     * one previously installed. Simply remove the
8471                     * already-installed application and replace it with our own
8472                     * while keeping the application data.
8473                     */
8474                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8475                            + " reverting from " + ps.codePathString + ": new version "
8476                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8477                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8478                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8479                    synchronized (mInstallLock) {
8480                        args.cleanUpResourcesLI();
8481                    }
8482                }
8483            }
8484        }
8485
8486        // The apk is forward locked (not public) if its code and resources
8487        // are kept in different files. (except for app in either system or
8488        // vendor path).
8489        // TODO grab this value from PackageSettings
8490        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8491            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8492                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8493            }
8494        }
8495
8496        // TODO: extend to support forward-locked splits
8497        String resourcePath = null;
8498        String baseResourcePath = null;
8499        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8500            if (ps != null && ps.resourcePathString != null) {
8501                resourcePath = ps.resourcePathString;
8502                baseResourcePath = ps.resourcePathString;
8503            } else {
8504                // Should not happen at all. Just log an error.
8505                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8506            }
8507        } else {
8508            resourcePath = pkg.codePath;
8509            baseResourcePath = pkg.baseCodePath;
8510        }
8511
8512        // Set application objects path explicitly.
8513        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8514        pkg.setApplicationInfoCodePath(pkg.codePath);
8515        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8516        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8517        pkg.setApplicationInfoResourcePath(resourcePath);
8518        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8519        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8520
8521        final int userId = ((user == null) ? 0 : user.getIdentifier());
8522        if (ps != null && ps.getInstantApp(userId)) {
8523            scanFlags |= SCAN_AS_INSTANT_APP;
8524        }
8525
8526        // Note that we invoke the following method only if we are about to unpack an application
8527        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8528                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8529
8530        /*
8531         * If the system app should be overridden by a previously installed
8532         * data, hide the system app now and let the /data/app scan pick it up
8533         * again.
8534         */
8535        if (shouldHideSystemApp) {
8536            synchronized (mPackages) {
8537                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8538            }
8539        }
8540
8541        return scannedPkg;
8542    }
8543
8544    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8545        // Derive the new package synthetic package name
8546        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8547                + pkg.staticSharedLibVersion);
8548    }
8549
8550    private static String fixProcessName(String defProcessName,
8551            String processName) {
8552        if (processName == null) {
8553            return defProcessName;
8554        }
8555        return processName;
8556    }
8557
8558    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8559            throws PackageManagerException {
8560        if (pkgSetting.signatures.mSignatures != null) {
8561            // Already existing package. Make sure signatures match
8562            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8563                    == PackageManager.SIGNATURE_MATCH;
8564            if (!match) {
8565                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8566                        == PackageManager.SIGNATURE_MATCH;
8567            }
8568            if (!match) {
8569                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8570                        == PackageManager.SIGNATURE_MATCH;
8571            }
8572            if (!match) {
8573                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8574                        + pkg.packageName + " signatures do not match the "
8575                        + "previously installed version; ignoring!");
8576            }
8577        }
8578
8579        // Check for shared user signatures
8580        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8581            // Already existing package. Make sure signatures match
8582            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8583                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8584            if (!match) {
8585                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8586                        == PackageManager.SIGNATURE_MATCH;
8587            }
8588            if (!match) {
8589                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8590                        == PackageManager.SIGNATURE_MATCH;
8591            }
8592            if (!match) {
8593                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8594                        "Package " + pkg.packageName
8595                        + " has no signatures that match those in shared user "
8596                        + pkgSetting.sharedUser.name + "; ignoring!");
8597            }
8598        }
8599    }
8600
8601    /**
8602     * Enforces that only the system UID or root's UID can call a method exposed
8603     * via Binder.
8604     *
8605     * @param message used as message if SecurityException is thrown
8606     * @throws SecurityException if the caller is not system or root
8607     */
8608    private static final void enforceSystemOrRoot(String message) {
8609        final int uid = Binder.getCallingUid();
8610        if (uid != Process.SYSTEM_UID && uid != 0) {
8611            throw new SecurityException(message);
8612        }
8613    }
8614
8615    @Override
8616    public void performFstrimIfNeeded() {
8617        enforceSystemOrRoot("Only the system can request fstrim");
8618
8619        // Before everything else, see whether we need to fstrim.
8620        try {
8621            IStorageManager sm = PackageHelper.getStorageManager();
8622            if (sm != null) {
8623                boolean doTrim = false;
8624                final long interval = android.provider.Settings.Global.getLong(
8625                        mContext.getContentResolver(),
8626                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8627                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8628                if (interval > 0) {
8629                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8630                    if (timeSinceLast > interval) {
8631                        doTrim = true;
8632                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8633                                + "; running immediately");
8634                    }
8635                }
8636                if (doTrim) {
8637                    final boolean dexOptDialogShown;
8638                    synchronized (mPackages) {
8639                        dexOptDialogShown = mDexOptDialogShown;
8640                    }
8641                    if (!isFirstBoot() && dexOptDialogShown) {
8642                        try {
8643                            ActivityManager.getService().showBootMessage(
8644                                    mContext.getResources().getString(
8645                                            R.string.android_upgrading_fstrim), true);
8646                        } catch (RemoteException e) {
8647                        }
8648                    }
8649                    sm.runMaintenance();
8650                }
8651            } else {
8652                Slog.e(TAG, "storageManager service unavailable!");
8653            }
8654        } catch (RemoteException e) {
8655            // Can't happen; StorageManagerService is local
8656        }
8657    }
8658
8659    @Override
8660    public void updatePackagesIfNeeded() {
8661        enforceSystemOrRoot("Only the system can request package update");
8662
8663        // We need to re-extract after an OTA.
8664        boolean causeUpgrade = isUpgrade();
8665
8666        // First boot or factory reset.
8667        // Note: we also handle devices that are upgrading to N right now as if it is their
8668        //       first boot, as they do not have profile data.
8669        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8670
8671        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8672        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8673
8674        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8675            return;
8676        }
8677
8678        List<PackageParser.Package> pkgs;
8679        synchronized (mPackages) {
8680            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8681        }
8682
8683        final long startTime = System.nanoTime();
8684        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8685                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8686
8687        final int elapsedTimeSeconds =
8688                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8689
8690        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8691        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8692        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8693        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8694        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8695    }
8696
8697    /**
8698     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8699     * containing statistics about the invocation. The array consists of three elements,
8700     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8701     * and {@code numberOfPackagesFailed}.
8702     */
8703    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8704            String compilerFilter) {
8705
8706        int numberOfPackagesVisited = 0;
8707        int numberOfPackagesOptimized = 0;
8708        int numberOfPackagesSkipped = 0;
8709        int numberOfPackagesFailed = 0;
8710        final int numberOfPackagesToDexopt = pkgs.size();
8711
8712        for (PackageParser.Package pkg : pkgs) {
8713            numberOfPackagesVisited++;
8714
8715            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8716                if (DEBUG_DEXOPT) {
8717                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8718                }
8719                numberOfPackagesSkipped++;
8720                continue;
8721            }
8722
8723            if (DEBUG_DEXOPT) {
8724                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8725                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8726            }
8727
8728            if (showDialog) {
8729                try {
8730                    ActivityManager.getService().showBootMessage(
8731                            mContext.getResources().getString(R.string.android_upgrading_apk,
8732                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8733                } catch (RemoteException e) {
8734                }
8735                synchronized (mPackages) {
8736                    mDexOptDialogShown = true;
8737                }
8738            }
8739
8740            // If the OTA updates a system app which was previously preopted to a non-preopted state
8741            // the app might end up being verified at runtime. That's because by default the apps
8742            // are verify-profile but for preopted apps there's no profile.
8743            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8744            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8745            // filter (by default 'quicken').
8746            // Note that at this stage unused apps are already filtered.
8747            if (isSystemApp(pkg) &&
8748                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8749                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8750                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8751            }
8752
8753            // checkProfiles is false to avoid merging profiles during boot which
8754            // might interfere with background compilation (b/28612421).
8755            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8756            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8757            // trade-off worth doing to save boot time work.
8758            int dexOptStatus = performDexOptTraced(pkg.packageName,
8759                    false /* checkProfiles */,
8760                    compilerFilter,
8761                    false /* force */);
8762            switch (dexOptStatus) {
8763                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8764                    numberOfPackagesOptimized++;
8765                    break;
8766                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8767                    numberOfPackagesSkipped++;
8768                    break;
8769                case PackageDexOptimizer.DEX_OPT_FAILED:
8770                    numberOfPackagesFailed++;
8771                    break;
8772                default:
8773                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8774                    break;
8775            }
8776        }
8777
8778        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8779                numberOfPackagesFailed };
8780    }
8781
8782    @Override
8783    public void notifyPackageUse(String packageName, int reason) {
8784        synchronized (mPackages) {
8785            PackageParser.Package p = mPackages.get(packageName);
8786            if (p == null) {
8787                return;
8788            }
8789            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8790        }
8791    }
8792
8793    @Override
8794    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8795        int userId = UserHandle.getCallingUserId();
8796        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8797        if (ai == null) {
8798            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8799                + loadingPackageName + ", user=" + userId);
8800            return;
8801        }
8802        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8803    }
8804
8805    @Override
8806    public boolean performDexOpt(String packageName,
8807            boolean checkProfiles, int compileReason, boolean force) {
8808        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8809                getCompilerFilterForReason(compileReason), force);
8810        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8811    }
8812
8813    @Override
8814    public boolean performDexOptMode(String packageName,
8815            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8816        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8817                targetCompilerFilter, force);
8818        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8819    }
8820
8821    private int performDexOptTraced(String packageName,
8822                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8823        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8824        try {
8825            return performDexOptInternal(packageName, checkProfiles,
8826                    targetCompilerFilter, force);
8827        } finally {
8828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8829        }
8830    }
8831
8832    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8833    // if the package can now be considered up to date for the given filter.
8834    private int performDexOptInternal(String packageName,
8835                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8836        PackageParser.Package p;
8837        synchronized (mPackages) {
8838            p = mPackages.get(packageName);
8839            if (p == null) {
8840                // Package could not be found. Report failure.
8841                return PackageDexOptimizer.DEX_OPT_FAILED;
8842            }
8843            mPackageUsage.maybeWriteAsync(mPackages);
8844            mCompilerStats.maybeWriteAsync();
8845        }
8846        long callingId = Binder.clearCallingIdentity();
8847        try {
8848            synchronized (mInstallLock) {
8849                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8850                        targetCompilerFilter, force);
8851            }
8852        } finally {
8853            Binder.restoreCallingIdentity(callingId);
8854        }
8855    }
8856
8857    public ArraySet<String> getOptimizablePackages() {
8858        ArraySet<String> pkgs = new ArraySet<String>();
8859        synchronized (mPackages) {
8860            for (PackageParser.Package p : mPackages.values()) {
8861                if (PackageDexOptimizer.canOptimizePackage(p)) {
8862                    pkgs.add(p.packageName);
8863                }
8864            }
8865        }
8866        return pkgs;
8867    }
8868
8869    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8870            boolean checkProfiles, String targetCompilerFilter,
8871            boolean force) {
8872        // Select the dex optimizer based on the force parameter.
8873        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8874        //       allocate an object here.
8875        PackageDexOptimizer pdo = force
8876                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8877                : mPackageDexOptimizer;
8878
8879        // Dexopt all dependencies first. Note: we ignore the return value and march on
8880        // on errors.
8881        // Note that we are going to call performDexOpt on those libraries as many times as
8882        // they are referenced in packages. When we do a batch of performDexOpt (for example
8883        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8884        // and the first package that uses the library will dexopt it. The
8885        // others will see that the compiled code for the library is up to date.
8886        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8887        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8888        if (!deps.isEmpty()) {
8889            for (PackageParser.Package depPackage : deps) {
8890                // TODO: Analyze and investigate if we (should) profile libraries.
8891                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8892                        false /* checkProfiles */,
8893                        targetCompilerFilter,
8894                        getOrCreateCompilerPackageStats(depPackage),
8895                        true /* isUsedByOtherApps */);
8896            }
8897        }
8898        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8899                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8900                mDexManager.isUsedByOtherApps(p.packageName));
8901    }
8902
8903    // Performs dexopt on the used secondary dex files belonging to the given package.
8904    // Returns true if all dex files were process successfully (which could mean either dexopt or
8905    // skip). Returns false if any of the files caused errors.
8906    @Override
8907    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8908            boolean force) {
8909        mDexManager.reconcileSecondaryDexFiles(packageName);
8910        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8911    }
8912
8913    public boolean performDexOptSecondary(String packageName, int compileReason,
8914            boolean force) {
8915        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8916    }
8917
8918    /**
8919     * Reconcile the information we have about the secondary dex files belonging to
8920     * {@code packagName} and the actual dex files. For all dex files that were
8921     * deleted, update the internal records and delete the generated oat files.
8922     */
8923    @Override
8924    public void reconcileSecondaryDexFiles(String packageName) {
8925        mDexManager.reconcileSecondaryDexFiles(packageName);
8926    }
8927
8928    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8929    // a reference there.
8930    /*package*/ DexManager getDexManager() {
8931        return mDexManager;
8932    }
8933
8934    /**
8935     * Execute the background dexopt job immediately.
8936     */
8937    @Override
8938    public boolean runBackgroundDexoptJob() {
8939        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8940    }
8941
8942    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8943        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8944                || p.usesStaticLibraries != null) {
8945            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8946            Set<String> collectedNames = new HashSet<>();
8947            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8948
8949            retValue.remove(p);
8950
8951            return retValue;
8952        } else {
8953            return Collections.emptyList();
8954        }
8955    }
8956
8957    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8958            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8959        if (!collectedNames.contains(p.packageName)) {
8960            collectedNames.add(p.packageName);
8961            collected.add(p);
8962
8963            if (p.usesLibraries != null) {
8964                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8965                        null, collected, collectedNames);
8966            }
8967            if (p.usesOptionalLibraries != null) {
8968                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8969                        null, collected, collectedNames);
8970            }
8971            if (p.usesStaticLibraries != null) {
8972                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8973                        p.usesStaticLibrariesVersions, collected, collectedNames);
8974            }
8975        }
8976    }
8977
8978    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8979            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8980        final int libNameCount = libs.size();
8981        for (int i = 0; i < libNameCount; i++) {
8982            String libName = libs.get(i);
8983            int version = (versions != null && versions.length == libNameCount)
8984                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8985            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8986            if (libPkg != null) {
8987                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8988            }
8989        }
8990    }
8991
8992    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8993        synchronized (mPackages) {
8994            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8995            if (libEntry != null) {
8996                return mPackages.get(libEntry.apk);
8997            }
8998            return null;
8999        }
9000    }
9001
9002    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9003        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9004        if (versionedLib == null) {
9005            return null;
9006        }
9007        return versionedLib.get(version);
9008    }
9009
9010    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9011        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9012                pkg.staticSharedLibName);
9013        if (versionedLib == null) {
9014            return null;
9015        }
9016        int previousLibVersion = -1;
9017        final int versionCount = versionedLib.size();
9018        for (int i = 0; i < versionCount; i++) {
9019            final int libVersion = versionedLib.keyAt(i);
9020            if (libVersion < pkg.staticSharedLibVersion) {
9021                previousLibVersion = Math.max(previousLibVersion, libVersion);
9022            }
9023        }
9024        if (previousLibVersion >= 0) {
9025            return versionedLib.get(previousLibVersion);
9026        }
9027        return null;
9028    }
9029
9030    public void shutdown() {
9031        mPackageUsage.writeNow(mPackages);
9032        mCompilerStats.writeNow();
9033    }
9034
9035    @Override
9036    public void dumpProfiles(String packageName) {
9037        PackageParser.Package pkg;
9038        synchronized (mPackages) {
9039            pkg = mPackages.get(packageName);
9040            if (pkg == null) {
9041                throw new IllegalArgumentException("Unknown package: " + packageName);
9042            }
9043        }
9044        /* Only the shell, root, or the app user should be able to dump profiles. */
9045        int callingUid = Binder.getCallingUid();
9046        if (callingUid != Process.SHELL_UID &&
9047            callingUid != Process.ROOT_UID &&
9048            callingUid != pkg.applicationInfo.uid) {
9049            throw new SecurityException("dumpProfiles");
9050        }
9051
9052        synchronized (mInstallLock) {
9053            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9054            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9055            try {
9056                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9057                String codePaths = TextUtils.join(";", allCodePaths);
9058                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9059            } catch (InstallerException e) {
9060                Slog.w(TAG, "Failed to dump profiles", e);
9061            }
9062            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9063        }
9064    }
9065
9066    @Override
9067    public void forceDexOpt(String packageName) {
9068        enforceSystemOrRoot("forceDexOpt");
9069
9070        PackageParser.Package pkg;
9071        synchronized (mPackages) {
9072            pkg = mPackages.get(packageName);
9073            if (pkg == null) {
9074                throw new IllegalArgumentException("Unknown package: " + packageName);
9075            }
9076        }
9077
9078        synchronized (mInstallLock) {
9079            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9080
9081            // Whoever is calling forceDexOpt wants a compiled package.
9082            // Don't use profiles since that may cause compilation to be skipped.
9083            final int res = performDexOptInternalWithDependenciesLI(pkg,
9084                    false /* checkProfiles */, getDefaultCompilerFilter(),
9085                    true /* force */);
9086
9087            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9088            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9089                throw new IllegalStateException("Failed to dexopt: " + res);
9090            }
9091        }
9092    }
9093
9094    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9095        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9096            Slog.w(TAG, "Unable to update from " + oldPkg.name
9097                    + " to " + newPkg.packageName
9098                    + ": old package not in system partition");
9099            return false;
9100        } else if (mPackages.get(oldPkg.name) != null) {
9101            Slog.w(TAG, "Unable to update from " + oldPkg.name
9102                    + " to " + newPkg.packageName
9103                    + ": old package still exists");
9104            return false;
9105        }
9106        return true;
9107    }
9108
9109    void removeCodePathLI(File codePath) {
9110        if (codePath.isDirectory()) {
9111            try {
9112                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9113            } catch (InstallerException e) {
9114                Slog.w(TAG, "Failed to remove code path", e);
9115            }
9116        } else {
9117            codePath.delete();
9118        }
9119    }
9120
9121    private int[] resolveUserIds(int userId) {
9122        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9123    }
9124
9125    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9126        if (pkg == null) {
9127            Slog.wtf(TAG, "Package was null!", new Throwable());
9128            return;
9129        }
9130        clearAppDataLeafLIF(pkg, userId, flags);
9131        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9132        for (int i = 0; i < childCount; i++) {
9133            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9134        }
9135    }
9136
9137    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9138        final PackageSetting ps;
9139        synchronized (mPackages) {
9140            ps = mSettings.mPackages.get(pkg.packageName);
9141        }
9142        for (int realUserId : resolveUserIds(userId)) {
9143            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9144            try {
9145                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9146                        ceDataInode);
9147            } catch (InstallerException e) {
9148                Slog.w(TAG, String.valueOf(e));
9149            }
9150        }
9151    }
9152
9153    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9154        if (pkg == null) {
9155            Slog.wtf(TAG, "Package was null!", new Throwable());
9156            return;
9157        }
9158        destroyAppDataLeafLIF(pkg, userId, flags);
9159        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9160        for (int i = 0; i < childCount; i++) {
9161            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9162        }
9163    }
9164
9165    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9166        final PackageSetting ps;
9167        synchronized (mPackages) {
9168            ps = mSettings.mPackages.get(pkg.packageName);
9169        }
9170        for (int realUserId : resolveUserIds(userId)) {
9171            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9172            try {
9173                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9174                        ceDataInode);
9175            } catch (InstallerException e) {
9176                Slog.w(TAG, String.valueOf(e));
9177            }
9178            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9179        }
9180    }
9181
9182    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9183        if (pkg == null) {
9184            Slog.wtf(TAG, "Package was null!", new Throwable());
9185            return;
9186        }
9187        destroyAppProfilesLeafLIF(pkg);
9188        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9189        for (int i = 0; i < childCount; i++) {
9190            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9191        }
9192    }
9193
9194    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9195        try {
9196            mInstaller.destroyAppProfiles(pkg.packageName);
9197        } catch (InstallerException e) {
9198            Slog.w(TAG, String.valueOf(e));
9199        }
9200    }
9201
9202    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9203        if (pkg == null) {
9204            Slog.wtf(TAG, "Package was null!", new Throwable());
9205            return;
9206        }
9207        clearAppProfilesLeafLIF(pkg);
9208        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9209        for (int i = 0; i < childCount; i++) {
9210            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9211        }
9212    }
9213
9214    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9215        try {
9216            mInstaller.clearAppProfiles(pkg.packageName);
9217        } catch (InstallerException e) {
9218            Slog.w(TAG, String.valueOf(e));
9219        }
9220    }
9221
9222    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9223            long lastUpdateTime) {
9224        // Set parent install/update time
9225        PackageSetting ps = (PackageSetting) pkg.mExtras;
9226        if (ps != null) {
9227            ps.firstInstallTime = firstInstallTime;
9228            ps.lastUpdateTime = lastUpdateTime;
9229        }
9230        // Set children install/update time
9231        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9232        for (int i = 0; i < childCount; i++) {
9233            PackageParser.Package childPkg = pkg.childPackages.get(i);
9234            ps = (PackageSetting) childPkg.mExtras;
9235            if (ps != null) {
9236                ps.firstInstallTime = firstInstallTime;
9237                ps.lastUpdateTime = lastUpdateTime;
9238            }
9239        }
9240    }
9241
9242    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9243            PackageParser.Package changingLib) {
9244        if (file.path != null) {
9245            usesLibraryFiles.add(file.path);
9246            return;
9247        }
9248        PackageParser.Package p = mPackages.get(file.apk);
9249        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9250            // If we are doing this while in the middle of updating a library apk,
9251            // then we need to make sure to use that new apk for determining the
9252            // dependencies here.  (We haven't yet finished committing the new apk
9253            // to the package manager state.)
9254            if (p == null || p.packageName.equals(changingLib.packageName)) {
9255                p = changingLib;
9256            }
9257        }
9258        if (p != null) {
9259            usesLibraryFiles.addAll(p.getAllCodePaths());
9260        }
9261    }
9262
9263    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9264            PackageParser.Package changingLib) throws PackageManagerException {
9265        if (pkg == null) {
9266            return;
9267        }
9268        ArraySet<String> usesLibraryFiles = null;
9269        if (pkg.usesLibraries != null) {
9270            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9271                    null, null, pkg.packageName, changingLib, true, null);
9272        }
9273        if (pkg.usesStaticLibraries != null) {
9274            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9275                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9276                    pkg.packageName, changingLib, true, usesLibraryFiles);
9277        }
9278        if (pkg.usesOptionalLibraries != null) {
9279            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9280                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9281        }
9282        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9283            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9284        } else {
9285            pkg.usesLibraryFiles = null;
9286        }
9287    }
9288
9289    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9290            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9291            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9292            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9293            throws PackageManagerException {
9294        final int libCount = requestedLibraries.size();
9295        for (int i = 0; i < libCount; i++) {
9296            final String libName = requestedLibraries.get(i);
9297            final int libVersion = requiredVersions != null ? requiredVersions[i]
9298                    : SharedLibraryInfo.VERSION_UNDEFINED;
9299            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9300            if (libEntry == null) {
9301                if (required) {
9302                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9303                            "Package " + packageName + " requires unavailable shared library "
9304                                    + libName + "; failing!");
9305                } else {
9306                    Slog.w(TAG, "Package " + packageName
9307                            + " desires unavailable shared library "
9308                            + libName + "; ignoring!");
9309                }
9310            } else {
9311                if (requiredVersions != null && requiredCertDigests != null) {
9312                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9313                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9314                            "Package " + packageName + " requires unavailable static shared"
9315                                    + " library " + libName + " version "
9316                                    + libEntry.info.getVersion() + "; failing!");
9317                    }
9318
9319                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9320                    if (libPkg == null) {
9321                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9322                                "Package " + packageName + " requires unavailable static shared"
9323                                        + " library; failing!");
9324                    }
9325
9326                    String expectedCertDigest = requiredCertDigests[i];
9327                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9328                                libPkg.mSignatures[0]);
9329                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9330                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9331                                "Package " + packageName + " requires differently signed" +
9332                                        " static shared library; failing!");
9333                    }
9334                }
9335
9336                if (outUsedLibraries == null) {
9337                    outUsedLibraries = new ArraySet<>();
9338                }
9339                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9340            }
9341        }
9342        return outUsedLibraries;
9343    }
9344
9345    private static boolean hasString(List<String> list, List<String> which) {
9346        if (list == null) {
9347            return false;
9348        }
9349        for (int i=list.size()-1; i>=0; i--) {
9350            for (int j=which.size()-1; j>=0; j--) {
9351                if (which.get(j).equals(list.get(i))) {
9352                    return true;
9353                }
9354            }
9355        }
9356        return false;
9357    }
9358
9359    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9360            PackageParser.Package changingPkg) {
9361        ArrayList<PackageParser.Package> res = null;
9362        for (PackageParser.Package pkg : mPackages.values()) {
9363            if (changingPkg != null
9364                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9365                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9366                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9367                            changingPkg.staticSharedLibName)) {
9368                return null;
9369            }
9370            if (res == null) {
9371                res = new ArrayList<>();
9372            }
9373            res.add(pkg);
9374            try {
9375                updateSharedLibrariesLPr(pkg, changingPkg);
9376            } catch (PackageManagerException e) {
9377                // If a system app update or an app and a required lib missing we
9378                // delete the package and for updated system apps keep the data as
9379                // it is better for the user to reinstall than to be in an limbo
9380                // state. Also libs disappearing under an app should never happen
9381                // - just in case.
9382                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9383                    final int flags = pkg.isUpdatedSystemApp()
9384                            ? PackageManager.DELETE_KEEP_DATA : 0;
9385                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9386                            flags , null, true, null);
9387                }
9388                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9389            }
9390        }
9391        return res;
9392    }
9393
9394    /**
9395     * Derive the value of the {@code cpuAbiOverride} based on the provided
9396     * value and an optional stored value from the package settings.
9397     */
9398    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9399        String cpuAbiOverride = null;
9400
9401        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9402            cpuAbiOverride = null;
9403        } else if (abiOverride != null) {
9404            cpuAbiOverride = abiOverride;
9405        } else if (settings != null) {
9406            cpuAbiOverride = settings.cpuAbiOverrideString;
9407        }
9408
9409        return cpuAbiOverride;
9410    }
9411
9412    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9413            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9414                    throws PackageManagerException {
9415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9416        // If the package has children and this is the first dive in the function
9417        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9418        // whether all packages (parent and children) would be successfully scanned
9419        // before the actual scan since scanning mutates internal state and we want
9420        // to atomically install the package and its children.
9421        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9422            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9423                scanFlags |= SCAN_CHECK_ONLY;
9424            }
9425        } else {
9426            scanFlags &= ~SCAN_CHECK_ONLY;
9427        }
9428
9429        final PackageParser.Package scannedPkg;
9430        try {
9431            // Scan the parent
9432            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9433            // Scan the children
9434            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9435            for (int i = 0; i < childCount; i++) {
9436                PackageParser.Package childPkg = pkg.childPackages.get(i);
9437                scanPackageLI(childPkg, policyFlags,
9438                        scanFlags, currentTime, user);
9439            }
9440        } finally {
9441            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9442        }
9443
9444        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9445            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9446        }
9447
9448        return scannedPkg;
9449    }
9450
9451    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9452            int scanFlags, long currentTime, @Nullable UserHandle user)
9453                    throws PackageManagerException {
9454        boolean success = false;
9455        try {
9456            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9457                    currentTime, user);
9458            success = true;
9459            return res;
9460        } finally {
9461            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9462                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9463                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9464                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9465                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9466            }
9467        }
9468    }
9469
9470    /**
9471     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9472     */
9473    private static boolean apkHasCode(String fileName) {
9474        StrictJarFile jarFile = null;
9475        try {
9476            jarFile = new StrictJarFile(fileName,
9477                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9478            return jarFile.findEntry("classes.dex") != null;
9479        } catch (IOException ignore) {
9480        } finally {
9481            try {
9482                if (jarFile != null) {
9483                    jarFile.close();
9484                }
9485            } catch (IOException ignore) {}
9486        }
9487        return false;
9488    }
9489
9490    /**
9491     * Enforces code policy for the package. This ensures that if an APK has
9492     * declared hasCode="true" in its manifest that the APK actually contains
9493     * code.
9494     *
9495     * @throws PackageManagerException If bytecode could not be found when it should exist
9496     */
9497    private static void assertCodePolicy(PackageParser.Package pkg)
9498            throws PackageManagerException {
9499        final boolean shouldHaveCode =
9500                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9501        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9502            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9503                    "Package " + pkg.baseCodePath + " code is missing");
9504        }
9505
9506        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9507            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9508                final boolean splitShouldHaveCode =
9509                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9510                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9511                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9512                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9513                }
9514            }
9515        }
9516    }
9517
9518    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9519            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9520                    throws PackageManagerException {
9521        if (DEBUG_PACKAGE_SCANNING) {
9522            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9523                Log.d(TAG, "Scanning package " + pkg.packageName);
9524        }
9525
9526        applyPolicy(pkg, policyFlags);
9527
9528        assertPackageIsValid(pkg, policyFlags, scanFlags);
9529
9530        // Initialize package source and resource directories
9531        final File scanFile = new File(pkg.codePath);
9532        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9533        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9534
9535        SharedUserSetting suid = null;
9536        PackageSetting pkgSetting = null;
9537
9538        // Getting the package setting may have a side-effect, so if we
9539        // are only checking if scan would succeed, stash a copy of the
9540        // old setting to restore at the end.
9541        PackageSetting nonMutatedPs = null;
9542
9543        // We keep references to the derived CPU Abis from settings in oder to reuse
9544        // them in the case where we're not upgrading or booting for the first time.
9545        String primaryCpuAbiFromSettings = null;
9546        String secondaryCpuAbiFromSettings = null;
9547
9548        // writer
9549        synchronized (mPackages) {
9550            if (pkg.mSharedUserId != null) {
9551                // SIDE EFFECTS; may potentially allocate a new shared user
9552                suid = mSettings.getSharedUserLPw(
9553                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9554                if (DEBUG_PACKAGE_SCANNING) {
9555                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9556                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9557                                + "): packages=" + suid.packages);
9558                }
9559            }
9560
9561            // Check if we are renaming from an original package name.
9562            PackageSetting origPackage = null;
9563            String realName = null;
9564            if (pkg.mOriginalPackages != null) {
9565                // This package may need to be renamed to a previously
9566                // installed name.  Let's check on that...
9567                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9568                if (pkg.mOriginalPackages.contains(renamed)) {
9569                    // This package had originally been installed as the
9570                    // original name, and we have already taken care of
9571                    // transitioning to the new one.  Just update the new
9572                    // one to continue using the old name.
9573                    realName = pkg.mRealPackage;
9574                    if (!pkg.packageName.equals(renamed)) {
9575                        // Callers into this function may have already taken
9576                        // care of renaming the package; only do it here if
9577                        // it is not already done.
9578                        pkg.setPackageName(renamed);
9579                    }
9580                } else {
9581                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9582                        if ((origPackage = mSettings.getPackageLPr(
9583                                pkg.mOriginalPackages.get(i))) != null) {
9584                            // We do have the package already installed under its
9585                            // original name...  should we use it?
9586                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9587                                // New package is not compatible with original.
9588                                origPackage = null;
9589                                continue;
9590                            } else if (origPackage.sharedUser != null) {
9591                                // Make sure uid is compatible between packages.
9592                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9593                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9594                                            + " to " + pkg.packageName + ": old uid "
9595                                            + origPackage.sharedUser.name
9596                                            + " differs from " + pkg.mSharedUserId);
9597                                    origPackage = null;
9598                                    continue;
9599                                }
9600                                // TODO: Add case when shared user id is added [b/28144775]
9601                            } else {
9602                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9603                                        + pkg.packageName + " to old name " + origPackage.name);
9604                            }
9605                            break;
9606                        }
9607                    }
9608                }
9609            }
9610
9611            if (mTransferedPackages.contains(pkg.packageName)) {
9612                Slog.w(TAG, "Package " + pkg.packageName
9613                        + " was transferred to another, but its .apk remains");
9614            }
9615
9616            // See comments in nonMutatedPs declaration
9617            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9618                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9619                if (foundPs != null) {
9620                    nonMutatedPs = new PackageSetting(foundPs);
9621                }
9622            }
9623
9624            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9625                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9626                if (foundPs != null) {
9627                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9628                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9629                }
9630            }
9631
9632            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9633            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9634                PackageManagerService.reportSettingsProblem(Log.WARN,
9635                        "Package " + pkg.packageName + " shared user changed from "
9636                                + (pkgSetting.sharedUser != null
9637                                        ? pkgSetting.sharedUser.name : "<nothing>")
9638                                + " to "
9639                                + (suid != null ? suid.name : "<nothing>")
9640                                + "; replacing with new");
9641                pkgSetting = null;
9642            }
9643            final PackageSetting oldPkgSetting =
9644                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9645            final PackageSetting disabledPkgSetting =
9646                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9647
9648            String[] usesStaticLibraries = null;
9649            if (pkg.usesStaticLibraries != null) {
9650                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9651                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9652            }
9653
9654            if (pkgSetting == null) {
9655                final String parentPackageName = (pkg.parentPackage != null)
9656                        ? pkg.parentPackage.packageName : null;
9657                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9658                // REMOVE SharedUserSetting from method; update in a separate call
9659                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9660                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9661                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9662                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9663                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9664                        true /*allowInstall*/, instantApp, parentPackageName,
9665                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9666                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9667                // SIDE EFFECTS; updates system state; move elsewhere
9668                if (origPackage != null) {
9669                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9670                }
9671                mSettings.addUserToSettingLPw(pkgSetting);
9672            } else {
9673                // REMOVE SharedUserSetting from method; update in a separate call.
9674                //
9675                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9676                // secondaryCpuAbi are not known at this point so we always update them
9677                // to null here, only to reset them at a later point.
9678                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9679                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9680                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9681                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9682                        UserManagerService.getInstance(), usesStaticLibraries,
9683                        pkg.usesStaticLibrariesVersions);
9684            }
9685            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9686            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9687
9688            // SIDE EFFECTS; modifies system state; move elsewhere
9689            if (pkgSetting.origPackage != null) {
9690                // If we are first transitioning from an original package,
9691                // fix up the new package's name now.  We need to do this after
9692                // looking up the package under its new name, so getPackageLP
9693                // can take care of fiddling things correctly.
9694                pkg.setPackageName(origPackage.name);
9695
9696                // File a report about this.
9697                String msg = "New package " + pkgSetting.realName
9698                        + " renamed to replace old package " + pkgSetting.name;
9699                reportSettingsProblem(Log.WARN, msg);
9700
9701                // Make a note of it.
9702                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9703                    mTransferedPackages.add(origPackage.name);
9704                }
9705
9706                // No longer need to retain this.
9707                pkgSetting.origPackage = null;
9708            }
9709
9710            // SIDE EFFECTS; modifies system state; move elsewhere
9711            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9712                // Make a note of it.
9713                mTransferedPackages.add(pkg.packageName);
9714            }
9715
9716            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9717                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9718            }
9719
9720            if ((scanFlags & SCAN_BOOTING) == 0
9721                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9722                // Check all shared libraries and map to their actual file path.
9723                // We only do this here for apps not on a system dir, because those
9724                // are the only ones that can fail an install due to this.  We
9725                // will take care of the system apps by updating all of their
9726                // library paths after the scan is done. Also during the initial
9727                // scan don't update any libs as we do this wholesale after all
9728                // apps are scanned to avoid dependency based scanning.
9729                updateSharedLibrariesLPr(pkg, null);
9730            }
9731
9732            if (mFoundPolicyFile) {
9733                SELinuxMMAC.assignSeInfoValue(pkg);
9734            }
9735            pkg.applicationInfo.uid = pkgSetting.appId;
9736            pkg.mExtras = pkgSetting;
9737
9738
9739            // Static shared libs have same package with different versions where
9740            // we internally use a synthetic package name to allow multiple versions
9741            // of the same package, therefore we need to compare signatures against
9742            // the package setting for the latest library version.
9743            PackageSetting signatureCheckPs = pkgSetting;
9744            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9745                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9746                if (libraryEntry != null) {
9747                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9748                }
9749            }
9750
9751            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9752                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9753                    // We just determined the app is signed correctly, so bring
9754                    // over the latest parsed certs.
9755                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9756                } else {
9757                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9758                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9759                                "Package " + pkg.packageName + " upgrade keys do not match the "
9760                                + "previously installed version");
9761                    } else {
9762                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9763                        String msg = "System package " + pkg.packageName
9764                                + " signature changed; retaining data.";
9765                        reportSettingsProblem(Log.WARN, msg);
9766                    }
9767                }
9768            } else {
9769                try {
9770                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9771                    verifySignaturesLP(signatureCheckPs, pkg);
9772                    // We just determined the app is signed correctly, so bring
9773                    // over the latest parsed certs.
9774                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9775                } catch (PackageManagerException e) {
9776                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9777                        throw e;
9778                    }
9779                    // The signature has changed, but this package is in the system
9780                    // image...  let's recover!
9781                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9782                    // However...  if this package is part of a shared user, but it
9783                    // doesn't match the signature of the shared user, let's fail.
9784                    // What this means is that you can't change the signatures
9785                    // associated with an overall shared user, which doesn't seem all
9786                    // that unreasonable.
9787                    if (signatureCheckPs.sharedUser != null) {
9788                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9789                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9790                            throw new PackageManagerException(
9791                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9792                                    "Signature mismatch for shared user: "
9793                                            + pkgSetting.sharedUser);
9794                        }
9795                    }
9796                    // File a report about this.
9797                    String msg = "System package " + pkg.packageName
9798                            + " signature changed; retaining data.";
9799                    reportSettingsProblem(Log.WARN, msg);
9800                }
9801            }
9802
9803            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9804                // This package wants to adopt ownership of permissions from
9805                // another package.
9806                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9807                    final String origName = pkg.mAdoptPermissions.get(i);
9808                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9809                    if (orig != null) {
9810                        if (verifyPackageUpdateLPr(orig, pkg)) {
9811                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9812                                    + pkg.packageName);
9813                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9814                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9815                        }
9816                    }
9817                }
9818            }
9819        }
9820
9821        pkg.applicationInfo.processName = fixProcessName(
9822                pkg.applicationInfo.packageName,
9823                pkg.applicationInfo.processName);
9824
9825        if (pkg != mPlatformPackage) {
9826            // Get all of our default paths setup
9827            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9828        }
9829
9830        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9831
9832        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9833            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9834                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9835                derivePackageAbi(
9836                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9837                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9838
9839                // Some system apps still use directory structure for native libraries
9840                // in which case we might end up not detecting abi solely based on apk
9841                // structure. Try to detect abi based on directory structure.
9842                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9843                        pkg.applicationInfo.primaryCpuAbi == null) {
9844                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9845                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9846                }
9847            } else {
9848                // This is not a first boot or an upgrade, don't bother deriving the
9849                // ABI during the scan. Instead, trust the value that was stored in the
9850                // package setting.
9851                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9852                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9853
9854                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9855
9856                if (DEBUG_ABI_SELECTION) {
9857                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9858                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9859                        pkg.applicationInfo.secondaryCpuAbi);
9860                }
9861            }
9862        } else {
9863            if ((scanFlags & SCAN_MOVE) != 0) {
9864                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9865                // but we already have this packages package info in the PackageSetting. We just
9866                // use that and derive the native library path based on the new codepath.
9867                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9868                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9869            }
9870
9871            // Set native library paths again. For moves, the path will be updated based on the
9872            // ABIs we've determined above. For non-moves, the path will be updated based on the
9873            // ABIs we determined during compilation, but the path will depend on the final
9874            // package path (after the rename away from the stage path).
9875            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9876        }
9877
9878        // This is a special case for the "system" package, where the ABI is
9879        // dictated by the zygote configuration (and init.rc). We should keep track
9880        // of this ABI so that we can deal with "normal" applications that run under
9881        // the same UID correctly.
9882        if (mPlatformPackage == pkg) {
9883            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9884                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9885        }
9886
9887        // If there's a mismatch between the abi-override in the package setting
9888        // and the abiOverride specified for the install. Warn about this because we
9889        // would've already compiled the app without taking the package setting into
9890        // account.
9891        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9892            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9893                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9894                        " for package " + pkg.packageName);
9895            }
9896        }
9897
9898        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9899        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9900        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9901
9902        // Copy the derived override back to the parsed package, so that we can
9903        // update the package settings accordingly.
9904        pkg.cpuAbiOverride = cpuAbiOverride;
9905
9906        if (DEBUG_ABI_SELECTION) {
9907            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9908                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9909                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9910        }
9911
9912        // Push the derived path down into PackageSettings so we know what to
9913        // clean up at uninstall time.
9914        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9915
9916        if (DEBUG_ABI_SELECTION) {
9917            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9918                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9919                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9920        }
9921
9922        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9923        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9924            // We don't do this here during boot because we can do it all
9925            // at once after scanning all existing packages.
9926            //
9927            // We also do this *before* we perform dexopt on this package, so that
9928            // we can avoid redundant dexopts, and also to make sure we've got the
9929            // code and package path correct.
9930            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9931        }
9932
9933        if (mFactoryTest && pkg.requestedPermissions.contains(
9934                android.Manifest.permission.FACTORY_TEST)) {
9935            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9936        }
9937
9938        if (isSystemApp(pkg)) {
9939            pkgSetting.isOrphaned = true;
9940        }
9941
9942        // Take care of first install / last update times.
9943        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9944        if (currentTime != 0) {
9945            if (pkgSetting.firstInstallTime == 0) {
9946                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9947            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9948                pkgSetting.lastUpdateTime = currentTime;
9949            }
9950        } else if (pkgSetting.firstInstallTime == 0) {
9951            // We need *something*.  Take time time stamp of the file.
9952            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9953        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9954            if (scanFileTime != pkgSetting.timeStamp) {
9955                // A package on the system image has changed; consider this
9956                // to be an update.
9957                pkgSetting.lastUpdateTime = scanFileTime;
9958            }
9959        }
9960        pkgSetting.setTimeStamp(scanFileTime);
9961
9962        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9963            if (nonMutatedPs != null) {
9964                synchronized (mPackages) {
9965                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9966                }
9967            }
9968        } else {
9969            final int userId = user == null ? 0 : user.getIdentifier();
9970            // Modify state for the given package setting
9971            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9972                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9973            if (pkgSetting.getInstantApp(userId)) {
9974                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9975            }
9976        }
9977        return pkg;
9978    }
9979
9980    /**
9981     * Applies policy to the parsed package based upon the given policy flags.
9982     * Ensures the package is in a good state.
9983     * <p>
9984     * Implementation detail: This method must NOT have any side effect. It would
9985     * ideally be static, but, it requires locks to read system state.
9986     */
9987    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9988        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9989            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9990            if (pkg.applicationInfo.isDirectBootAware()) {
9991                // we're direct boot aware; set for all components
9992                for (PackageParser.Service s : pkg.services) {
9993                    s.info.encryptionAware = s.info.directBootAware = true;
9994                }
9995                for (PackageParser.Provider p : pkg.providers) {
9996                    p.info.encryptionAware = p.info.directBootAware = true;
9997                }
9998                for (PackageParser.Activity a : pkg.activities) {
9999                    a.info.encryptionAware = a.info.directBootAware = true;
10000                }
10001                for (PackageParser.Activity r : pkg.receivers) {
10002                    r.info.encryptionAware = r.info.directBootAware = true;
10003                }
10004            }
10005        } else {
10006            // Only allow system apps to be flagged as core apps.
10007            pkg.coreApp = false;
10008            // clear flags not applicable to regular apps
10009            pkg.applicationInfo.privateFlags &=
10010                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10011            pkg.applicationInfo.privateFlags &=
10012                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10013        }
10014        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10015
10016        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10017            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10018        }
10019
10020        if (!isSystemApp(pkg)) {
10021            // Only system apps can use these features.
10022            pkg.mOriginalPackages = null;
10023            pkg.mRealPackage = null;
10024            pkg.mAdoptPermissions = null;
10025        }
10026    }
10027
10028    /**
10029     * Asserts the parsed package is valid according to the given policy. If the
10030     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10031     * <p>
10032     * Implementation detail: This method must NOT have any side effects. It would
10033     * ideally be static, but, it requires locks to read system state.
10034     *
10035     * @throws PackageManagerException If the package fails any of the validation checks
10036     */
10037    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10038            throws PackageManagerException {
10039        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10040            assertCodePolicy(pkg);
10041        }
10042
10043        if (pkg.applicationInfo.getCodePath() == null ||
10044                pkg.applicationInfo.getResourcePath() == null) {
10045            // Bail out. The resource and code paths haven't been set.
10046            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10047                    "Code and resource paths haven't been set correctly");
10048        }
10049
10050        // Make sure we're not adding any bogus keyset info
10051        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10052        ksms.assertScannedPackageValid(pkg);
10053
10054        synchronized (mPackages) {
10055            // The special "android" package can only be defined once
10056            if (pkg.packageName.equals("android")) {
10057                if (mAndroidApplication != null) {
10058                    Slog.w(TAG, "*************************************************");
10059                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10060                    Slog.w(TAG, " codePath=" + pkg.codePath);
10061                    Slog.w(TAG, "*************************************************");
10062                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10063                            "Core android package being redefined.  Skipping.");
10064                }
10065            }
10066
10067            // A package name must be unique; don't allow duplicates
10068            if (mPackages.containsKey(pkg.packageName)) {
10069                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10070                        "Application package " + pkg.packageName
10071                        + " already installed.  Skipping duplicate.");
10072            }
10073
10074            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10075                // Static libs have a synthetic package name containing the version
10076                // but we still want the base name to be unique.
10077                if (mPackages.containsKey(pkg.manifestPackageName)) {
10078                    throw new PackageManagerException(
10079                            "Duplicate static shared lib provider package");
10080                }
10081
10082                // Static shared libraries should have at least O target SDK
10083                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10084                    throw new PackageManagerException(
10085                            "Packages declaring static-shared libs must target O SDK or higher");
10086                }
10087
10088                // Package declaring static a shared lib cannot be instant apps
10089                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10090                    throw new PackageManagerException(
10091                            "Packages declaring static-shared libs cannot be instant apps");
10092                }
10093
10094                // Package declaring static a shared lib cannot be renamed since the package
10095                // name is synthetic and apps can't code around package manager internals.
10096                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10097                    throw new PackageManagerException(
10098                            "Packages declaring static-shared libs cannot be renamed");
10099                }
10100
10101                // Package declaring static a shared lib cannot declare child packages
10102                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10103                    throw new PackageManagerException(
10104                            "Packages declaring static-shared libs cannot have child packages");
10105                }
10106
10107                // Package declaring static a shared lib cannot declare dynamic libs
10108                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10109                    throw new PackageManagerException(
10110                            "Packages declaring static-shared libs cannot declare dynamic libs");
10111                }
10112
10113                // Package declaring static a shared lib cannot declare shared users
10114                if (pkg.mSharedUserId != null) {
10115                    throw new PackageManagerException(
10116                            "Packages declaring static-shared libs cannot declare shared users");
10117                }
10118
10119                // Static shared libs cannot declare activities
10120                if (!pkg.activities.isEmpty()) {
10121                    throw new PackageManagerException(
10122                            "Static shared libs cannot declare activities");
10123                }
10124
10125                // Static shared libs cannot declare services
10126                if (!pkg.services.isEmpty()) {
10127                    throw new PackageManagerException(
10128                            "Static shared libs cannot declare services");
10129                }
10130
10131                // Static shared libs cannot declare providers
10132                if (!pkg.providers.isEmpty()) {
10133                    throw new PackageManagerException(
10134                            "Static shared libs cannot declare content providers");
10135                }
10136
10137                // Static shared libs cannot declare receivers
10138                if (!pkg.receivers.isEmpty()) {
10139                    throw new PackageManagerException(
10140                            "Static shared libs cannot declare broadcast receivers");
10141                }
10142
10143                // Static shared libs cannot declare permission groups
10144                if (!pkg.permissionGroups.isEmpty()) {
10145                    throw new PackageManagerException(
10146                            "Static shared libs cannot declare permission groups");
10147                }
10148
10149                // Static shared libs cannot declare permissions
10150                if (!pkg.permissions.isEmpty()) {
10151                    throw new PackageManagerException(
10152                            "Static shared libs cannot declare permissions");
10153                }
10154
10155                // Static shared libs cannot declare protected broadcasts
10156                if (pkg.protectedBroadcasts != null) {
10157                    throw new PackageManagerException(
10158                            "Static shared libs cannot declare protected broadcasts");
10159                }
10160
10161                // Static shared libs cannot be overlay targets
10162                if (pkg.mOverlayTarget != null) {
10163                    throw new PackageManagerException(
10164                            "Static shared libs cannot be overlay targets");
10165                }
10166
10167                // The version codes must be ordered as lib versions
10168                int minVersionCode = Integer.MIN_VALUE;
10169                int maxVersionCode = Integer.MAX_VALUE;
10170
10171                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10172                        pkg.staticSharedLibName);
10173                if (versionedLib != null) {
10174                    final int versionCount = versionedLib.size();
10175                    for (int i = 0; i < versionCount; i++) {
10176                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10177                        // TODO: We will change version code to long, so in the new API it is long
10178                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
10179                                .getVersionCode();
10180                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10181                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10182                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10183                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10184                        } else {
10185                            minVersionCode = maxVersionCode = libVersionCode;
10186                            break;
10187                        }
10188                    }
10189                }
10190                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10191                    throw new PackageManagerException("Static shared"
10192                            + " lib version codes must be ordered as lib versions");
10193                }
10194            }
10195
10196            // Only privileged apps and updated privileged apps can add child packages.
10197            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10198                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10199                    throw new PackageManagerException("Only privileged apps can add child "
10200                            + "packages. Ignoring package " + pkg.packageName);
10201                }
10202                final int childCount = pkg.childPackages.size();
10203                for (int i = 0; i < childCount; i++) {
10204                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10205                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10206                            childPkg.packageName)) {
10207                        throw new PackageManagerException("Can't override child of "
10208                                + "another disabled app. Ignoring package " + pkg.packageName);
10209                    }
10210                }
10211            }
10212
10213            // If we're only installing presumed-existing packages, require that the
10214            // scanned APK is both already known and at the path previously established
10215            // for it.  Previously unknown packages we pick up normally, but if we have an
10216            // a priori expectation about this package's install presence, enforce it.
10217            // With a singular exception for new system packages. When an OTA contains
10218            // a new system package, we allow the codepath to change from a system location
10219            // to the user-installed location. If we don't allow this change, any newer,
10220            // user-installed version of the application will be ignored.
10221            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10222                if (mExpectingBetter.containsKey(pkg.packageName)) {
10223                    logCriticalInfo(Log.WARN,
10224                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10225                } else {
10226                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10227                    if (known != null) {
10228                        if (DEBUG_PACKAGE_SCANNING) {
10229                            Log.d(TAG, "Examining " + pkg.codePath
10230                                    + " and requiring known paths " + known.codePathString
10231                                    + " & " + known.resourcePathString);
10232                        }
10233                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10234                                || !pkg.applicationInfo.getResourcePath().equals(
10235                                        known.resourcePathString)) {
10236                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10237                                    "Application package " + pkg.packageName
10238                                    + " found at " + pkg.applicationInfo.getCodePath()
10239                                    + " but expected at " + known.codePathString
10240                                    + "; ignoring.");
10241                        }
10242                    }
10243                }
10244            }
10245
10246            // Verify that this new package doesn't have any content providers
10247            // that conflict with existing packages.  Only do this if the
10248            // package isn't already installed, since we don't want to break
10249            // things that are installed.
10250            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10251                final int N = pkg.providers.size();
10252                int i;
10253                for (i=0; i<N; i++) {
10254                    PackageParser.Provider p = pkg.providers.get(i);
10255                    if (p.info.authority != null) {
10256                        String names[] = p.info.authority.split(";");
10257                        for (int j = 0; j < names.length; j++) {
10258                            if (mProvidersByAuthority.containsKey(names[j])) {
10259                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10260                                final String otherPackageName =
10261                                        ((other != null && other.getComponentName() != null) ?
10262                                                other.getComponentName().getPackageName() : "?");
10263                                throw new PackageManagerException(
10264                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10265                                        "Can't install because provider name " + names[j]
10266                                                + " (in package " + pkg.applicationInfo.packageName
10267                                                + ") is already used by " + otherPackageName);
10268                            }
10269                        }
10270                    }
10271                }
10272            }
10273        }
10274    }
10275
10276    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10277            int type, String declaringPackageName, int declaringVersionCode) {
10278        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10279        if (versionedLib == null) {
10280            versionedLib = new SparseArray<>();
10281            mSharedLibraries.put(name, versionedLib);
10282            if (type == SharedLibraryInfo.TYPE_STATIC) {
10283                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10284            }
10285        } else if (versionedLib.indexOfKey(version) >= 0) {
10286            return false;
10287        }
10288        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10289                version, type, declaringPackageName, declaringVersionCode);
10290        versionedLib.put(version, libEntry);
10291        return true;
10292    }
10293
10294    private boolean removeSharedLibraryLPw(String name, int version) {
10295        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10296        if (versionedLib == null) {
10297            return false;
10298        }
10299        final int libIdx = versionedLib.indexOfKey(version);
10300        if (libIdx < 0) {
10301            return false;
10302        }
10303        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10304        versionedLib.remove(version);
10305        if (versionedLib.size() <= 0) {
10306            mSharedLibraries.remove(name);
10307            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10308                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10309                        .getPackageName());
10310            }
10311        }
10312        return true;
10313    }
10314
10315    /**
10316     * Adds a scanned package to the system. When this method is finished, the package will
10317     * be available for query, resolution, etc...
10318     */
10319    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10320            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10321        final String pkgName = pkg.packageName;
10322        if (mCustomResolverComponentName != null &&
10323                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10324            setUpCustomResolverActivity(pkg);
10325        }
10326
10327        if (pkg.packageName.equals("android")) {
10328            synchronized (mPackages) {
10329                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10330                    // Set up information for our fall-back user intent resolution activity.
10331                    mPlatformPackage = pkg;
10332                    pkg.mVersionCode = mSdkVersion;
10333                    mAndroidApplication = pkg.applicationInfo;
10334                    if (!mResolverReplaced) {
10335                        mResolveActivity.applicationInfo = mAndroidApplication;
10336                        mResolveActivity.name = ResolverActivity.class.getName();
10337                        mResolveActivity.packageName = mAndroidApplication.packageName;
10338                        mResolveActivity.processName = "system:ui";
10339                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10340                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10341                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10342                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10343                        mResolveActivity.exported = true;
10344                        mResolveActivity.enabled = true;
10345                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10346                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10347                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10348                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10349                                | ActivityInfo.CONFIG_ORIENTATION
10350                                | ActivityInfo.CONFIG_KEYBOARD
10351                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10352                        mResolveInfo.activityInfo = mResolveActivity;
10353                        mResolveInfo.priority = 0;
10354                        mResolveInfo.preferredOrder = 0;
10355                        mResolveInfo.match = 0;
10356                        mResolveComponentName = new ComponentName(
10357                                mAndroidApplication.packageName, mResolveActivity.name);
10358                    }
10359                }
10360            }
10361        }
10362
10363        ArrayList<PackageParser.Package> clientLibPkgs = null;
10364        // writer
10365        synchronized (mPackages) {
10366            boolean hasStaticSharedLibs = false;
10367
10368            // Any app can add new static shared libraries
10369            if (pkg.staticSharedLibName != null) {
10370                // Static shared libs don't allow renaming as they have synthetic package
10371                // names to allow install of multiple versions, so use name from manifest.
10372                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10373                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10374                        pkg.manifestPackageName, pkg.mVersionCode)) {
10375                    hasStaticSharedLibs = true;
10376                } else {
10377                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10378                                + pkg.staticSharedLibName + " already exists; skipping");
10379                }
10380                // Static shared libs cannot be updated once installed since they
10381                // use synthetic package name which includes the version code, so
10382                // not need to update other packages's shared lib dependencies.
10383            }
10384
10385            if (!hasStaticSharedLibs
10386                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10387                // Only system apps can add new dynamic shared libraries.
10388                if (pkg.libraryNames != null) {
10389                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10390                        String name = pkg.libraryNames.get(i);
10391                        boolean allowed = false;
10392                        if (pkg.isUpdatedSystemApp()) {
10393                            // New library entries can only be added through the
10394                            // system image.  This is important to get rid of a lot
10395                            // of nasty edge cases: for example if we allowed a non-
10396                            // system update of the app to add a library, then uninstalling
10397                            // the update would make the library go away, and assumptions
10398                            // we made such as through app install filtering would now
10399                            // have allowed apps on the device which aren't compatible
10400                            // with it.  Better to just have the restriction here, be
10401                            // conservative, and create many fewer cases that can negatively
10402                            // impact the user experience.
10403                            final PackageSetting sysPs = mSettings
10404                                    .getDisabledSystemPkgLPr(pkg.packageName);
10405                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10406                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10407                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10408                                        allowed = true;
10409                                        break;
10410                                    }
10411                                }
10412                            }
10413                        } else {
10414                            allowed = true;
10415                        }
10416                        if (allowed) {
10417                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10418                                    SharedLibraryInfo.VERSION_UNDEFINED,
10419                                    SharedLibraryInfo.TYPE_DYNAMIC,
10420                                    pkg.packageName, pkg.mVersionCode)) {
10421                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10422                                        + name + " already exists; skipping");
10423                            }
10424                        } else {
10425                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10426                                    + name + " that is not declared on system image; skipping");
10427                        }
10428                    }
10429
10430                    if ((scanFlags & SCAN_BOOTING) == 0) {
10431                        // If we are not booting, we need to update any applications
10432                        // that are clients of our shared library.  If we are booting,
10433                        // this will all be done once the scan is complete.
10434                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10435                    }
10436                }
10437            }
10438        }
10439
10440        if ((scanFlags & SCAN_BOOTING) != 0) {
10441            // No apps can run during boot scan, so they don't need to be frozen
10442        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10443            // Caller asked to not kill app, so it's probably not frozen
10444        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10445            // Caller asked us to ignore frozen check for some reason; they
10446            // probably didn't know the package name
10447        } else {
10448            // We're doing major surgery on this package, so it better be frozen
10449            // right now to keep it from launching
10450            checkPackageFrozen(pkgName);
10451        }
10452
10453        // Also need to kill any apps that are dependent on the library.
10454        if (clientLibPkgs != null) {
10455            for (int i=0; i<clientLibPkgs.size(); i++) {
10456                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10457                killApplication(clientPkg.applicationInfo.packageName,
10458                        clientPkg.applicationInfo.uid, "update lib");
10459            }
10460        }
10461
10462        // writer
10463        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10464
10465        synchronized (mPackages) {
10466            // We don't expect installation to fail beyond this point
10467
10468            // Add the new setting to mSettings
10469            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10470            // Add the new setting to mPackages
10471            mPackages.put(pkg.applicationInfo.packageName, pkg);
10472            // Make sure we don't accidentally delete its data.
10473            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10474            while (iter.hasNext()) {
10475                PackageCleanItem item = iter.next();
10476                if (pkgName.equals(item.packageName)) {
10477                    iter.remove();
10478                }
10479            }
10480
10481            // Add the package's KeySets to the global KeySetManagerService
10482            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10483            ksms.addScannedPackageLPw(pkg);
10484
10485            int N = pkg.providers.size();
10486            StringBuilder r = null;
10487            int i;
10488            for (i=0; i<N; i++) {
10489                PackageParser.Provider p = pkg.providers.get(i);
10490                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10491                        p.info.processName);
10492                mProviders.addProvider(p);
10493                p.syncable = p.info.isSyncable;
10494                if (p.info.authority != null) {
10495                    String names[] = p.info.authority.split(";");
10496                    p.info.authority = null;
10497                    for (int j = 0; j < names.length; j++) {
10498                        if (j == 1 && p.syncable) {
10499                            // We only want the first authority for a provider to possibly be
10500                            // syncable, so if we already added this provider using a different
10501                            // authority clear the syncable flag. We copy the provider before
10502                            // changing it because the mProviders object contains a reference
10503                            // to a provider that we don't want to change.
10504                            // Only do this for the second authority since the resulting provider
10505                            // object can be the same for all future authorities for this provider.
10506                            p = new PackageParser.Provider(p);
10507                            p.syncable = false;
10508                        }
10509                        if (!mProvidersByAuthority.containsKey(names[j])) {
10510                            mProvidersByAuthority.put(names[j], p);
10511                            if (p.info.authority == null) {
10512                                p.info.authority = names[j];
10513                            } else {
10514                                p.info.authority = p.info.authority + ";" + names[j];
10515                            }
10516                            if (DEBUG_PACKAGE_SCANNING) {
10517                                if (chatty)
10518                                    Log.d(TAG, "Registered content provider: " + names[j]
10519                                            + ", className = " + p.info.name + ", isSyncable = "
10520                                            + p.info.isSyncable);
10521                            }
10522                        } else {
10523                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10524                            Slog.w(TAG, "Skipping provider name " + names[j] +
10525                                    " (in package " + pkg.applicationInfo.packageName +
10526                                    "): name already used by "
10527                                    + ((other != null && other.getComponentName() != null)
10528                                            ? other.getComponentName().getPackageName() : "?"));
10529                        }
10530                    }
10531                }
10532                if (chatty) {
10533                    if (r == null) {
10534                        r = new StringBuilder(256);
10535                    } else {
10536                        r.append(' ');
10537                    }
10538                    r.append(p.info.name);
10539                }
10540            }
10541            if (r != null) {
10542                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10543            }
10544
10545            N = pkg.services.size();
10546            r = null;
10547            for (i=0; i<N; i++) {
10548                PackageParser.Service s = pkg.services.get(i);
10549                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10550                        s.info.processName);
10551                mServices.addService(s);
10552                if (chatty) {
10553                    if (r == null) {
10554                        r = new StringBuilder(256);
10555                    } else {
10556                        r.append(' ');
10557                    }
10558                    r.append(s.info.name);
10559                }
10560            }
10561            if (r != null) {
10562                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10563            }
10564
10565            N = pkg.receivers.size();
10566            r = null;
10567            for (i=0; i<N; i++) {
10568                PackageParser.Activity a = pkg.receivers.get(i);
10569                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10570                        a.info.processName);
10571                mReceivers.addActivity(a, "receiver");
10572                if (chatty) {
10573                    if (r == null) {
10574                        r = new StringBuilder(256);
10575                    } else {
10576                        r.append(' ');
10577                    }
10578                    r.append(a.info.name);
10579                }
10580            }
10581            if (r != null) {
10582                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10583            }
10584
10585            N = pkg.activities.size();
10586            r = null;
10587            for (i=0; i<N; i++) {
10588                PackageParser.Activity a = pkg.activities.get(i);
10589                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10590                        a.info.processName);
10591                mActivities.addActivity(a, "activity");
10592                if (chatty) {
10593                    if (r == null) {
10594                        r = new StringBuilder(256);
10595                    } else {
10596                        r.append(' ');
10597                    }
10598                    r.append(a.info.name);
10599                }
10600            }
10601            if (r != null) {
10602                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10603            }
10604
10605            N = pkg.permissionGroups.size();
10606            r = null;
10607            for (i=0; i<N; i++) {
10608                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10609                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10610                final String curPackageName = cur == null ? null : cur.info.packageName;
10611                // Dont allow ephemeral apps to define new permission groups.
10612                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10613                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10614                            + pg.info.packageName
10615                            + " ignored: instant apps cannot define new permission groups.");
10616                    continue;
10617                }
10618                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10619                if (cur == null || isPackageUpdate) {
10620                    mPermissionGroups.put(pg.info.name, pg);
10621                    if (chatty) {
10622                        if (r == null) {
10623                            r = new StringBuilder(256);
10624                        } else {
10625                            r.append(' ');
10626                        }
10627                        if (isPackageUpdate) {
10628                            r.append("UPD:");
10629                        }
10630                        r.append(pg.info.name);
10631                    }
10632                } else {
10633                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10634                            + pg.info.packageName + " ignored: original from "
10635                            + cur.info.packageName);
10636                    if (chatty) {
10637                        if (r == null) {
10638                            r = new StringBuilder(256);
10639                        } else {
10640                            r.append(' ');
10641                        }
10642                        r.append("DUP:");
10643                        r.append(pg.info.name);
10644                    }
10645                }
10646            }
10647            if (r != null) {
10648                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10649            }
10650
10651            N = pkg.permissions.size();
10652            r = null;
10653            for (i=0; i<N; i++) {
10654                PackageParser.Permission p = pkg.permissions.get(i);
10655
10656                // Dont allow ephemeral apps to define new permissions.
10657                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10658                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10659                            + p.info.packageName
10660                            + " ignored: instant apps cannot define new permissions.");
10661                    continue;
10662                }
10663
10664                // Assume by default that we did not install this permission into the system.
10665                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10666
10667                // Now that permission groups have a special meaning, we ignore permission
10668                // groups for legacy apps to prevent unexpected behavior. In particular,
10669                // permissions for one app being granted to someone just becase they happen
10670                // to be in a group defined by another app (before this had no implications).
10671                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10672                    p.group = mPermissionGroups.get(p.info.group);
10673                    // Warn for a permission in an unknown group.
10674                    if (p.info.group != null && p.group == null) {
10675                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10676                                + p.info.packageName + " in an unknown group " + p.info.group);
10677                    }
10678                }
10679
10680                ArrayMap<String, BasePermission> permissionMap =
10681                        p.tree ? mSettings.mPermissionTrees
10682                                : mSettings.mPermissions;
10683                BasePermission bp = permissionMap.get(p.info.name);
10684
10685                // Allow system apps to redefine non-system permissions
10686                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10687                    final boolean currentOwnerIsSystem = (bp.perm != null
10688                            && isSystemApp(bp.perm.owner));
10689                    if (isSystemApp(p.owner)) {
10690                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10691                            // It's a built-in permission and no owner, take ownership now
10692                            bp.packageSetting = pkgSetting;
10693                            bp.perm = p;
10694                            bp.uid = pkg.applicationInfo.uid;
10695                            bp.sourcePackage = p.info.packageName;
10696                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10697                        } else if (!currentOwnerIsSystem) {
10698                            String msg = "New decl " + p.owner + " of permission  "
10699                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10700                            reportSettingsProblem(Log.WARN, msg);
10701                            bp = null;
10702                        }
10703                    }
10704                }
10705
10706                if (bp == null) {
10707                    bp = new BasePermission(p.info.name, p.info.packageName,
10708                            BasePermission.TYPE_NORMAL);
10709                    permissionMap.put(p.info.name, bp);
10710                }
10711
10712                if (bp.perm == null) {
10713                    if (bp.sourcePackage == null
10714                            || bp.sourcePackage.equals(p.info.packageName)) {
10715                        BasePermission tree = findPermissionTreeLP(p.info.name);
10716                        if (tree == null
10717                                || tree.sourcePackage.equals(p.info.packageName)) {
10718                            bp.packageSetting = pkgSetting;
10719                            bp.perm = p;
10720                            bp.uid = pkg.applicationInfo.uid;
10721                            bp.sourcePackage = p.info.packageName;
10722                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10723                            if (chatty) {
10724                                if (r == null) {
10725                                    r = new StringBuilder(256);
10726                                } else {
10727                                    r.append(' ');
10728                                }
10729                                r.append(p.info.name);
10730                            }
10731                        } else {
10732                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10733                                    + p.info.packageName + " ignored: base tree "
10734                                    + tree.name + " is from package "
10735                                    + tree.sourcePackage);
10736                        }
10737                    } else {
10738                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10739                                + p.info.packageName + " ignored: original from "
10740                                + bp.sourcePackage);
10741                    }
10742                } else if (chatty) {
10743                    if (r == null) {
10744                        r = new StringBuilder(256);
10745                    } else {
10746                        r.append(' ');
10747                    }
10748                    r.append("DUP:");
10749                    r.append(p.info.name);
10750                }
10751                if (bp.perm == p) {
10752                    bp.protectionLevel = p.info.protectionLevel;
10753                }
10754            }
10755
10756            if (r != null) {
10757                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10758            }
10759
10760            N = pkg.instrumentation.size();
10761            r = null;
10762            for (i=0; i<N; i++) {
10763                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10764                a.info.packageName = pkg.applicationInfo.packageName;
10765                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10766                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10767                a.info.splitNames = pkg.splitNames;
10768                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10769                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10770                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10771                a.info.dataDir = pkg.applicationInfo.dataDir;
10772                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10773                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10774                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10775                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10776                mInstrumentation.put(a.getComponentName(), a);
10777                if (chatty) {
10778                    if (r == null) {
10779                        r = new StringBuilder(256);
10780                    } else {
10781                        r.append(' ');
10782                    }
10783                    r.append(a.info.name);
10784                }
10785            }
10786            if (r != null) {
10787                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10788            }
10789
10790            if (pkg.protectedBroadcasts != null) {
10791                N = pkg.protectedBroadcasts.size();
10792                for (i=0; i<N; i++) {
10793                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10794                }
10795            }
10796        }
10797
10798        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10799    }
10800
10801    /**
10802     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10803     * is derived purely on the basis of the contents of {@code scanFile} and
10804     * {@code cpuAbiOverride}.
10805     *
10806     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10807     */
10808    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10809                                 String cpuAbiOverride, boolean extractLibs,
10810                                 File appLib32InstallDir)
10811            throws PackageManagerException {
10812        // Give ourselves some initial paths; we'll come back for another
10813        // pass once we've determined ABI below.
10814        setNativeLibraryPaths(pkg, appLib32InstallDir);
10815
10816        // We would never need to extract libs for forward-locked and external packages,
10817        // since the container service will do it for us. We shouldn't attempt to
10818        // extract libs from system app when it was not updated.
10819        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10820                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10821            extractLibs = false;
10822        }
10823
10824        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10825        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10826
10827        NativeLibraryHelper.Handle handle = null;
10828        try {
10829            handle = NativeLibraryHelper.Handle.create(pkg);
10830            // TODO(multiArch): This can be null for apps that didn't go through the
10831            // usual installation process. We can calculate it again, like we
10832            // do during install time.
10833            //
10834            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10835            // unnecessary.
10836            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10837
10838            // Null out the abis so that they can be recalculated.
10839            pkg.applicationInfo.primaryCpuAbi = null;
10840            pkg.applicationInfo.secondaryCpuAbi = null;
10841            if (isMultiArch(pkg.applicationInfo)) {
10842                // Warn if we've set an abiOverride for multi-lib packages..
10843                // By definition, we need to copy both 32 and 64 bit libraries for
10844                // such packages.
10845                if (pkg.cpuAbiOverride != null
10846                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10847                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10848                }
10849
10850                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10851                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10852                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10853                    if (extractLibs) {
10854                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10855                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10856                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10857                                useIsaSpecificSubdirs);
10858                    } else {
10859                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10860                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10861                    }
10862                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10863                }
10864
10865                maybeThrowExceptionForMultiArchCopy(
10866                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10867
10868                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10869                    if (extractLibs) {
10870                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10871                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10872                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10873                                useIsaSpecificSubdirs);
10874                    } else {
10875                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10876                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10877                    }
10878                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10879                }
10880
10881                maybeThrowExceptionForMultiArchCopy(
10882                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10883
10884                if (abi64 >= 0) {
10885                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10886                }
10887
10888                if (abi32 >= 0) {
10889                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10890                    if (abi64 >= 0) {
10891                        if (pkg.use32bitAbi) {
10892                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10893                            pkg.applicationInfo.primaryCpuAbi = abi;
10894                        } else {
10895                            pkg.applicationInfo.secondaryCpuAbi = abi;
10896                        }
10897                    } else {
10898                        pkg.applicationInfo.primaryCpuAbi = abi;
10899                    }
10900                }
10901
10902            } else {
10903                String[] abiList = (cpuAbiOverride != null) ?
10904                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10905
10906                // Enable gross and lame hacks for apps that are built with old
10907                // SDK tools. We must scan their APKs for renderscript bitcode and
10908                // not launch them if it's present. Don't bother checking on devices
10909                // that don't have 64 bit support.
10910                boolean needsRenderScriptOverride = false;
10911                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10912                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10913                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10914                    needsRenderScriptOverride = true;
10915                }
10916
10917                final int copyRet;
10918                if (extractLibs) {
10919                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10920                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10921                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10922                } else {
10923                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10924                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10925                }
10926                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10927
10928                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10929                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10930                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10931                }
10932
10933                if (copyRet >= 0) {
10934                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10935                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10936                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10937                } else if (needsRenderScriptOverride) {
10938                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10939                }
10940            }
10941        } catch (IOException ioe) {
10942            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10943        } finally {
10944            IoUtils.closeQuietly(handle);
10945        }
10946
10947        // Now that we've calculated the ABIs and determined if it's an internal app,
10948        // we will go ahead and populate the nativeLibraryPath.
10949        setNativeLibraryPaths(pkg, appLib32InstallDir);
10950    }
10951
10952    /**
10953     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10954     * i.e, so that all packages can be run inside a single process if required.
10955     *
10956     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10957     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10958     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10959     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10960     * updating a package that belongs to a shared user.
10961     *
10962     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10963     * adds unnecessary complexity.
10964     */
10965    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10966            PackageParser.Package scannedPackage) {
10967        String requiredInstructionSet = null;
10968        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10969            requiredInstructionSet = VMRuntime.getInstructionSet(
10970                     scannedPackage.applicationInfo.primaryCpuAbi);
10971        }
10972
10973        PackageSetting requirer = null;
10974        for (PackageSetting ps : packagesForUser) {
10975            // If packagesForUser contains scannedPackage, we skip it. This will happen
10976            // when scannedPackage is an update of an existing package. Without this check,
10977            // we will never be able to change the ABI of any package belonging to a shared
10978            // user, even if it's compatible with other packages.
10979            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10980                if (ps.primaryCpuAbiString == null) {
10981                    continue;
10982                }
10983
10984                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10985                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10986                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10987                    // this but there's not much we can do.
10988                    String errorMessage = "Instruction set mismatch, "
10989                            + ((requirer == null) ? "[caller]" : requirer)
10990                            + " requires " + requiredInstructionSet + " whereas " + ps
10991                            + " requires " + instructionSet;
10992                    Slog.w(TAG, errorMessage);
10993                }
10994
10995                if (requiredInstructionSet == null) {
10996                    requiredInstructionSet = instructionSet;
10997                    requirer = ps;
10998                }
10999            }
11000        }
11001
11002        if (requiredInstructionSet != null) {
11003            String adjustedAbi;
11004            if (requirer != null) {
11005                // requirer != null implies that either scannedPackage was null or that scannedPackage
11006                // did not require an ABI, in which case we have to adjust scannedPackage to match
11007                // the ABI of the set (which is the same as requirer's ABI)
11008                adjustedAbi = requirer.primaryCpuAbiString;
11009                if (scannedPackage != null) {
11010                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11011                }
11012            } else {
11013                // requirer == null implies that we're updating all ABIs in the set to
11014                // match scannedPackage.
11015                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11016            }
11017
11018            for (PackageSetting ps : packagesForUser) {
11019                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11020                    if (ps.primaryCpuAbiString != null) {
11021                        continue;
11022                    }
11023
11024                    ps.primaryCpuAbiString = adjustedAbi;
11025                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11026                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11027                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11028                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11029                                + " (requirer="
11030                                + (requirer != null ? requirer.pkg : "null")
11031                                + ", scannedPackage="
11032                                + (scannedPackage != null ? scannedPackage : "null")
11033                                + ")");
11034                        try {
11035                            mInstaller.rmdex(ps.codePathString,
11036                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11037                        } catch (InstallerException ignored) {
11038                        }
11039                    }
11040                }
11041            }
11042        }
11043    }
11044
11045    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11046        synchronized (mPackages) {
11047            mResolverReplaced = true;
11048            // Set up information for custom user intent resolution activity.
11049            mResolveActivity.applicationInfo = pkg.applicationInfo;
11050            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11051            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11052            mResolveActivity.processName = pkg.applicationInfo.packageName;
11053            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11054            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11055                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11056            mResolveActivity.theme = 0;
11057            mResolveActivity.exported = true;
11058            mResolveActivity.enabled = true;
11059            mResolveInfo.activityInfo = mResolveActivity;
11060            mResolveInfo.priority = 0;
11061            mResolveInfo.preferredOrder = 0;
11062            mResolveInfo.match = 0;
11063            mResolveComponentName = mCustomResolverComponentName;
11064            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11065                    mResolveComponentName);
11066        }
11067    }
11068
11069    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11070        if (installerActivity == null) {
11071            if (DEBUG_EPHEMERAL) {
11072                Slog.d(TAG, "Clear ephemeral installer activity");
11073            }
11074            mInstantAppInstallerActivity = null;
11075            return;
11076        }
11077
11078        if (DEBUG_EPHEMERAL) {
11079            Slog.d(TAG, "Set ephemeral installer activity: "
11080                    + installerActivity.getComponentName());
11081        }
11082        // Set up information for ephemeral installer activity
11083        mInstantAppInstallerActivity = installerActivity;
11084        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11085                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11086        mInstantAppInstallerActivity.exported = true;
11087        mInstantAppInstallerActivity.enabled = true;
11088        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11089        mInstantAppInstallerInfo.priority = 0;
11090        mInstantAppInstallerInfo.preferredOrder = 1;
11091        mInstantAppInstallerInfo.isDefault = true;
11092        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11093                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11094    }
11095
11096    private static String calculateBundledApkRoot(final String codePathString) {
11097        final File codePath = new File(codePathString);
11098        final File codeRoot;
11099        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11100            codeRoot = Environment.getRootDirectory();
11101        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11102            codeRoot = Environment.getOemDirectory();
11103        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11104            codeRoot = Environment.getVendorDirectory();
11105        } else {
11106            // Unrecognized code path; take its top real segment as the apk root:
11107            // e.g. /something/app/blah.apk => /something
11108            try {
11109                File f = codePath.getCanonicalFile();
11110                File parent = f.getParentFile();    // non-null because codePath is a file
11111                File tmp;
11112                while ((tmp = parent.getParentFile()) != null) {
11113                    f = parent;
11114                    parent = tmp;
11115                }
11116                codeRoot = f;
11117                Slog.w(TAG, "Unrecognized code path "
11118                        + codePath + " - using " + codeRoot);
11119            } catch (IOException e) {
11120                // Can't canonicalize the code path -- shenanigans?
11121                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11122                return Environment.getRootDirectory().getPath();
11123            }
11124        }
11125        return codeRoot.getPath();
11126    }
11127
11128    /**
11129     * Derive and set the location of native libraries for the given package,
11130     * which varies depending on where and how the package was installed.
11131     */
11132    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11133        final ApplicationInfo info = pkg.applicationInfo;
11134        final String codePath = pkg.codePath;
11135        final File codeFile = new File(codePath);
11136        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11137        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11138
11139        info.nativeLibraryRootDir = null;
11140        info.nativeLibraryRootRequiresIsa = false;
11141        info.nativeLibraryDir = null;
11142        info.secondaryNativeLibraryDir = null;
11143
11144        if (isApkFile(codeFile)) {
11145            // Monolithic install
11146            if (bundledApp) {
11147                // If "/system/lib64/apkname" exists, assume that is the per-package
11148                // native library directory to use; otherwise use "/system/lib/apkname".
11149                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11150                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11151                        getPrimaryInstructionSet(info));
11152
11153                // This is a bundled system app so choose the path based on the ABI.
11154                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11155                // is just the default path.
11156                final String apkName = deriveCodePathName(codePath);
11157                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11158                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11159                        apkName).getAbsolutePath();
11160
11161                if (info.secondaryCpuAbi != null) {
11162                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11163                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11164                            secondaryLibDir, apkName).getAbsolutePath();
11165                }
11166            } else if (asecApp) {
11167                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11168                        .getAbsolutePath();
11169            } else {
11170                final String apkName = deriveCodePathName(codePath);
11171                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11172                        .getAbsolutePath();
11173            }
11174
11175            info.nativeLibraryRootRequiresIsa = false;
11176            info.nativeLibraryDir = info.nativeLibraryRootDir;
11177        } else {
11178            // Cluster install
11179            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11180            info.nativeLibraryRootRequiresIsa = true;
11181
11182            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11183                    getPrimaryInstructionSet(info)).getAbsolutePath();
11184
11185            if (info.secondaryCpuAbi != null) {
11186                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11187                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11188            }
11189        }
11190    }
11191
11192    /**
11193     * Calculate the abis and roots for a bundled app. These can uniquely
11194     * be determined from the contents of the system partition, i.e whether
11195     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11196     * of this information, and instead assume that the system was built
11197     * sensibly.
11198     */
11199    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11200                                           PackageSetting pkgSetting) {
11201        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11202
11203        // If "/system/lib64/apkname" exists, assume that is the per-package
11204        // native library directory to use; otherwise use "/system/lib/apkname".
11205        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11206        setBundledAppAbi(pkg, apkRoot, apkName);
11207        // pkgSetting might be null during rescan following uninstall of updates
11208        // to a bundled app, so accommodate that possibility.  The settings in
11209        // that case will be established later from the parsed package.
11210        //
11211        // If the settings aren't null, sync them up with what we've just derived.
11212        // note that apkRoot isn't stored in the package settings.
11213        if (pkgSetting != null) {
11214            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11215            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11216        }
11217    }
11218
11219    /**
11220     * Deduces the ABI of a bundled app and sets the relevant fields on the
11221     * parsed pkg object.
11222     *
11223     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11224     *        under which system libraries are installed.
11225     * @param apkName the name of the installed package.
11226     */
11227    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11228        final File codeFile = new File(pkg.codePath);
11229
11230        final boolean has64BitLibs;
11231        final boolean has32BitLibs;
11232        if (isApkFile(codeFile)) {
11233            // Monolithic install
11234            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11235            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11236        } else {
11237            // Cluster install
11238            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11239            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11240                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11241                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11242                has64BitLibs = (new File(rootDir, isa)).exists();
11243            } else {
11244                has64BitLibs = false;
11245            }
11246            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11247                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11248                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11249                has32BitLibs = (new File(rootDir, isa)).exists();
11250            } else {
11251                has32BitLibs = false;
11252            }
11253        }
11254
11255        if (has64BitLibs && !has32BitLibs) {
11256            // The package has 64 bit libs, but not 32 bit libs. Its primary
11257            // ABI should be 64 bit. We can safely assume here that the bundled
11258            // native libraries correspond to the most preferred ABI in the list.
11259
11260            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11261            pkg.applicationInfo.secondaryCpuAbi = null;
11262        } else if (has32BitLibs && !has64BitLibs) {
11263            // The package has 32 bit libs but not 64 bit libs. Its primary
11264            // ABI should be 32 bit.
11265
11266            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11267            pkg.applicationInfo.secondaryCpuAbi = null;
11268        } else if (has32BitLibs && has64BitLibs) {
11269            // The application has both 64 and 32 bit bundled libraries. We check
11270            // here that the app declares multiArch support, and warn if it doesn't.
11271            //
11272            // We will be lenient here and record both ABIs. The primary will be the
11273            // ABI that's higher on the list, i.e, a device that's configured to prefer
11274            // 64 bit apps will see a 64 bit primary ABI,
11275
11276            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11277                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11278            }
11279
11280            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11281                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11282                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11283            } else {
11284                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11285                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11286            }
11287        } else {
11288            pkg.applicationInfo.primaryCpuAbi = null;
11289            pkg.applicationInfo.secondaryCpuAbi = null;
11290        }
11291    }
11292
11293    private void killApplication(String pkgName, int appId, String reason) {
11294        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11295    }
11296
11297    private void killApplication(String pkgName, int appId, int userId, String reason) {
11298        // Request the ActivityManager to kill the process(only for existing packages)
11299        // so that we do not end up in a confused state while the user is still using the older
11300        // version of the application while the new one gets installed.
11301        final long token = Binder.clearCallingIdentity();
11302        try {
11303            IActivityManager am = ActivityManager.getService();
11304            if (am != null) {
11305                try {
11306                    am.killApplication(pkgName, appId, userId, reason);
11307                } catch (RemoteException e) {
11308                }
11309            }
11310        } finally {
11311            Binder.restoreCallingIdentity(token);
11312        }
11313    }
11314
11315    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11316        // Remove the parent package setting
11317        PackageSetting ps = (PackageSetting) pkg.mExtras;
11318        if (ps != null) {
11319            removePackageLI(ps, chatty);
11320        }
11321        // Remove the child package setting
11322        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11323        for (int i = 0; i < childCount; i++) {
11324            PackageParser.Package childPkg = pkg.childPackages.get(i);
11325            ps = (PackageSetting) childPkg.mExtras;
11326            if (ps != null) {
11327                removePackageLI(ps, chatty);
11328            }
11329        }
11330    }
11331
11332    void removePackageLI(PackageSetting ps, boolean chatty) {
11333        if (DEBUG_INSTALL) {
11334            if (chatty)
11335                Log.d(TAG, "Removing package " + ps.name);
11336        }
11337
11338        // writer
11339        synchronized (mPackages) {
11340            mPackages.remove(ps.name);
11341            final PackageParser.Package pkg = ps.pkg;
11342            if (pkg != null) {
11343                cleanPackageDataStructuresLILPw(pkg, chatty);
11344            }
11345        }
11346    }
11347
11348    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11349        if (DEBUG_INSTALL) {
11350            if (chatty)
11351                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11352        }
11353
11354        // writer
11355        synchronized (mPackages) {
11356            // Remove the parent package
11357            mPackages.remove(pkg.applicationInfo.packageName);
11358            cleanPackageDataStructuresLILPw(pkg, chatty);
11359
11360            // Remove the child packages
11361            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11362            for (int i = 0; i < childCount; i++) {
11363                PackageParser.Package childPkg = pkg.childPackages.get(i);
11364                mPackages.remove(childPkg.applicationInfo.packageName);
11365                cleanPackageDataStructuresLILPw(childPkg, chatty);
11366            }
11367        }
11368    }
11369
11370    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11371        int N = pkg.providers.size();
11372        StringBuilder r = null;
11373        int i;
11374        for (i=0; i<N; i++) {
11375            PackageParser.Provider p = pkg.providers.get(i);
11376            mProviders.removeProvider(p);
11377            if (p.info.authority == null) {
11378
11379                /* There was another ContentProvider with this authority when
11380                 * this app was installed so this authority is null,
11381                 * Ignore it as we don't have to unregister the provider.
11382                 */
11383                continue;
11384            }
11385            String names[] = p.info.authority.split(";");
11386            for (int j = 0; j < names.length; j++) {
11387                if (mProvidersByAuthority.get(names[j]) == p) {
11388                    mProvidersByAuthority.remove(names[j]);
11389                    if (DEBUG_REMOVE) {
11390                        if (chatty)
11391                            Log.d(TAG, "Unregistered content provider: " + names[j]
11392                                    + ", className = " + p.info.name + ", isSyncable = "
11393                                    + p.info.isSyncable);
11394                    }
11395                }
11396            }
11397            if (DEBUG_REMOVE && chatty) {
11398                if (r == null) {
11399                    r = new StringBuilder(256);
11400                } else {
11401                    r.append(' ');
11402                }
11403                r.append(p.info.name);
11404            }
11405        }
11406        if (r != null) {
11407            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11408        }
11409
11410        N = pkg.services.size();
11411        r = null;
11412        for (i=0; i<N; i++) {
11413            PackageParser.Service s = pkg.services.get(i);
11414            mServices.removeService(s);
11415            if (chatty) {
11416                if (r == null) {
11417                    r = new StringBuilder(256);
11418                } else {
11419                    r.append(' ');
11420                }
11421                r.append(s.info.name);
11422            }
11423        }
11424        if (r != null) {
11425            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11426        }
11427
11428        N = pkg.receivers.size();
11429        r = null;
11430        for (i=0; i<N; i++) {
11431            PackageParser.Activity a = pkg.receivers.get(i);
11432            mReceivers.removeActivity(a, "receiver");
11433            if (DEBUG_REMOVE && chatty) {
11434                if (r == null) {
11435                    r = new StringBuilder(256);
11436                } else {
11437                    r.append(' ');
11438                }
11439                r.append(a.info.name);
11440            }
11441        }
11442        if (r != null) {
11443            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11444        }
11445
11446        N = pkg.activities.size();
11447        r = null;
11448        for (i=0; i<N; i++) {
11449            PackageParser.Activity a = pkg.activities.get(i);
11450            mActivities.removeActivity(a, "activity");
11451            if (DEBUG_REMOVE && chatty) {
11452                if (r == null) {
11453                    r = new StringBuilder(256);
11454                } else {
11455                    r.append(' ');
11456                }
11457                r.append(a.info.name);
11458            }
11459        }
11460        if (r != null) {
11461            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11462        }
11463
11464        N = pkg.permissions.size();
11465        r = null;
11466        for (i=0; i<N; i++) {
11467            PackageParser.Permission p = pkg.permissions.get(i);
11468            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11469            if (bp == null) {
11470                bp = mSettings.mPermissionTrees.get(p.info.name);
11471            }
11472            if (bp != null && bp.perm == p) {
11473                bp.perm = null;
11474                if (DEBUG_REMOVE && chatty) {
11475                    if (r == null) {
11476                        r = new StringBuilder(256);
11477                    } else {
11478                        r.append(' ');
11479                    }
11480                    r.append(p.info.name);
11481                }
11482            }
11483            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11484                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11485                if (appOpPkgs != null) {
11486                    appOpPkgs.remove(pkg.packageName);
11487                }
11488            }
11489        }
11490        if (r != null) {
11491            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11492        }
11493
11494        N = pkg.requestedPermissions.size();
11495        r = null;
11496        for (i=0; i<N; i++) {
11497            String perm = pkg.requestedPermissions.get(i);
11498            BasePermission bp = mSettings.mPermissions.get(perm);
11499            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11500                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11501                if (appOpPkgs != null) {
11502                    appOpPkgs.remove(pkg.packageName);
11503                    if (appOpPkgs.isEmpty()) {
11504                        mAppOpPermissionPackages.remove(perm);
11505                    }
11506                }
11507            }
11508        }
11509        if (r != null) {
11510            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11511        }
11512
11513        N = pkg.instrumentation.size();
11514        r = null;
11515        for (i=0; i<N; i++) {
11516            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11517            mInstrumentation.remove(a.getComponentName());
11518            if (DEBUG_REMOVE && chatty) {
11519                if (r == null) {
11520                    r = new StringBuilder(256);
11521                } else {
11522                    r.append(' ');
11523                }
11524                r.append(a.info.name);
11525            }
11526        }
11527        if (r != null) {
11528            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11529        }
11530
11531        r = null;
11532        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11533            // Only system apps can hold shared libraries.
11534            if (pkg.libraryNames != null) {
11535                for (i = 0; i < pkg.libraryNames.size(); i++) {
11536                    String name = pkg.libraryNames.get(i);
11537                    if (removeSharedLibraryLPw(name, 0)) {
11538                        if (DEBUG_REMOVE && chatty) {
11539                            if (r == null) {
11540                                r = new StringBuilder(256);
11541                            } else {
11542                                r.append(' ');
11543                            }
11544                            r.append(name);
11545                        }
11546                    }
11547                }
11548            }
11549        }
11550
11551        r = null;
11552
11553        // Any package can hold static shared libraries.
11554        if (pkg.staticSharedLibName != null) {
11555            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11556                if (DEBUG_REMOVE && chatty) {
11557                    if (r == null) {
11558                        r = new StringBuilder(256);
11559                    } else {
11560                        r.append(' ');
11561                    }
11562                    r.append(pkg.staticSharedLibName);
11563                }
11564            }
11565        }
11566
11567        if (r != null) {
11568            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11569        }
11570    }
11571
11572    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11573        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11574            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11575                return true;
11576            }
11577        }
11578        return false;
11579    }
11580
11581    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11582    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11583    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11584
11585    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11586        // Update the parent permissions
11587        updatePermissionsLPw(pkg.packageName, pkg, flags);
11588        // Update the child permissions
11589        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11590        for (int i = 0; i < childCount; i++) {
11591            PackageParser.Package childPkg = pkg.childPackages.get(i);
11592            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11593        }
11594    }
11595
11596    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11597            int flags) {
11598        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11599        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11600    }
11601
11602    private void updatePermissionsLPw(String changingPkg,
11603            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11604        // Make sure there are no dangling permission trees.
11605        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11606        while (it.hasNext()) {
11607            final BasePermission bp = it.next();
11608            if (bp.packageSetting == null) {
11609                // We may not yet have parsed the package, so just see if
11610                // we still know about its settings.
11611                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11612            }
11613            if (bp.packageSetting == null) {
11614                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11615                        + " from package " + bp.sourcePackage);
11616                it.remove();
11617            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11618                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11619                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11620                            + " from package " + bp.sourcePackage);
11621                    flags |= UPDATE_PERMISSIONS_ALL;
11622                    it.remove();
11623                }
11624            }
11625        }
11626
11627        // Make sure all dynamic permissions have been assigned to a package,
11628        // and make sure there are no dangling permissions.
11629        it = mSettings.mPermissions.values().iterator();
11630        while (it.hasNext()) {
11631            final BasePermission bp = it.next();
11632            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11633                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11634                        + bp.name + " pkg=" + bp.sourcePackage
11635                        + " info=" + bp.pendingInfo);
11636                if (bp.packageSetting == null && bp.pendingInfo != null) {
11637                    final BasePermission tree = findPermissionTreeLP(bp.name);
11638                    if (tree != null && tree.perm != null) {
11639                        bp.packageSetting = tree.packageSetting;
11640                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11641                                new PermissionInfo(bp.pendingInfo));
11642                        bp.perm.info.packageName = tree.perm.info.packageName;
11643                        bp.perm.info.name = bp.name;
11644                        bp.uid = tree.uid;
11645                    }
11646                }
11647            }
11648            if (bp.packageSetting == null) {
11649                // We may not yet have parsed the package, so just see if
11650                // we still know about its settings.
11651                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11652            }
11653            if (bp.packageSetting == null) {
11654                Slog.w(TAG, "Removing dangling permission: " + bp.name
11655                        + " from package " + bp.sourcePackage);
11656                it.remove();
11657            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11658                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11659                    Slog.i(TAG, "Removing old permission: " + bp.name
11660                            + " from package " + bp.sourcePackage);
11661                    flags |= UPDATE_PERMISSIONS_ALL;
11662                    it.remove();
11663                }
11664            }
11665        }
11666
11667        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11668        // Now update the permissions for all packages, in particular
11669        // replace the granted permissions of the system packages.
11670        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11671            for (PackageParser.Package pkg : mPackages.values()) {
11672                if (pkg != pkgInfo) {
11673                    // Only replace for packages on requested volume
11674                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11675                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11676                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11677                    grantPermissionsLPw(pkg, replace, changingPkg);
11678                }
11679            }
11680        }
11681
11682        if (pkgInfo != null) {
11683            // Only replace for packages on requested volume
11684            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11685            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11686                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11687            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11688        }
11689        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11690    }
11691
11692    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11693            String packageOfInterest) {
11694        // IMPORTANT: There are two types of permissions: install and runtime.
11695        // Install time permissions are granted when the app is installed to
11696        // all device users and users added in the future. Runtime permissions
11697        // are granted at runtime explicitly to specific users. Normal and signature
11698        // protected permissions are install time permissions. Dangerous permissions
11699        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11700        // otherwise they are runtime permissions. This function does not manage
11701        // runtime permissions except for the case an app targeting Lollipop MR1
11702        // being upgraded to target a newer SDK, in which case dangerous permissions
11703        // are transformed from install time to runtime ones.
11704
11705        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11706        if (ps == null) {
11707            return;
11708        }
11709
11710        PermissionsState permissionsState = ps.getPermissionsState();
11711        PermissionsState origPermissions = permissionsState;
11712
11713        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11714
11715        boolean runtimePermissionsRevoked = false;
11716        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11717
11718        boolean changedInstallPermission = false;
11719
11720        if (replace) {
11721            ps.installPermissionsFixed = false;
11722            if (!ps.isSharedUser()) {
11723                origPermissions = new PermissionsState(permissionsState);
11724                permissionsState.reset();
11725            } else {
11726                // We need to know only about runtime permission changes since the
11727                // calling code always writes the install permissions state but
11728                // the runtime ones are written only if changed. The only cases of
11729                // changed runtime permissions here are promotion of an install to
11730                // runtime and revocation of a runtime from a shared user.
11731                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11732                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11733                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11734                    runtimePermissionsRevoked = true;
11735                }
11736            }
11737        }
11738
11739        permissionsState.setGlobalGids(mGlobalGids);
11740
11741        final int N = pkg.requestedPermissions.size();
11742        for (int i=0; i<N; i++) {
11743            final String name = pkg.requestedPermissions.get(i);
11744            final BasePermission bp = mSettings.mPermissions.get(name);
11745            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11746                    >= Build.VERSION_CODES.M;
11747
11748            if (DEBUG_INSTALL) {
11749                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11750            }
11751
11752            if (bp == null || bp.packageSetting == null) {
11753                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11754                    Slog.w(TAG, "Unknown permission " + name
11755                            + " in package " + pkg.packageName);
11756                }
11757                continue;
11758            }
11759
11760
11761            // Limit ephemeral apps to ephemeral allowed permissions.
11762            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11763                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11764                        + pkg.packageName);
11765                continue;
11766            }
11767
11768            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11769                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11770                        + pkg.packageName);
11771                continue;
11772            }
11773
11774            final String perm = bp.name;
11775            boolean allowedSig = false;
11776            int grant = GRANT_DENIED;
11777
11778            // Keep track of app op permissions.
11779            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11780                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11781                if (pkgs == null) {
11782                    pkgs = new ArraySet<>();
11783                    mAppOpPermissionPackages.put(bp.name, pkgs);
11784                }
11785                pkgs.add(pkg.packageName);
11786            }
11787
11788            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11789            switch (level) {
11790                case PermissionInfo.PROTECTION_NORMAL: {
11791                    // For all apps normal permissions are install time ones.
11792                    grant = GRANT_INSTALL;
11793                } break;
11794
11795                case PermissionInfo.PROTECTION_DANGEROUS: {
11796                    // If a permission review is required for legacy apps we represent
11797                    // their permissions as always granted runtime ones since we need
11798                    // to keep the review required permission flag per user while an
11799                    // install permission's state is shared across all users.
11800                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11801                        // For legacy apps dangerous permissions are install time ones.
11802                        grant = GRANT_INSTALL;
11803                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11804                        // For legacy apps that became modern, install becomes runtime.
11805                        grant = GRANT_UPGRADE;
11806                    } else if (mPromoteSystemApps
11807                            && isSystemApp(ps)
11808                            && mExistingSystemPackages.contains(ps.name)) {
11809                        // For legacy system apps, install becomes runtime.
11810                        // We cannot check hasInstallPermission() for system apps since those
11811                        // permissions were granted implicitly and not persisted pre-M.
11812                        grant = GRANT_UPGRADE;
11813                    } else {
11814                        // For modern apps keep runtime permissions unchanged.
11815                        grant = GRANT_RUNTIME;
11816                    }
11817                } break;
11818
11819                case PermissionInfo.PROTECTION_SIGNATURE: {
11820                    // For all apps signature permissions are install time ones.
11821                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11822                    if (allowedSig) {
11823                        grant = GRANT_INSTALL;
11824                    }
11825                } break;
11826            }
11827
11828            if (DEBUG_INSTALL) {
11829                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11830            }
11831
11832            if (grant != GRANT_DENIED) {
11833                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11834                    // If this is an existing, non-system package, then
11835                    // we can't add any new permissions to it.
11836                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11837                        // Except...  if this is a permission that was added
11838                        // to the platform (note: need to only do this when
11839                        // updating the platform).
11840                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11841                            grant = GRANT_DENIED;
11842                        }
11843                    }
11844                }
11845
11846                switch (grant) {
11847                    case GRANT_INSTALL: {
11848                        // Revoke this as runtime permission to handle the case of
11849                        // a runtime permission being downgraded to an install one.
11850                        // Also in permission review mode we keep dangerous permissions
11851                        // for legacy apps
11852                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11853                            if (origPermissions.getRuntimePermissionState(
11854                                    bp.name, userId) != null) {
11855                                // Revoke the runtime permission and clear the flags.
11856                                origPermissions.revokeRuntimePermission(bp, userId);
11857                                origPermissions.updatePermissionFlags(bp, userId,
11858                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11859                                // If we revoked a permission permission, we have to write.
11860                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11861                                        changedRuntimePermissionUserIds, userId);
11862                            }
11863                        }
11864                        // Grant an install permission.
11865                        if (permissionsState.grantInstallPermission(bp) !=
11866                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11867                            changedInstallPermission = true;
11868                        }
11869                    } break;
11870
11871                    case GRANT_RUNTIME: {
11872                        // Grant previously granted runtime permissions.
11873                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11874                            PermissionState permissionState = origPermissions
11875                                    .getRuntimePermissionState(bp.name, userId);
11876                            int flags = permissionState != null
11877                                    ? permissionState.getFlags() : 0;
11878                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11879                                // Don't propagate the permission in a permission review mode if
11880                                // the former was revoked, i.e. marked to not propagate on upgrade.
11881                                // Note that in a permission review mode install permissions are
11882                                // represented as constantly granted runtime ones since we need to
11883                                // keep a per user state associated with the permission. Also the
11884                                // revoke on upgrade flag is no longer applicable and is reset.
11885                                final boolean revokeOnUpgrade = (flags & PackageManager
11886                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11887                                if (revokeOnUpgrade) {
11888                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11889                                    // Since we changed the flags, we have to write.
11890                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11891                                            changedRuntimePermissionUserIds, userId);
11892                                }
11893                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11894                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11895                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11896                                        // If we cannot put the permission as it was,
11897                                        // we have to write.
11898                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11899                                                changedRuntimePermissionUserIds, userId);
11900                                    }
11901                                }
11902
11903                                // If the app supports runtime permissions no need for a review.
11904                                if (mPermissionReviewRequired
11905                                        && appSupportsRuntimePermissions
11906                                        && (flags & PackageManager
11907                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11908                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11909                                    // Since we changed the flags, we have to write.
11910                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11911                                            changedRuntimePermissionUserIds, userId);
11912                                }
11913                            } else if (mPermissionReviewRequired
11914                                    && !appSupportsRuntimePermissions) {
11915                                // For legacy apps that need a permission review, every new
11916                                // runtime permission is granted but it is pending a review.
11917                                // We also need to review only platform defined runtime
11918                                // permissions as these are the only ones the platform knows
11919                                // how to disable the API to simulate revocation as legacy
11920                                // apps don't expect to run with revoked permissions.
11921                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11922                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11923                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11924                                        // We changed the flags, hence have to write.
11925                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11926                                                changedRuntimePermissionUserIds, userId);
11927                                    }
11928                                }
11929                                if (permissionsState.grantRuntimePermission(bp, userId)
11930                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11931                                    // We changed the permission, hence have to write.
11932                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11933                                            changedRuntimePermissionUserIds, userId);
11934                                }
11935                            }
11936                            // Propagate the permission flags.
11937                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11938                        }
11939                    } break;
11940
11941                    case GRANT_UPGRADE: {
11942                        // Grant runtime permissions for a previously held install permission.
11943                        PermissionState permissionState = origPermissions
11944                                .getInstallPermissionState(bp.name);
11945                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11946
11947                        if (origPermissions.revokeInstallPermission(bp)
11948                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11949                            // We will be transferring the permission flags, so clear them.
11950                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11951                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11952                            changedInstallPermission = true;
11953                        }
11954
11955                        // If the permission is not to be promoted to runtime we ignore it and
11956                        // also its other flags as they are not applicable to install permissions.
11957                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11958                            for (int userId : currentUserIds) {
11959                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11960                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11961                                    // Transfer the permission flags.
11962                                    permissionsState.updatePermissionFlags(bp, userId,
11963                                            flags, flags);
11964                                    // If we granted the permission, we have to write.
11965                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11966                                            changedRuntimePermissionUserIds, userId);
11967                                }
11968                            }
11969                        }
11970                    } break;
11971
11972                    default: {
11973                        if (packageOfInterest == null
11974                                || packageOfInterest.equals(pkg.packageName)) {
11975                            Slog.w(TAG, "Not granting permission " + perm
11976                                    + " to package " + pkg.packageName
11977                                    + " because it was previously installed without");
11978                        }
11979                    } break;
11980                }
11981            } else {
11982                if (permissionsState.revokeInstallPermission(bp) !=
11983                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11984                    // Also drop the permission flags.
11985                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11986                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11987                    changedInstallPermission = true;
11988                    Slog.i(TAG, "Un-granting permission " + perm
11989                            + " from package " + pkg.packageName
11990                            + " (protectionLevel=" + bp.protectionLevel
11991                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11992                            + ")");
11993                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11994                    // Don't print warning for app op permissions, since it is fine for them
11995                    // not to be granted, there is a UI for the user to decide.
11996                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11997                        Slog.w(TAG, "Not granting permission " + perm
11998                                + " to package " + pkg.packageName
11999                                + " (protectionLevel=" + bp.protectionLevel
12000                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12001                                + ")");
12002                    }
12003                }
12004            }
12005        }
12006
12007        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12008                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12009            // This is the first that we have heard about this package, so the
12010            // permissions we have now selected are fixed until explicitly
12011            // changed.
12012            ps.installPermissionsFixed = true;
12013        }
12014
12015        // Persist the runtime permissions state for users with changes. If permissions
12016        // were revoked because no app in the shared user declares them we have to
12017        // write synchronously to avoid losing runtime permissions state.
12018        for (int userId : changedRuntimePermissionUserIds) {
12019            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12020        }
12021    }
12022
12023    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12024        boolean allowed = false;
12025        final int NP = PackageParser.NEW_PERMISSIONS.length;
12026        for (int ip=0; ip<NP; ip++) {
12027            final PackageParser.NewPermissionInfo npi
12028                    = PackageParser.NEW_PERMISSIONS[ip];
12029            if (npi.name.equals(perm)
12030                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12031                allowed = true;
12032                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12033                        + pkg.packageName);
12034                break;
12035            }
12036        }
12037        return allowed;
12038    }
12039
12040    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12041            BasePermission bp, PermissionsState origPermissions) {
12042        boolean privilegedPermission = (bp.protectionLevel
12043                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12044        boolean privappPermissionsDisable =
12045                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12046        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12047        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12048        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12049                && !platformPackage && platformPermission) {
12050            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12051                    .getPrivAppPermissions(pkg.packageName);
12052            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12053            if (!whitelisted) {
12054                Slog.w(TAG, "Privileged permission " + perm + " for package "
12055                        + pkg.packageName + " - not in privapp-permissions whitelist");
12056                // Only report violations for apps on system image
12057                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12058                    if (mPrivappPermissionsViolations == null) {
12059                        mPrivappPermissionsViolations = new ArraySet<>();
12060                    }
12061                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12062                }
12063                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12064                    return false;
12065                }
12066            }
12067        }
12068        boolean allowed = (compareSignatures(
12069                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12070                        == PackageManager.SIGNATURE_MATCH)
12071                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12072                        == PackageManager.SIGNATURE_MATCH);
12073        if (!allowed && privilegedPermission) {
12074            if (isSystemApp(pkg)) {
12075                // For updated system applications, a system permission
12076                // is granted only if it had been defined by the original application.
12077                if (pkg.isUpdatedSystemApp()) {
12078                    final PackageSetting sysPs = mSettings
12079                            .getDisabledSystemPkgLPr(pkg.packageName);
12080                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12081                        // If the original was granted this permission, we take
12082                        // that grant decision as read and propagate it to the
12083                        // update.
12084                        if (sysPs.isPrivileged()) {
12085                            allowed = true;
12086                        }
12087                    } else {
12088                        // The system apk may have been updated with an older
12089                        // version of the one on the data partition, but which
12090                        // granted a new system permission that it didn't have
12091                        // before.  In this case we do want to allow the app to
12092                        // now get the new permission if the ancestral apk is
12093                        // privileged to get it.
12094                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12095                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12096                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12097                                    allowed = true;
12098                                    break;
12099                                }
12100                            }
12101                        }
12102                        // Also if a privileged parent package on the system image or any of
12103                        // its children requested a privileged permission, the updated child
12104                        // packages can also get the permission.
12105                        if (pkg.parentPackage != null) {
12106                            final PackageSetting disabledSysParentPs = mSettings
12107                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12108                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12109                                    && disabledSysParentPs.isPrivileged()) {
12110                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12111                                    allowed = true;
12112                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12113                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12114                                    for (int i = 0; i < count; i++) {
12115                                        PackageParser.Package disabledSysChildPkg =
12116                                                disabledSysParentPs.pkg.childPackages.get(i);
12117                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12118                                                perm)) {
12119                                            allowed = true;
12120                                            break;
12121                                        }
12122                                    }
12123                                }
12124                            }
12125                        }
12126                    }
12127                } else {
12128                    allowed = isPrivilegedApp(pkg);
12129                }
12130            }
12131        }
12132        if (!allowed) {
12133            if (!allowed && (bp.protectionLevel
12134                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12135                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12136                // If this was a previously normal/dangerous permission that got moved
12137                // to a system permission as part of the runtime permission redesign, then
12138                // we still want to blindly grant it to old apps.
12139                allowed = true;
12140            }
12141            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12142                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12143                // If this permission is to be granted to the system installer and
12144                // this app is an installer, then it gets the permission.
12145                allowed = true;
12146            }
12147            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12148                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12149                // If this permission is to be granted to the system verifier and
12150                // this app is a verifier, then it gets the permission.
12151                allowed = true;
12152            }
12153            if (!allowed && (bp.protectionLevel
12154                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12155                    && isSystemApp(pkg)) {
12156                // Any pre-installed system app is allowed to get this permission.
12157                allowed = true;
12158            }
12159            if (!allowed && (bp.protectionLevel
12160                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12161                // For development permissions, a development permission
12162                // is granted only if it was already granted.
12163                allowed = origPermissions.hasInstallPermission(perm);
12164            }
12165            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12166                    && pkg.packageName.equals(mSetupWizardPackage)) {
12167                // If this permission is to be granted to the system setup wizard and
12168                // this app is a setup wizard, then it gets the permission.
12169                allowed = true;
12170            }
12171        }
12172        return allowed;
12173    }
12174
12175    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12176        final int permCount = pkg.requestedPermissions.size();
12177        for (int j = 0; j < permCount; j++) {
12178            String requestedPermission = pkg.requestedPermissions.get(j);
12179            if (permission.equals(requestedPermission)) {
12180                return true;
12181            }
12182        }
12183        return false;
12184    }
12185
12186    final class ActivityIntentResolver
12187            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12188        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12189                boolean defaultOnly, int userId) {
12190            if (!sUserManager.exists(userId)) return null;
12191            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12192            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12193        }
12194
12195        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12196                int userId) {
12197            if (!sUserManager.exists(userId)) return null;
12198            mFlags = flags;
12199            return super.queryIntent(intent, resolvedType,
12200                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12201                    userId);
12202        }
12203
12204        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12205                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12206            if (!sUserManager.exists(userId)) return null;
12207            if (packageActivities == null) {
12208                return null;
12209            }
12210            mFlags = flags;
12211            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12212            final int N = packageActivities.size();
12213            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12214                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12215
12216            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12217            for (int i = 0; i < N; ++i) {
12218                intentFilters = packageActivities.get(i).intents;
12219                if (intentFilters != null && intentFilters.size() > 0) {
12220                    PackageParser.ActivityIntentInfo[] array =
12221                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12222                    intentFilters.toArray(array);
12223                    listCut.add(array);
12224                }
12225            }
12226            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12227        }
12228
12229        /**
12230         * Finds a privileged activity that matches the specified activity names.
12231         */
12232        private PackageParser.Activity findMatchingActivity(
12233                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12234            for (PackageParser.Activity sysActivity : activityList) {
12235                if (sysActivity.info.name.equals(activityInfo.name)) {
12236                    return sysActivity;
12237                }
12238                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12239                    return sysActivity;
12240                }
12241                if (sysActivity.info.targetActivity != null) {
12242                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12243                        return sysActivity;
12244                    }
12245                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12246                        return sysActivity;
12247                    }
12248                }
12249            }
12250            return null;
12251        }
12252
12253        public class IterGenerator<E> {
12254            public Iterator<E> generate(ActivityIntentInfo info) {
12255                return null;
12256            }
12257        }
12258
12259        public class ActionIterGenerator extends IterGenerator<String> {
12260            @Override
12261            public Iterator<String> generate(ActivityIntentInfo info) {
12262                return info.actionsIterator();
12263            }
12264        }
12265
12266        public class CategoriesIterGenerator extends IterGenerator<String> {
12267            @Override
12268            public Iterator<String> generate(ActivityIntentInfo info) {
12269                return info.categoriesIterator();
12270            }
12271        }
12272
12273        public class SchemesIterGenerator extends IterGenerator<String> {
12274            @Override
12275            public Iterator<String> generate(ActivityIntentInfo info) {
12276                return info.schemesIterator();
12277            }
12278        }
12279
12280        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12281            @Override
12282            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12283                return info.authoritiesIterator();
12284            }
12285        }
12286
12287        /**
12288         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12289         * MODIFIED. Do not pass in a list that should not be changed.
12290         */
12291        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12292                IterGenerator<T> generator, Iterator<T> searchIterator) {
12293            // loop through the set of actions; every one must be found in the intent filter
12294            while (searchIterator.hasNext()) {
12295                // we must have at least one filter in the list to consider a match
12296                if (intentList.size() == 0) {
12297                    break;
12298                }
12299
12300                final T searchAction = searchIterator.next();
12301
12302                // loop through the set of intent filters
12303                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12304                while (intentIter.hasNext()) {
12305                    final ActivityIntentInfo intentInfo = intentIter.next();
12306                    boolean selectionFound = false;
12307
12308                    // loop through the intent filter's selection criteria; at least one
12309                    // of them must match the searched criteria
12310                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12311                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12312                        final T intentSelection = intentSelectionIter.next();
12313                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12314                            selectionFound = true;
12315                            break;
12316                        }
12317                    }
12318
12319                    // the selection criteria wasn't found in this filter's set; this filter
12320                    // is not a potential match
12321                    if (!selectionFound) {
12322                        intentIter.remove();
12323                    }
12324                }
12325            }
12326        }
12327
12328        private boolean isProtectedAction(ActivityIntentInfo filter) {
12329            final Iterator<String> actionsIter = filter.actionsIterator();
12330            while (actionsIter != null && actionsIter.hasNext()) {
12331                final String filterAction = actionsIter.next();
12332                if (PROTECTED_ACTIONS.contains(filterAction)) {
12333                    return true;
12334                }
12335            }
12336            return false;
12337        }
12338
12339        /**
12340         * Adjusts the priority of the given intent filter according to policy.
12341         * <p>
12342         * <ul>
12343         * <li>The priority for non privileged applications is capped to '0'</li>
12344         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12345         * <li>The priority for unbundled updates to privileged applications is capped to the
12346         *      priority defined on the system partition</li>
12347         * </ul>
12348         * <p>
12349         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12350         * allowed to obtain any priority on any action.
12351         */
12352        private void adjustPriority(
12353                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12354            // nothing to do; priority is fine as-is
12355            if (intent.getPriority() <= 0) {
12356                return;
12357            }
12358
12359            final ActivityInfo activityInfo = intent.activity.info;
12360            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12361
12362            final boolean privilegedApp =
12363                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12364            if (!privilegedApp) {
12365                // non-privileged applications can never define a priority >0
12366                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12367                        + " package: " + applicationInfo.packageName
12368                        + " activity: " + intent.activity.className
12369                        + " origPrio: " + intent.getPriority());
12370                intent.setPriority(0);
12371                return;
12372            }
12373
12374            if (systemActivities == null) {
12375                // the system package is not disabled; we're parsing the system partition
12376                if (isProtectedAction(intent)) {
12377                    if (mDeferProtectedFilters) {
12378                        // We can't deal with these just yet. No component should ever obtain a
12379                        // >0 priority for a protected actions, with ONE exception -- the setup
12380                        // wizard. The setup wizard, however, cannot be known until we're able to
12381                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12382                        // until all intent filters have been processed. Chicken, meet egg.
12383                        // Let the filter temporarily have a high priority and rectify the
12384                        // priorities after all system packages have been scanned.
12385                        mProtectedFilters.add(intent);
12386                        if (DEBUG_FILTERS) {
12387                            Slog.i(TAG, "Protected action; save for later;"
12388                                    + " package: " + applicationInfo.packageName
12389                                    + " activity: " + intent.activity.className
12390                                    + " origPrio: " + intent.getPriority());
12391                        }
12392                        return;
12393                    } else {
12394                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12395                            Slog.i(TAG, "No setup wizard;"
12396                                + " All protected intents capped to priority 0");
12397                        }
12398                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12399                            if (DEBUG_FILTERS) {
12400                                Slog.i(TAG, "Found setup wizard;"
12401                                    + " allow priority " + intent.getPriority() + ";"
12402                                    + " package: " + intent.activity.info.packageName
12403                                    + " activity: " + intent.activity.className
12404                                    + " priority: " + intent.getPriority());
12405                            }
12406                            // setup wizard gets whatever it wants
12407                            return;
12408                        }
12409                        Slog.w(TAG, "Protected action; cap priority to 0;"
12410                                + " package: " + intent.activity.info.packageName
12411                                + " activity: " + intent.activity.className
12412                                + " origPrio: " + intent.getPriority());
12413                        intent.setPriority(0);
12414                        return;
12415                    }
12416                }
12417                // privileged apps on the system image get whatever priority they request
12418                return;
12419            }
12420
12421            // privileged app unbundled update ... try to find the same activity
12422            final PackageParser.Activity foundActivity =
12423                    findMatchingActivity(systemActivities, activityInfo);
12424            if (foundActivity == null) {
12425                // this is a new activity; it cannot obtain >0 priority
12426                if (DEBUG_FILTERS) {
12427                    Slog.i(TAG, "New activity; cap priority to 0;"
12428                            + " package: " + applicationInfo.packageName
12429                            + " activity: " + intent.activity.className
12430                            + " origPrio: " + intent.getPriority());
12431                }
12432                intent.setPriority(0);
12433                return;
12434            }
12435
12436            // found activity, now check for filter equivalence
12437
12438            // a shallow copy is enough; we modify the list, not its contents
12439            final List<ActivityIntentInfo> intentListCopy =
12440                    new ArrayList<>(foundActivity.intents);
12441            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12442
12443            // find matching action subsets
12444            final Iterator<String> actionsIterator = intent.actionsIterator();
12445            if (actionsIterator != null) {
12446                getIntentListSubset(
12447                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12448                if (intentListCopy.size() == 0) {
12449                    // no more intents to match; we're not equivalent
12450                    if (DEBUG_FILTERS) {
12451                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12452                                + " package: " + applicationInfo.packageName
12453                                + " activity: " + intent.activity.className
12454                                + " origPrio: " + intent.getPriority());
12455                    }
12456                    intent.setPriority(0);
12457                    return;
12458                }
12459            }
12460
12461            // find matching category subsets
12462            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12463            if (categoriesIterator != null) {
12464                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12465                        categoriesIterator);
12466                if (intentListCopy.size() == 0) {
12467                    // no more intents to match; we're not equivalent
12468                    if (DEBUG_FILTERS) {
12469                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12470                                + " package: " + applicationInfo.packageName
12471                                + " activity: " + intent.activity.className
12472                                + " origPrio: " + intent.getPriority());
12473                    }
12474                    intent.setPriority(0);
12475                    return;
12476                }
12477            }
12478
12479            // find matching schemes subsets
12480            final Iterator<String> schemesIterator = intent.schemesIterator();
12481            if (schemesIterator != null) {
12482                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12483                        schemesIterator);
12484                if (intentListCopy.size() == 0) {
12485                    // no more intents to match; we're not equivalent
12486                    if (DEBUG_FILTERS) {
12487                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12488                                + " package: " + applicationInfo.packageName
12489                                + " activity: " + intent.activity.className
12490                                + " origPrio: " + intent.getPriority());
12491                    }
12492                    intent.setPriority(0);
12493                    return;
12494                }
12495            }
12496
12497            // find matching authorities subsets
12498            final Iterator<IntentFilter.AuthorityEntry>
12499                    authoritiesIterator = intent.authoritiesIterator();
12500            if (authoritiesIterator != null) {
12501                getIntentListSubset(intentListCopy,
12502                        new AuthoritiesIterGenerator(),
12503                        authoritiesIterator);
12504                if (intentListCopy.size() == 0) {
12505                    // no more intents to match; we're not equivalent
12506                    if (DEBUG_FILTERS) {
12507                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12508                                + " package: " + applicationInfo.packageName
12509                                + " activity: " + intent.activity.className
12510                                + " origPrio: " + intent.getPriority());
12511                    }
12512                    intent.setPriority(0);
12513                    return;
12514                }
12515            }
12516
12517            // we found matching filter(s); app gets the max priority of all intents
12518            int cappedPriority = 0;
12519            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12520                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12521            }
12522            if (intent.getPriority() > cappedPriority) {
12523                if (DEBUG_FILTERS) {
12524                    Slog.i(TAG, "Found matching filter(s);"
12525                            + " cap priority to " + cappedPriority + ";"
12526                            + " package: " + applicationInfo.packageName
12527                            + " activity: " + intent.activity.className
12528                            + " origPrio: " + intent.getPriority());
12529                }
12530                intent.setPriority(cappedPriority);
12531                return;
12532            }
12533            // all this for nothing; the requested priority was <= what was on the system
12534        }
12535
12536        public final void addActivity(PackageParser.Activity a, String type) {
12537            mActivities.put(a.getComponentName(), a);
12538            if (DEBUG_SHOW_INFO)
12539                Log.v(
12540                TAG, "  " + type + " " +
12541                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12542            if (DEBUG_SHOW_INFO)
12543                Log.v(TAG, "    Class=" + a.info.name);
12544            final int NI = a.intents.size();
12545            for (int j=0; j<NI; j++) {
12546                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12547                if ("activity".equals(type)) {
12548                    final PackageSetting ps =
12549                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12550                    final List<PackageParser.Activity> systemActivities =
12551                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12552                    adjustPriority(systemActivities, intent);
12553                }
12554                if (DEBUG_SHOW_INFO) {
12555                    Log.v(TAG, "    IntentFilter:");
12556                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12557                }
12558                if (!intent.debugCheck()) {
12559                    Log.w(TAG, "==> For Activity " + a.info.name);
12560                }
12561                addFilter(intent);
12562            }
12563        }
12564
12565        public final void removeActivity(PackageParser.Activity a, String type) {
12566            mActivities.remove(a.getComponentName());
12567            if (DEBUG_SHOW_INFO) {
12568                Log.v(TAG, "  " + type + " "
12569                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12570                                : a.info.name) + ":");
12571                Log.v(TAG, "    Class=" + a.info.name);
12572            }
12573            final int NI = a.intents.size();
12574            for (int j=0; j<NI; j++) {
12575                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12576                if (DEBUG_SHOW_INFO) {
12577                    Log.v(TAG, "    IntentFilter:");
12578                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12579                }
12580                removeFilter(intent);
12581            }
12582        }
12583
12584        @Override
12585        protected boolean allowFilterResult(
12586                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12587            ActivityInfo filterAi = filter.activity.info;
12588            for (int i=dest.size()-1; i>=0; i--) {
12589                ActivityInfo destAi = dest.get(i).activityInfo;
12590                if (destAi.name == filterAi.name
12591                        && destAi.packageName == filterAi.packageName) {
12592                    return false;
12593                }
12594            }
12595            return true;
12596        }
12597
12598        @Override
12599        protected ActivityIntentInfo[] newArray(int size) {
12600            return new ActivityIntentInfo[size];
12601        }
12602
12603        @Override
12604        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12605            if (!sUserManager.exists(userId)) return true;
12606            PackageParser.Package p = filter.activity.owner;
12607            if (p != null) {
12608                PackageSetting ps = (PackageSetting)p.mExtras;
12609                if (ps != null) {
12610                    // System apps are never considered stopped for purposes of
12611                    // filtering, because there may be no way for the user to
12612                    // actually re-launch them.
12613                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12614                            && ps.getStopped(userId);
12615                }
12616            }
12617            return false;
12618        }
12619
12620        @Override
12621        protected boolean isPackageForFilter(String packageName,
12622                PackageParser.ActivityIntentInfo info) {
12623            return packageName.equals(info.activity.owner.packageName);
12624        }
12625
12626        @Override
12627        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12628                int match, int userId) {
12629            if (!sUserManager.exists(userId)) return null;
12630            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12631                return null;
12632            }
12633            final PackageParser.Activity activity = info.activity;
12634            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12635            if (ps == null) {
12636                return null;
12637            }
12638            final PackageUserState userState = ps.readUserState(userId);
12639            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12640            if (ai == null) {
12641                return null;
12642            }
12643            final boolean matchExplicitlyVisibleOnly =
12644                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12645            final boolean matchVisibleToInstantApp =
12646                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12647            final boolean componentVisible =
12648                    matchVisibleToInstantApp
12649                    && info.isVisibleToInstantApp()
12650                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12651            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12652            // throw out filters that aren't visible to ephemeral apps
12653            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12654                return null;
12655            }
12656            // throw out instant app filters if we're not explicitly requesting them
12657            if (!matchInstantApp && userState.instantApp) {
12658                return null;
12659            }
12660            // throw out instant app filters if updates are available; will trigger
12661            // instant app resolution
12662            if (userState.instantApp && ps.isUpdateAvailable()) {
12663                return null;
12664            }
12665            final ResolveInfo res = new ResolveInfo();
12666            res.activityInfo = ai;
12667            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12668                res.filter = info;
12669            }
12670            if (info != null) {
12671                res.handleAllWebDataURI = info.handleAllWebDataURI();
12672            }
12673            res.priority = info.getPriority();
12674            res.preferredOrder = activity.owner.mPreferredOrder;
12675            //System.out.println("Result: " + res.activityInfo.className +
12676            //                   " = " + res.priority);
12677            res.match = match;
12678            res.isDefault = info.hasDefault;
12679            res.labelRes = info.labelRes;
12680            res.nonLocalizedLabel = info.nonLocalizedLabel;
12681            if (userNeedsBadging(userId)) {
12682                res.noResourceId = true;
12683            } else {
12684                res.icon = info.icon;
12685            }
12686            res.iconResourceId = info.icon;
12687            res.system = res.activityInfo.applicationInfo.isSystemApp();
12688            res.isInstantAppAvailable = userState.instantApp;
12689            return res;
12690        }
12691
12692        @Override
12693        protected void sortResults(List<ResolveInfo> results) {
12694            Collections.sort(results, mResolvePrioritySorter);
12695        }
12696
12697        @Override
12698        protected void dumpFilter(PrintWriter out, String prefix,
12699                PackageParser.ActivityIntentInfo filter) {
12700            out.print(prefix); out.print(
12701                    Integer.toHexString(System.identityHashCode(filter.activity)));
12702                    out.print(' ');
12703                    filter.activity.printComponentShortName(out);
12704                    out.print(" filter ");
12705                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12706        }
12707
12708        @Override
12709        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12710            return filter.activity;
12711        }
12712
12713        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12714            PackageParser.Activity activity = (PackageParser.Activity)label;
12715            out.print(prefix); out.print(
12716                    Integer.toHexString(System.identityHashCode(activity)));
12717                    out.print(' ');
12718                    activity.printComponentShortName(out);
12719            if (count > 1) {
12720                out.print(" ("); out.print(count); out.print(" filters)");
12721            }
12722            out.println();
12723        }
12724
12725        // Keys are String (activity class name), values are Activity.
12726        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12727                = new ArrayMap<ComponentName, PackageParser.Activity>();
12728        private int mFlags;
12729    }
12730
12731    private final class ServiceIntentResolver
12732            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12733        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12734                boolean defaultOnly, int userId) {
12735            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12736            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12737        }
12738
12739        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12740                int userId) {
12741            if (!sUserManager.exists(userId)) return null;
12742            mFlags = flags;
12743            return super.queryIntent(intent, resolvedType,
12744                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12745                    userId);
12746        }
12747
12748        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12749                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12750            if (!sUserManager.exists(userId)) return null;
12751            if (packageServices == null) {
12752                return null;
12753            }
12754            mFlags = flags;
12755            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12756            final int N = packageServices.size();
12757            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12758                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12759
12760            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12761            for (int i = 0; i < N; ++i) {
12762                intentFilters = packageServices.get(i).intents;
12763                if (intentFilters != null && intentFilters.size() > 0) {
12764                    PackageParser.ServiceIntentInfo[] array =
12765                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12766                    intentFilters.toArray(array);
12767                    listCut.add(array);
12768                }
12769            }
12770            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12771        }
12772
12773        public final void addService(PackageParser.Service s) {
12774            mServices.put(s.getComponentName(), s);
12775            if (DEBUG_SHOW_INFO) {
12776                Log.v(TAG, "  "
12777                        + (s.info.nonLocalizedLabel != null
12778                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12779                Log.v(TAG, "    Class=" + s.info.name);
12780            }
12781            final int NI = s.intents.size();
12782            int j;
12783            for (j=0; j<NI; j++) {
12784                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12785                if (DEBUG_SHOW_INFO) {
12786                    Log.v(TAG, "    IntentFilter:");
12787                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12788                }
12789                if (!intent.debugCheck()) {
12790                    Log.w(TAG, "==> For Service " + s.info.name);
12791                }
12792                addFilter(intent);
12793            }
12794        }
12795
12796        public final void removeService(PackageParser.Service s) {
12797            mServices.remove(s.getComponentName());
12798            if (DEBUG_SHOW_INFO) {
12799                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12800                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12801                Log.v(TAG, "    Class=" + s.info.name);
12802            }
12803            final int NI = s.intents.size();
12804            int j;
12805            for (j=0; j<NI; j++) {
12806                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12807                if (DEBUG_SHOW_INFO) {
12808                    Log.v(TAG, "    IntentFilter:");
12809                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12810                }
12811                removeFilter(intent);
12812            }
12813        }
12814
12815        @Override
12816        protected boolean allowFilterResult(
12817                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12818            ServiceInfo filterSi = filter.service.info;
12819            for (int i=dest.size()-1; i>=0; i--) {
12820                ServiceInfo destAi = dest.get(i).serviceInfo;
12821                if (destAi.name == filterSi.name
12822                        && destAi.packageName == filterSi.packageName) {
12823                    return false;
12824                }
12825            }
12826            return true;
12827        }
12828
12829        @Override
12830        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12831            return new PackageParser.ServiceIntentInfo[size];
12832        }
12833
12834        @Override
12835        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12836            if (!sUserManager.exists(userId)) return true;
12837            PackageParser.Package p = filter.service.owner;
12838            if (p != null) {
12839                PackageSetting ps = (PackageSetting)p.mExtras;
12840                if (ps != null) {
12841                    // System apps are never considered stopped for purposes of
12842                    // filtering, because there may be no way for the user to
12843                    // actually re-launch them.
12844                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12845                            && ps.getStopped(userId);
12846                }
12847            }
12848            return false;
12849        }
12850
12851        @Override
12852        protected boolean isPackageForFilter(String packageName,
12853                PackageParser.ServiceIntentInfo info) {
12854            return packageName.equals(info.service.owner.packageName);
12855        }
12856
12857        @Override
12858        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12859                int match, int userId) {
12860            if (!sUserManager.exists(userId)) return null;
12861            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12862            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12863                return null;
12864            }
12865            final PackageParser.Service service = info.service;
12866            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12867            if (ps == null) {
12868                return null;
12869            }
12870            final PackageUserState userState = ps.readUserState(userId);
12871            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12872                    userState, userId);
12873            if (si == null) {
12874                return null;
12875            }
12876            final boolean matchVisibleToInstantApp =
12877                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12878            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12879            // throw out filters that aren't visible to ephemeral apps
12880            if (matchVisibleToInstantApp
12881                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12882                return null;
12883            }
12884            // throw out ephemeral filters if we're not explicitly requesting them
12885            if (!isInstantApp && userState.instantApp) {
12886                return null;
12887            }
12888            // throw out instant app filters if updates are available; will trigger
12889            // instant app resolution
12890            if (userState.instantApp && ps.isUpdateAvailable()) {
12891                return null;
12892            }
12893            final ResolveInfo res = new ResolveInfo();
12894            res.serviceInfo = si;
12895            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12896                res.filter = filter;
12897            }
12898            res.priority = info.getPriority();
12899            res.preferredOrder = service.owner.mPreferredOrder;
12900            res.match = match;
12901            res.isDefault = info.hasDefault;
12902            res.labelRes = info.labelRes;
12903            res.nonLocalizedLabel = info.nonLocalizedLabel;
12904            res.icon = info.icon;
12905            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12906            return res;
12907        }
12908
12909        @Override
12910        protected void sortResults(List<ResolveInfo> results) {
12911            Collections.sort(results, mResolvePrioritySorter);
12912        }
12913
12914        @Override
12915        protected void dumpFilter(PrintWriter out, String prefix,
12916                PackageParser.ServiceIntentInfo filter) {
12917            out.print(prefix); out.print(
12918                    Integer.toHexString(System.identityHashCode(filter.service)));
12919                    out.print(' ');
12920                    filter.service.printComponentShortName(out);
12921                    out.print(" filter ");
12922                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12923        }
12924
12925        @Override
12926        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12927            return filter.service;
12928        }
12929
12930        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12931            PackageParser.Service service = (PackageParser.Service)label;
12932            out.print(prefix); out.print(
12933                    Integer.toHexString(System.identityHashCode(service)));
12934                    out.print(' ');
12935                    service.printComponentShortName(out);
12936            if (count > 1) {
12937                out.print(" ("); out.print(count); out.print(" filters)");
12938            }
12939            out.println();
12940        }
12941
12942//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12943//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12944//            final List<ResolveInfo> retList = Lists.newArrayList();
12945//            while (i.hasNext()) {
12946//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12947//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12948//                    retList.add(resolveInfo);
12949//                }
12950//            }
12951//            return retList;
12952//        }
12953
12954        // Keys are String (activity class name), values are Activity.
12955        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12956                = new ArrayMap<ComponentName, PackageParser.Service>();
12957        private int mFlags;
12958    }
12959
12960    private final class ProviderIntentResolver
12961            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12962        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12963                boolean defaultOnly, int userId) {
12964            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12965            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12966        }
12967
12968        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12969                int userId) {
12970            if (!sUserManager.exists(userId))
12971                return null;
12972            mFlags = flags;
12973            return super.queryIntent(intent, resolvedType,
12974                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12975                    userId);
12976        }
12977
12978        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12979                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12980            if (!sUserManager.exists(userId))
12981                return null;
12982            if (packageProviders == null) {
12983                return null;
12984            }
12985            mFlags = flags;
12986            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12987            final int N = packageProviders.size();
12988            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12989                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12990
12991            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12992            for (int i = 0; i < N; ++i) {
12993                intentFilters = packageProviders.get(i).intents;
12994                if (intentFilters != null && intentFilters.size() > 0) {
12995                    PackageParser.ProviderIntentInfo[] array =
12996                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12997                    intentFilters.toArray(array);
12998                    listCut.add(array);
12999                }
13000            }
13001            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13002        }
13003
13004        public final void addProvider(PackageParser.Provider p) {
13005            if (mProviders.containsKey(p.getComponentName())) {
13006                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13007                return;
13008            }
13009
13010            mProviders.put(p.getComponentName(), p);
13011            if (DEBUG_SHOW_INFO) {
13012                Log.v(TAG, "  "
13013                        + (p.info.nonLocalizedLabel != null
13014                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13015                Log.v(TAG, "    Class=" + p.info.name);
13016            }
13017            final int NI = p.intents.size();
13018            int j;
13019            for (j = 0; j < NI; j++) {
13020                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13021                if (DEBUG_SHOW_INFO) {
13022                    Log.v(TAG, "    IntentFilter:");
13023                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13024                }
13025                if (!intent.debugCheck()) {
13026                    Log.w(TAG, "==> For Provider " + p.info.name);
13027                }
13028                addFilter(intent);
13029            }
13030        }
13031
13032        public final void removeProvider(PackageParser.Provider p) {
13033            mProviders.remove(p.getComponentName());
13034            if (DEBUG_SHOW_INFO) {
13035                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13036                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13037                Log.v(TAG, "    Class=" + p.info.name);
13038            }
13039            final int NI = p.intents.size();
13040            int j;
13041            for (j = 0; j < NI; j++) {
13042                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13043                if (DEBUG_SHOW_INFO) {
13044                    Log.v(TAG, "    IntentFilter:");
13045                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13046                }
13047                removeFilter(intent);
13048            }
13049        }
13050
13051        @Override
13052        protected boolean allowFilterResult(
13053                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13054            ProviderInfo filterPi = filter.provider.info;
13055            for (int i = dest.size() - 1; i >= 0; i--) {
13056                ProviderInfo destPi = dest.get(i).providerInfo;
13057                if (destPi.name == filterPi.name
13058                        && destPi.packageName == filterPi.packageName) {
13059                    return false;
13060                }
13061            }
13062            return true;
13063        }
13064
13065        @Override
13066        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13067            return new PackageParser.ProviderIntentInfo[size];
13068        }
13069
13070        @Override
13071        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13072            if (!sUserManager.exists(userId))
13073                return true;
13074            PackageParser.Package p = filter.provider.owner;
13075            if (p != null) {
13076                PackageSetting ps = (PackageSetting) p.mExtras;
13077                if (ps != null) {
13078                    // System apps are never considered stopped for purposes of
13079                    // filtering, because there may be no way for the user to
13080                    // actually re-launch them.
13081                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13082                            && ps.getStopped(userId);
13083                }
13084            }
13085            return false;
13086        }
13087
13088        @Override
13089        protected boolean isPackageForFilter(String packageName,
13090                PackageParser.ProviderIntentInfo info) {
13091            return packageName.equals(info.provider.owner.packageName);
13092        }
13093
13094        @Override
13095        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13096                int match, int userId) {
13097            if (!sUserManager.exists(userId))
13098                return null;
13099            final PackageParser.ProviderIntentInfo info = filter;
13100            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13101                return null;
13102            }
13103            final PackageParser.Provider provider = info.provider;
13104            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13105            if (ps == null) {
13106                return null;
13107            }
13108            final PackageUserState userState = ps.readUserState(userId);
13109            final boolean matchVisibleToInstantApp =
13110                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13111            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13112            // throw out filters that aren't visible to instant applications
13113            if (matchVisibleToInstantApp
13114                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13115                return null;
13116            }
13117            // throw out instant application filters if we're not explicitly requesting them
13118            if (!isInstantApp && userState.instantApp) {
13119                return null;
13120            }
13121            // throw out instant application filters if updates are available; will trigger
13122            // instant application resolution
13123            if (userState.instantApp && ps.isUpdateAvailable()) {
13124                return null;
13125            }
13126            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13127                    userState, userId);
13128            if (pi == null) {
13129                return null;
13130            }
13131            final ResolveInfo res = new ResolveInfo();
13132            res.providerInfo = pi;
13133            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13134                res.filter = filter;
13135            }
13136            res.priority = info.getPriority();
13137            res.preferredOrder = provider.owner.mPreferredOrder;
13138            res.match = match;
13139            res.isDefault = info.hasDefault;
13140            res.labelRes = info.labelRes;
13141            res.nonLocalizedLabel = info.nonLocalizedLabel;
13142            res.icon = info.icon;
13143            res.system = res.providerInfo.applicationInfo.isSystemApp();
13144            return res;
13145        }
13146
13147        @Override
13148        protected void sortResults(List<ResolveInfo> results) {
13149            Collections.sort(results, mResolvePrioritySorter);
13150        }
13151
13152        @Override
13153        protected void dumpFilter(PrintWriter out, String prefix,
13154                PackageParser.ProviderIntentInfo filter) {
13155            out.print(prefix);
13156            out.print(
13157                    Integer.toHexString(System.identityHashCode(filter.provider)));
13158            out.print(' ');
13159            filter.provider.printComponentShortName(out);
13160            out.print(" filter ");
13161            out.println(Integer.toHexString(System.identityHashCode(filter)));
13162        }
13163
13164        @Override
13165        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13166            return filter.provider;
13167        }
13168
13169        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13170            PackageParser.Provider provider = (PackageParser.Provider)label;
13171            out.print(prefix); out.print(
13172                    Integer.toHexString(System.identityHashCode(provider)));
13173                    out.print(' ');
13174                    provider.printComponentShortName(out);
13175            if (count > 1) {
13176                out.print(" ("); out.print(count); out.print(" filters)");
13177            }
13178            out.println();
13179        }
13180
13181        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13182                = new ArrayMap<ComponentName, PackageParser.Provider>();
13183        private int mFlags;
13184    }
13185
13186    static final class EphemeralIntentResolver
13187            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13188        /**
13189         * The result that has the highest defined order. Ordering applies on a
13190         * per-package basis. Mapping is from package name to Pair of order and
13191         * EphemeralResolveInfo.
13192         * <p>
13193         * NOTE: This is implemented as a field variable for convenience and efficiency.
13194         * By having a field variable, we're able to track filter ordering as soon as
13195         * a non-zero order is defined. Otherwise, multiple loops across the result set
13196         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13197         * this needs to be contained entirely within {@link #filterResults}.
13198         */
13199        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13200
13201        @Override
13202        protected AuxiliaryResolveInfo[] newArray(int size) {
13203            return new AuxiliaryResolveInfo[size];
13204        }
13205
13206        @Override
13207        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13208            return true;
13209        }
13210
13211        @Override
13212        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13213                int userId) {
13214            if (!sUserManager.exists(userId)) {
13215                return null;
13216            }
13217            final String packageName = responseObj.resolveInfo.getPackageName();
13218            final Integer order = responseObj.getOrder();
13219            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13220                    mOrderResult.get(packageName);
13221            // ordering is enabled and this item's order isn't high enough
13222            if (lastOrderResult != null && lastOrderResult.first >= order) {
13223                return null;
13224            }
13225            final InstantAppResolveInfo res = responseObj.resolveInfo;
13226            if (order > 0) {
13227                // non-zero order, enable ordering
13228                mOrderResult.put(packageName, new Pair<>(order, res));
13229            }
13230            return responseObj;
13231        }
13232
13233        @Override
13234        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13235            // only do work if ordering is enabled [most of the time it won't be]
13236            if (mOrderResult.size() == 0) {
13237                return;
13238            }
13239            int resultSize = results.size();
13240            for (int i = 0; i < resultSize; i++) {
13241                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13242                final String packageName = info.getPackageName();
13243                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13244                if (savedInfo == null) {
13245                    // package doesn't having ordering
13246                    continue;
13247                }
13248                if (savedInfo.second == info) {
13249                    // circled back to the highest ordered item; remove from order list
13250                    mOrderResult.remove(savedInfo);
13251                    if (mOrderResult.size() == 0) {
13252                        // no more ordered items
13253                        break;
13254                    }
13255                    continue;
13256                }
13257                // item has a worse order, remove it from the result list
13258                results.remove(i);
13259                resultSize--;
13260                i--;
13261            }
13262        }
13263    }
13264
13265    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13266            new Comparator<ResolveInfo>() {
13267        public int compare(ResolveInfo r1, ResolveInfo r2) {
13268            int v1 = r1.priority;
13269            int v2 = r2.priority;
13270            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13271            if (v1 != v2) {
13272                return (v1 > v2) ? -1 : 1;
13273            }
13274            v1 = r1.preferredOrder;
13275            v2 = r2.preferredOrder;
13276            if (v1 != v2) {
13277                return (v1 > v2) ? -1 : 1;
13278            }
13279            if (r1.isDefault != r2.isDefault) {
13280                return r1.isDefault ? -1 : 1;
13281            }
13282            v1 = r1.match;
13283            v2 = r2.match;
13284            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13285            if (v1 != v2) {
13286                return (v1 > v2) ? -1 : 1;
13287            }
13288            if (r1.system != r2.system) {
13289                return r1.system ? -1 : 1;
13290            }
13291            if (r1.activityInfo != null) {
13292                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13293            }
13294            if (r1.serviceInfo != null) {
13295                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13296            }
13297            if (r1.providerInfo != null) {
13298                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13299            }
13300            return 0;
13301        }
13302    };
13303
13304    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13305            new Comparator<ProviderInfo>() {
13306        public int compare(ProviderInfo p1, ProviderInfo p2) {
13307            final int v1 = p1.initOrder;
13308            final int v2 = p2.initOrder;
13309            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13310        }
13311    };
13312
13313    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13314            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13315            final int[] userIds) {
13316        mHandler.post(new Runnable() {
13317            @Override
13318            public void run() {
13319                try {
13320                    final IActivityManager am = ActivityManager.getService();
13321                    if (am == null) return;
13322                    final int[] resolvedUserIds;
13323                    if (userIds == null) {
13324                        resolvedUserIds = am.getRunningUserIds();
13325                    } else {
13326                        resolvedUserIds = userIds;
13327                    }
13328                    for (int id : resolvedUserIds) {
13329                        final Intent intent = new Intent(action,
13330                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13331                        if (extras != null) {
13332                            intent.putExtras(extras);
13333                        }
13334                        if (targetPkg != null) {
13335                            intent.setPackage(targetPkg);
13336                        }
13337                        // Modify the UID when posting to other users
13338                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13339                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13340                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13341                            intent.putExtra(Intent.EXTRA_UID, uid);
13342                        }
13343                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13344                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13345                        if (DEBUG_BROADCASTS) {
13346                            RuntimeException here = new RuntimeException("here");
13347                            here.fillInStackTrace();
13348                            Slog.d(TAG, "Sending to user " + id + ": "
13349                                    + intent.toShortString(false, true, false, false)
13350                                    + " " + intent.getExtras(), here);
13351                        }
13352                        am.broadcastIntent(null, intent, null, finishedReceiver,
13353                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13354                                null, finishedReceiver != null, false, id);
13355                    }
13356                } catch (RemoteException ex) {
13357                }
13358            }
13359        });
13360    }
13361
13362    /**
13363     * Check if the external storage media is available. This is true if there
13364     * is a mounted external storage medium or if the external storage is
13365     * emulated.
13366     */
13367    private boolean isExternalMediaAvailable() {
13368        return mMediaMounted || Environment.isExternalStorageEmulated();
13369    }
13370
13371    @Override
13372    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13373        // writer
13374        synchronized (mPackages) {
13375            if (!isExternalMediaAvailable()) {
13376                // If the external storage is no longer mounted at this point,
13377                // the caller may not have been able to delete all of this
13378                // packages files and can not delete any more.  Bail.
13379                return null;
13380            }
13381            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13382            if (lastPackage != null) {
13383                pkgs.remove(lastPackage);
13384            }
13385            if (pkgs.size() > 0) {
13386                return pkgs.get(0);
13387            }
13388        }
13389        return null;
13390    }
13391
13392    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13393        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13394                userId, andCode ? 1 : 0, packageName);
13395        if (mSystemReady) {
13396            msg.sendToTarget();
13397        } else {
13398            if (mPostSystemReadyMessages == null) {
13399                mPostSystemReadyMessages = new ArrayList<>();
13400            }
13401            mPostSystemReadyMessages.add(msg);
13402        }
13403    }
13404
13405    void startCleaningPackages() {
13406        // reader
13407        if (!isExternalMediaAvailable()) {
13408            return;
13409        }
13410        synchronized (mPackages) {
13411            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13412                return;
13413            }
13414        }
13415        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13416        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13417        IActivityManager am = ActivityManager.getService();
13418        if (am != null) {
13419            int dcsUid = -1;
13420            synchronized (mPackages) {
13421                if (!mDefaultContainerWhitelisted) {
13422                    mDefaultContainerWhitelisted = true;
13423                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13424                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13425                }
13426            }
13427            try {
13428                if (dcsUid > 0) {
13429                    am.backgroundWhitelistUid(dcsUid);
13430                }
13431                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13432                        UserHandle.USER_SYSTEM);
13433            } catch (RemoteException e) {
13434            }
13435        }
13436    }
13437
13438    @Override
13439    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13440            int installFlags, String installerPackageName, int userId) {
13441        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13442
13443        final int callingUid = Binder.getCallingUid();
13444        enforceCrossUserPermission(callingUid, userId,
13445                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13446
13447        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13448            try {
13449                if (observer != null) {
13450                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13451                }
13452            } catch (RemoteException re) {
13453            }
13454            return;
13455        }
13456
13457        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13458            installFlags |= PackageManager.INSTALL_FROM_ADB;
13459
13460        } else {
13461            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13462            // about installerPackageName.
13463
13464            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13465            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13466        }
13467
13468        UserHandle user;
13469        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13470            user = UserHandle.ALL;
13471        } else {
13472            user = new UserHandle(userId);
13473        }
13474
13475        // Only system components can circumvent runtime permissions when installing.
13476        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13477                && mContext.checkCallingOrSelfPermission(Manifest.permission
13478                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13479            throw new SecurityException("You need the "
13480                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13481                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13482        }
13483
13484        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13485                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13486            throw new IllegalArgumentException(
13487                    "New installs into ASEC containers no longer supported");
13488        }
13489
13490        final File originFile = new File(originPath);
13491        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13492
13493        final Message msg = mHandler.obtainMessage(INIT_COPY);
13494        final VerificationInfo verificationInfo = new VerificationInfo(
13495                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13496        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13497                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13498                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13499                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13500        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13501        msg.obj = params;
13502
13503        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13504                System.identityHashCode(msg.obj));
13505        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13506                System.identityHashCode(msg.obj));
13507
13508        mHandler.sendMessage(msg);
13509    }
13510
13511
13512    /**
13513     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13514     * it is acting on behalf on an enterprise or the user).
13515     *
13516     * Note that the ordering of the conditionals in this method is important. The checks we perform
13517     * are as follows, in this order:
13518     *
13519     * 1) If the install is being performed by a system app, we can trust the app to have set the
13520     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13521     *    what it is.
13522     * 2) If the install is being performed by a device or profile owner app, the install reason
13523     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13524     *    set the install reason correctly. If the app targets an older SDK version where install
13525     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13526     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13527     * 3) In all other cases, the install is being performed by a regular app that is neither part
13528     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13529     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13530     *    set to enterprise policy and if so, change it to unknown instead.
13531     */
13532    private int fixUpInstallReason(String installerPackageName, int installerUid,
13533            int installReason) {
13534        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13535                == PERMISSION_GRANTED) {
13536            // If the install is being performed by a system app, we trust that app to have set the
13537            // install reason correctly.
13538            return installReason;
13539        }
13540
13541        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13542            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13543        if (dpm != null) {
13544            ComponentName owner = null;
13545            try {
13546                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13547                if (owner == null) {
13548                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13549                }
13550            } catch (RemoteException e) {
13551            }
13552            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13553                // If the install is being performed by a device or profile owner, the install
13554                // reason should be enterprise policy.
13555                return PackageManager.INSTALL_REASON_POLICY;
13556            }
13557        }
13558
13559        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13560            // If the install is being performed by a regular app (i.e. neither system app nor
13561            // device or profile owner), we have no reason to believe that the app is acting on
13562            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13563            // change it to unknown instead.
13564            return PackageManager.INSTALL_REASON_UNKNOWN;
13565        }
13566
13567        // If the install is being performed by a regular app and the install reason was set to any
13568        // value but enterprise policy, leave the install reason unchanged.
13569        return installReason;
13570    }
13571
13572    void installStage(String packageName, File stagedDir, String stagedCid,
13573            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13574            String installerPackageName, int installerUid, UserHandle user,
13575            Certificate[][] certificates) {
13576        if (DEBUG_EPHEMERAL) {
13577            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13578                Slog.d(TAG, "Ephemeral install of " + packageName);
13579            }
13580        }
13581        final VerificationInfo verificationInfo = new VerificationInfo(
13582                sessionParams.originatingUri, sessionParams.referrerUri,
13583                sessionParams.originatingUid, installerUid);
13584
13585        final OriginInfo origin;
13586        if (stagedDir != null) {
13587            origin = OriginInfo.fromStagedFile(stagedDir);
13588        } else {
13589            origin = OriginInfo.fromStagedContainer(stagedCid);
13590        }
13591
13592        final Message msg = mHandler.obtainMessage(INIT_COPY);
13593        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13594                sessionParams.installReason);
13595        final InstallParams params = new InstallParams(origin, null, observer,
13596                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13597                verificationInfo, user, sessionParams.abiOverride,
13598                sessionParams.grantedRuntimePermissions, certificates, installReason);
13599        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13600        msg.obj = params;
13601
13602        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13603                System.identityHashCode(msg.obj));
13604        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13605                System.identityHashCode(msg.obj));
13606
13607        mHandler.sendMessage(msg);
13608    }
13609
13610    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13611            int userId) {
13612        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13613        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13614    }
13615
13616    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13617        if (ArrayUtils.isEmpty(userIds)) {
13618            return;
13619        }
13620        Bundle extras = new Bundle(1);
13621        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13622        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13623
13624        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13625                packageName, extras, 0, null, null, userIds);
13626        if (isSystem) {
13627            mHandler.post(() -> {
13628                        for (int userId : userIds) {
13629                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13630                        }
13631                    }
13632            );
13633        }
13634    }
13635
13636    /**
13637     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13638     * automatically without needing an explicit launch.
13639     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13640     */
13641    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13642        // If user is not running, the app didn't miss any broadcast
13643        if (!mUserManagerInternal.isUserRunning(userId)) {
13644            return;
13645        }
13646        final IActivityManager am = ActivityManager.getService();
13647        try {
13648            // Deliver LOCKED_BOOT_COMPLETED first
13649            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13650                    .setPackage(packageName);
13651            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13652            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13653                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13654
13655            // Deliver BOOT_COMPLETED only if user is unlocked
13656            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13657                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13658                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13659                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13660            }
13661        } catch (RemoteException e) {
13662            throw e.rethrowFromSystemServer();
13663        }
13664    }
13665
13666    @Override
13667    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13668            int userId) {
13669        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13670        PackageSetting pkgSetting;
13671        final int uid = Binder.getCallingUid();
13672        enforceCrossUserPermission(uid, userId,
13673                true /* requireFullPermission */, true /* checkShell */,
13674                "setApplicationHiddenSetting for user " + userId);
13675
13676        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13677            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13678            return false;
13679        }
13680
13681        long callingId = Binder.clearCallingIdentity();
13682        try {
13683            boolean sendAdded = false;
13684            boolean sendRemoved = false;
13685            // writer
13686            synchronized (mPackages) {
13687                pkgSetting = mSettings.mPackages.get(packageName);
13688                if (pkgSetting == null) {
13689                    return false;
13690                }
13691                // Do not allow "android" is being disabled
13692                if ("android".equals(packageName)) {
13693                    Slog.w(TAG, "Cannot hide package: android");
13694                    return false;
13695                }
13696                // Cannot hide static shared libs as they are considered
13697                // a part of the using app (emulating static linking). Also
13698                // static libs are installed always on internal storage.
13699                PackageParser.Package pkg = mPackages.get(packageName);
13700                if (pkg != null && pkg.staticSharedLibName != null) {
13701                    Slog.w(TAG, "Cannot hide package: " + packageName
13702                            + " providing static shared library: "
13703                            + pkg.staticSharedLibName);
13704                    return false;
13705                }
13706                // Only allow protected packages to hide themselves.
13707                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13708                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13709                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13710                    return false;
13711                }
13712
13713                if (pkgSetting.getHidden(userId) != hidden) {
13714                    pkgSetting.setHidden(hidden, userId);
13715                    mSettings.writePackageRestrictionsLPr(userId);
13716                    if (hidden) {
13717                        sendRemoved = true;
13718                    } else {
13719                        sendAdded = true;
13720                    }
13721                }
13722            }
13723            if (sendAdded) {
13724                sendPackageAddedForUser(packageName, pkgSetting, userId);
13725                return true;
13726            }
13727            if (sendRemoved) {
13728                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13729                        "hiding pkg");
13730                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13731                return true;
13732            }
13733        } finally {
13734            Binder.restoreCallingIdentity(callingId);
13735        }
13736        return false;
13737    }
13738
13739    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13740            int userId) {
13741        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13742        info.removedPackage = packageName;
13743        info.installerPackageName = pkgSetting.installerPackageName;
13744        info.removedUsers = new int[] {userId};
13745        info.broadcastUsers = new int[] {userId};
13746        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13747        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13748    }
13749
13750    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13751        if (pkgList.length > 0) {
13752            Bundle extras = new Bundle(1);
13753            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13754
13755            sendPackageBroadcast(
13756                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13757                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13758                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13759                    new int[] {userId});
13760        }
13761    }
13762
13763    /**
13764     * Returns true if application is not found or there was an error. Otherwise it returns
13765     * the hidden state of the package for the given user.
13766     */
13767    @Override
13768    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13769        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13770        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13771                true /* requireFullPermission */, false /* checkShell */,
13772                "getApplicationHidden for user " + userId);
13773        PackageSetting pkgSetting;
13774        long callingId = Binder.clearCallingIdentity();
13775        try {
13776            // writer
13777            synchronized (mPackages) {
13778                pkgSetting = mSettings.mPackages.get(packageName);
13779                if (pkgSetting == null) {
13780                    return true;
13781                }
13782                return pkgSetting.getHidden(userId);
13783            }
13784        } finally {
13785            Binder.restoreCallingIdentity(callingId);
13786        }
13787    }
13788
13789    /**
13790     * @hide
13791     */
13792    @Override
13793    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13794            int installReason) {
13795        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13796                null);
13797        PackageSetting pkgSetting;
13798        final int uid = Binder.getCallingUid();
13799        enforceCrossUserPermission(uid, userId,
13800                true /* requireFullPermission */, true /* checkShell */,
13801                "installExistingPackage for user " + userId);
13802        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13803            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13804        }
13805
13806        long callingId = Binder.clearCallingIdentity();
13807        try {
13808            boolean installed = false;
13809            final boolean instantApp =
13810                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13811            final boolean fullApp =
13812                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13813
13814            // writer
13815            synchronized (mPackages) {
13816                pkgSetting = mSettings.mPackages.get(packageName);
13817                if (pkgSetting == null) {
13818                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13819                }
13820                if (!pkgSetting.getInstalled(userId)) {
13821                    pkgSetting.setInstalled(true, userId);
13822                    pkgSetting.setHidden(false, userId);
13823                    pkgSetting.setInstallReason(installReason, userId);
13824                    mSettings.writePackageRestrictionsLPr(userId);
13825                    mSettings.writeKernelMappingLPr(pkgSetting);
13826                    installed = true;
13827                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13828                    // upgrade app from instant to full; we don't allow app downgrade
13829                    installed = true;
13830                }
13831                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13832            }
13833
13834            if (installed) {
13835                if (pkgSetting.pkg != null) {
13836                    synchronized (mInstallLock) {
13837                        // We don't need to freeze for a brand new install
13838                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13839                    }
13840                }
13841                sendPackageAddedForUser(packageName, pkgSetting, userId);
13842                synchronized (mPackages) {
13843                    updateSequenceNumberLP(packageName, new int[]{ userId });
13844                }
13845            }
13846        } finally {
13847            Binder.restoreCallingIdentity(callingId);
13848        }
13849
13850        return PackageManager.INSTALL_SUCCEEDED;
13851    }
13852
13853    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13854            boolean instantApp, boolean fullApp) {
13855        // no state specified; do nothing
13856        if (!instantApp && !fullApp) {
13857            return;
13858        }
13859        if (userId != UserHandle.USER_ALL) {
13860            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13861                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13862            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13863                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13864            }
13865        } else {
13866            for (int currentUserId : sUserManager.getUserIds()) {
13867                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13868                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13869                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13870                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13871                }
13872            }
13873        }
13874    }
13875
13876    boolean isUserRestricted(int userId, String restrictionKey) {
13877        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13878        if (restrictions.getBoolean(restrictionKey, false)) {
13879            Log.w(TAG, "User is restricted: " + restrictionKey);
13880            return true;
13881        }
13882        return false;
13883    }
13884
13885    @Override
13886    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13887            int userId) {
13888        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13889        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13890                true /* requireFullPermission */, true /* checkShell */,
13891                "setPackagesSuspended for user " + userId);
13892
13893        if (ArrayUtils.isEmpty(packageNames)) {
13894            return packageNames;
13895        }
13896
13897        // List of package names for whom the suspended state has changed.
13898        List<String> changedPackages = new ArrayList<>(packageNames.length);
13899        // List of package names for whom the suspended state is not set as requested in this
13900        // method.
13901        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13902        long callingId = Binder.clearCallingIdentity();
13903        try {
13904            for (int i = 0; i < packageNames.length; i++) {
13905                String packageName = packageNames[i];
13906                boolean changed = false;
13907                final int appId;
13908                synchronized (mPackages) {
13909                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13910                    if (pkgSetting == null) {
13911                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13912                                + "\". Skipping suspending/un-suspending.");
13913                        unactionedPackages.add(packageName);
13914                        continue;
13915                    }
13916                    appId = pkgSetting.appId;
13917                    if (pkgSetting.getSuspended(userId) != suspended) {
13918                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13919                            unactionedPackages.add(packageName);
13920                            continue;
13921                        }
13922                        pkgSetting.setSuspended(suspended, userId);
13923                        mSettings.writePackageRestrictionsLPr(userId);
13924                        changed = true;
13925                        changedPackages.add(packageName);
13926                    }
13927                }
13928
13929                if (changed && suspended) {
13930                    killApplication(packageName, UserHandle.getUid(userId, appId),
13931                            "suspending package");
13932                }
13933            }
13934        } finally {
13935            Binder.restoreCallingIdentity(callingId);
13936        }
13937
13938        if (!changedPackages.isEmpty()) {
13939            sendPackagesSuspendedForUser(changedPackages.toArray(
13940                    new String[changedPackages.size()]), userId, suspended);
13941        }
13942
13943        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13944    }
13945
13946    @Override
13947    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13948        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13949                true /* requireFullPermission */, false /* checkShell */,
13950                "isPackageSuspendedForUser for user " + userId);
13951        synchronized (mPackages) {
13952            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13953            if (pkgSetting == null) {
13954                throw new IllegalArgumentException("Unknown target package: " + packageName);
13955            }
13956            return pkgSetting.getSuspended(userId);
13957        }
13958    }
13959
13960    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13961        if (isPackageDeviceAdmin(packageName, userId)) {
13962            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13963                    + "\": has an active device admin");
13964            return false;
13965        }
13966
13967        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13968        if (packageName.equals(activeLauncherPackageName)) {
13969            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13970                    + "\": contains the active launcher");
13971            return false;
13972        }
13973
13974        if (packageName.equals(mRequiredInstallerPackage)) {
13975            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13976                    + "\": required for package installation");
13977            return false;
13978        }
13979
13980        if (packageName.equals(mRequiredUninstallerPackage)) {
13981            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13982                    + "\": required for package uninstallation");
13983            return false;
13984        }
13985
13986        if (packageName.equals(mRequiredVerifierPackage)) {
13987            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13988                    + "\": required for package verification");
13989            return false;
13990        }
13991
13992        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13993            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13994                    + "\": is the default dialer");
13995            return false;
13996        }
13997
13998        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13999            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14000                    + "\": protected package");
14001            return false;
14002        }
14003
14004        // Cannot suspend static shared libs as they are considered
14005        // a part of the using app (emulating static linking). Also
14006        // static libs are installed always on internal storage.
14007        PackageParser.Package pkg = mPackages.get(packageName);
14008        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14009            Slog.w(TAG, "Cannot suspend package: " + packageName
14010                    + " providing static shared library: "
14011                    + pkg.staticSharedLibName);
14012            return false;
14013        }
14014
14015        return true;
14016    }
14017
14018    private String getActiveLauncherPackageName(int userId) {
14019        Intent intent = new Intent(Intent.ACTION_MAIN);
14020        intent.addCategory(Intent.CATEGORY_HOME);
14021        ResolveInfo resolveInfo = resolveIntent(
14022                intent,
14023                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14024                PackageManager.MATCH_DEFAULT_ONLY,
14025                userId);
14026
14027        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14028    }
14029
14030    private String getDefaultDialerPackageName(int userId) {
14031        synchronized (mPackages) {
14032            return mSettings.getDefaultDialerPackageNameLPw(userId);
14033        }
14034    }
14035
14036    @Override
14037    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14038        mContext.enforceCallingOrSelfPermission(
14039                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14040                "Only package verification agents can verify applications");
14041
14042        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14043        final PackageVerificationResponse response = new PackageVerificationResponse(
14044                verificationCode, Binder.getCallingUid());
14045        msg.arg1 = id;
14046        msg.obj = response;
14047        mHandler.sendMessage(msg);
14048    }
14049
14050    @Override
14051    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14052            long millisecondsToDelay) {
14053        mContext.enforceCallingOrSelfPermission(
14054                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14055                "Only package verification agents can extend verification timeouts");
14056
14057        final PackageVerificationState state = mPendingVerification.get(id);
14058        final PackageVerificationResponse response = new PackageVerificationResponse(
14059                verificationCodeAtTimeout, Binder.getCallingUid());
14060
14061        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14062            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14063        }
14064        if (millisecondsToDelay < 0) {
14065            millisecondsToDelay = 0;
14066        }
14067        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14068                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14069            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14070        }
14071
14072        if ((state != null) && !state.timeoutExtended()) {
14073            state.extendTimeout();
14074
14075            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14076            msg.arg1 = id;
14077            msg.obj = response;
14078            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14079        }
14080    }
14081
14082    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14083            int verificationCode, UserHandle user) {
14084        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14085        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14086        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14087        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14088        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14089
14090        mContext.sendBroadcastAsUser(intent, user,
14091                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14092    }
14093
14094    private ComponentName matchComponentForVerifier(String packageName,
14095            List<ResolveInfo> receivers) {
14096        ActivityInfo targetReceiver = null;
14097
14098        final int NR = receivers.size();
14099        for (int i = 0; i < NR; i++) {
14100            final ResolveInfo info = receivers.get(i);
14101            if (info.activityInfo == null) {
14102                continue;
14103            }
14104
14105            if (packageName.equals(info.activityInfo.packageName)) {
14106                targetReceiver = info.activityInfo;
14107                break;
14108            }
14109        }
14110
14111        if (targetReceiver == null) {
14112            return null;
14113        }
14114
14115        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14116    }
14117
14118    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14119            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14120        if (pkgInfo.verifiers.length == 0) {
14121            return null;
14122        }
14123
14124        final int N = pkgInfo.verifiers.length;
14125        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14126        for (int i = 0; i < N; i++) {
14127            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14128
14129            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14130                    receivers);
14131            if (comp == null) {
14132                continue;
14133            }
14134
14135            final int verifierUid = getUidForVerifier(verifierInfo);
14136            if (verifierUid == -1) {
14137                continue;
14138            }
14139
14140            if (DEBUG_VERIFY) {
14141                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14142                        + " with the correct signature");
14143            }
14144            sufficientVerifiers.add(comp);
14145            verificationState.addSufficientVerifier(verifierUid);
14146        }
14147
14148        return sufficientVerifiers;
14149    }
14150
14151    private int getUidForVerifier(VerifierInfo verifierInfo) {
14152        synchronized (mPackages) {
14153            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14154            if (pkg == null) {
14155                return -1;
14156            } else if (pkg.mSignatures.length != 1) {
14157                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14158                        + " has more than one signature; ignoring");
14159                return -1;
14160            }
14161
14162            /*
14163             * If the public key of the package's signature does not match
14164             * our expected public key, then this is a different package and
14165             * we should skip.
14166             */
14167
14168            final byte[] expectedPublicKey;
14169            try {
14170                final Signature verifierSig = pkg.mSignatures[0];
14171                final PublicKey publicKey = verifierSig.getPublicKey();
14172                expectedPublicKey = publicKey.getEncoded();
14173            } catch (CertificateException e) {
14174                return -1;
14175            }
14176
14177            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14178
14179            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14180                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14181                        + " does not have the expected public key; ignoring");
14182                return -1;
14183            }
14184
14185            return pkg.applicationInfo.uid;
14186        }
14187    }
14188
14189    @Override
14190    public void finishPackageInstall(int token, boolean didLaunch) {
14191        enforceSystemOrRoot("Only the system is allowed to finish installs");
14192
14193        if (DEBUG_INSTALL) {
14194            Slog.v(TAG, "BM finishing package install for " + token);
14195        }
14196        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14197
14198        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14199        mHandler.sendMessage(msg);
14200    }
14201
14202    /**
14203     * Get the verification agent timeout.  Used for both the APK verifier and the
14204     * intent filter verifier.
14205     *
14206     * @return verification timeout in milliseconds
14207     */
14208    private long getVerificationTimeout() {
14209        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14210                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14211                DEFAULT_VERIFICATION_TIMEOUT);
14212    }
14213
14214    /**
14215     * Get the default verification agent response code.
14216     *
14217     * @return default verification response code
14218     */
14219    private int getDefaultVerificationResponse(UserHandle user) {
14220        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14221            return PackageManager.VERIFICATION_REJECT;
14222        }
14223        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14224                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14225                DEFAULT_VERIFICATION_RESPONSE);
14226    }
14227
14228    /**
14229     * Check whether or not package verification has been enabled.
14230     *
14231     * @return true if verification should be performed
14232     */
14233    private boolean isVerificationEnabled(int userId, int installFlags) {
14234        if (!DEFAULT_VERIFY_ENABLE) {
14235            return false;
14236        }
14237
14238        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14239
14240        // Check if installing from ADB
14241        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14242            // Do not run verification in a test harness environment
14243            if (ActivityManager.isRunningInTestHarness()) {
14244                return false;
14245            }
14246            if (ensureVerifyAppsEnabled) {
14247                return true;
14248            }
14249            // Check if the developer does not want package verification for ADB installs
14250            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14251                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14252                return false;
14253            }
14254        }
14255
14256        if (ensureVerifyAppsEnabled) {
14257            return true;
14258        }
14259
14260        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14261                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14262    }
14263
14264    @Override
14265    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14266            throws RemoteException {
14267        mContext.enforceCallingOrSelfPermission(
14268                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14269                "Only intentfilter verification agents can verify applications");
14270
14271        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14272        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14273                Binder.getCallingUid(), verificationCode, failedDomains);
14274        msg.arg1 = id;
14275        msg.obj = response;
14276        mHandler.sendMessage(msg);
14277    }
14278
14279    @Override
14280    public int getIntentVerificationStatus(String packageName, int userId) {
14281        synchronized (mPackages) {
14282            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14283        }
14284    }
14285
14286    @Override
14287    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14288        mContext.enforceCallingOrSelfPermission(
14289                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14290
14291        boolean result = false;
14292        synchronized (mPackages) {
14293            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14294        }
14295        if (result) {
14296            scheduleWritePackageRestrictionsLocked(userId);
14297        }
14298        return result;
14299    }
14300
14301    @Override
14302    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14303            String packageName) {
14304        synchronized (mPackages) {
14305            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14306        }
14307    }
14308
14309    @Override
14310    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14311        if (TextUtils.isEmpty(packageName)) {
14312            return ParceledListSlice.emptyList();
14313        }
14314        synchronized (mPackages) {
14315            PackageParser.Package pkg = mPackages.get(packageName);
14316            if (pkg == null || pkg.activities == null) {
14317                return ParceledListSlice.emptyList();
14318            }
14319            final int count = pkg.activities.size();
14320            ArrayList<IntentFilter> result = new ArrayList<>();
14321            for (int n=0; n<count; n++) {
14322                PackageParser.Activity activity = pkg.activities.get(n);
14323                if (activity.intents != null && activity.intents.size() > 0) {
14324                    result.addAll(activity.intents);
14325                }
14326            }
14327            return new ParceledListSlice<>(result);
14328        }
14329    }
14330
14331    @Override
14332    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14333        mContext.enforceCallingOrSelfPermission(
14334                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14335
14336        synchronized (mPackages) {
14337            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14338            if (packageName != null) {
14339                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14340                        packageName, userId);
14341            }
14342            return result;
14343        }
14344    }
14345
14346    @Override
14347    public String getDefaultBrowserPackageName(int userId) {
14348        synchronized (mPackages) {
14349            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14350        }
14351    }
14352
14353    /**
14354     * Get the "allow unknown sources" setting.
14355     *
14356     * @return the current "allow unknown sources" setting
14357     */
14358    private int getUnknownSourcesSettings() {
14359        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14360                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14361                -1);
14362    }
14363
14364    @Override
14365    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14366        final int uid = Binder.getCallingUid();
14367        // writer
14368        synchronized (mPackages) {
14369            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14370            if (targetPackageSetting == null) {
14371                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14372            }
14373
14374            PackageSetting installerPackageSetting;
14375            if (installerPackageName != null) {
14376                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14377                if (installerPackageSetting == null) {
14378                    throw new IllegalArgumentException("Unknown installer package: "
14379                            + installerPackageName);
14380                }
14381            } else {
14382                installerPackageSetting = null;
14383            }
14384
14385            Signature[] callerSignature;
14386            Object obj = mSettings.getUserIdLPr(uid);
14387            if (obj != null) {
14388                if (obj instanceof SharedUserSetting) {
14389                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14390                } else if (obj instanceof PackageSetting) {
14391                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14392                } else {
14393                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14394                }
14395            } else {
14396                throw new SecurityException("Unknown calling UID: " + uid);
14397            }
14398
14399            // Verify: can't set installerPackageName to a package that is
14400            // not signed with the same cert as the caller.
14401            if (installerPackageSetting != null) {
14402                if (compareSignatures(callerSignature,
14403                        installerPackageSetting.signatures.mSignatures)
14404                        != PackageManager.SIGNATURE_MATCH) {
14405                    throw new SecurityException(
14406                            "Caller does not have same cert as new installer package "
14407                            + installerPackageName);
14408                }
14409            }
14410
14411            // Verify: if target already has an installer package, it must
14412            // be signed with the same cert as the caller.
14413            if (targetPackageSetting.installerPackageName != null) {
14414                PackageSetting setting = mSettings.mPackages.get(
14415                        targetPackageSetting.installerPackageName);
14416                // If the currently set package isn't valid, then it's always
14417                // okay to change it.
14418                if (setting != null) {
14419                    if (compareSignatures(callerSignature,
14420                            setting.signatures.mSignatures)
14421                            != PackageManager.SIGNATURE_MATCH) {
14422                        throw new SecurityException(
14423                                "Caller does not have same cert as old installer package "
14424                                + targetPackageSetting.installerPackageName);
14425                    }
14426                }
14427            }
14428
14429            // Okay!
14430            targetPackageSetting.installerPackageName = installerPackageName;
14431            if (installerPackageName != null) {
14432                mSettings.mInstallerPackages.add(installerPackageName);
14433            }
14434            scheduleWriteSettingsLocked();
14435        }
14436    }
14437
14438    @Override
14439    public void setApplicationCategoryHint(String packageName, int categoryHint,
14440            String callerPackageName) {
14441        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14442                callerPackageName);
14443        synchronized (mPackages) {
14444            PackageSetting ps = mSettings.mPackages.get(packageName);
14445            if (ps == null) {
14446                throw new IllegalArgumentException("Unknown target package " + packageName);
14447            }
14448
14449            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14450                throw new IllegalArgumentException("Calling package " + callerPackageName
14451                        + " is not installer for " + packageName);
14452            }
14453
14454            if (ps.categoryHint != categoryHint) {
14455                ps.categoryHint = categoryHint;
14456                scheduleWriteSettingsLocked();
14457            }
14458        }
14459    }
14460
14461    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14462        // Queue up an async operation since the package installation may take a little while.
14463        mHandler.post(new Runnable() {
14464            public void run() {
14465                mHandler.removeCallbacks(this);
14466                 // Result object to be returned
14467                PackageInstalledInfo res = new PackageInstalledInfo();
14468                res.setReturnCode(currentStatus);
14469                res.uid = -1;
14470                res.pkg = null;
14471                res.removedInfo = null;
14472                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14473                    args.doPreInstall(res.returnCode);
14474                    synchronized (mInstallLock) {
14475                        installPackageTracedLI(args, res);
14476                    }
14477                    args.doPostInstall(res.returnCode, res.uid);
14478                }
14479
14480                // A restore should be performed at this point if (a) the install
14481                // succeeded, (b) the operation is not an update, and (c) the new
14482                // package has not opted out of backup participation.
14483                final boolean update = res.removedInfo != null
14484                        && res.removedInfo.removedPackage != null;
14485                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14486                boolean doRestore = !update
14487                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14488
14489                // Set up the post-install work request bookkeeping.  This will be used
14490                // and cleaned up by the post-install event handling regardless of whether
14491                // there's a restore pass performed.  Token values are >= 1.
14492                int token;
14493                if (mNextInstallToken < 0) mNextInstallToken = 1;
14494                token = mNextInstallToken++;
14495
14496                PostInstallData data = new PostInstallData(args, res);
14497                mRunningInstalls.put(token, data);
14498                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14499
14500                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14501                    // Pass responsibility to the Backup Manager.  It will perform a
14502                    // restore if appropriate, then pass responsibility back to the
14503                    // Package Manager to run the post-install observer callbacks
14504                    // and broadcasts.
14505                    IBackupManager bm = IBackupManager.Stub.asInterface(
14506                            ServiceManager.getService(Context.BACKUP_SERVICE));
14507                    if (bm != null) {
14508                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14509                                + " to BM for possible restore");
14510                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14511                        try {
14512                            // TODO: http://b/22388012
14513                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14514                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14515                            } else {
14516                                doRestore = false;
14517                            }
14518                        } catch (RemoteException e) {
14519                            // can't happen; the backup manager is local
14520                        } catch (Exception e) {
14521                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14522                            doRestore = false;
14523                        }
14524                    } else {
14525                        Slog.e(TAG, "Backup Manager not found!");
14526                        doRestore = false;
14527                    }
14528                }
14529
14530                if (!doRestore) {
14531                    // No restore possible, or the Backup Manager was mysteriously not
14532                    // available -- just fire the post-install work request directly.
14533                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14534
14535                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14536
14537                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14538                    mHandler.sendMessage(msg);
14539                }
14540            }
14541        });
14542    }
14543
14544    /**
14545     * Callback from PackageSettings whenever an app is first transitioned out of the
14546     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14547     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14548     * here whether the app is the target of an ongoing install, and only send the
14549     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14550     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14551     * handling.
14552     */
14553    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14554        // Serialize this with the rest of the install-process message chain.  In the
14555        // restore-at-install case, this Runnable will necessarily run before the
14556        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14557        // are coherent.  In the non-restore case, the app has already completed install
14558        // and been launched through some other means, so it is not in a problematic
14559        // state for observers to see the FIRST_LAUNCH signal.
14560        mHandler.post(new Runnable() {
14561            @Override
14562            public void run() {
14563                for (int i = 0; i < mRunningInstalls.size(); i++) {
14564                    final PostInstallData data = mRunningInstalls.valueAt(i);
14565                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14566                        continue;
14567                    }
14568                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14569                        // right package; but is it for the right user?
14570                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14571                            if (userId == data.res.newUsers[uIndex]) {
14572                                if (DEBUG_BACKUP) {
14573                                    Slog.i(TAG, "Package " + pkgName
14574                                            + " being restored so deferring FIRST_LAUNCH");
14575                                }
14576                                return;
14577                            }
14578                        }
14579                    }
14580                }
14581                // didn't find it, so not being restored
14582                if (DEBUG_BACKUP) {
14583                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14584                }
14585                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14586            }
14587        });
14588    }
14589
14590    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14591        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14592                installerPkg, null, userIds);
14593    }
14594
14595    private abstract class HandlerParams {
14596        private static final int MAX_RETRIES = 4;
14597
14598        /**
14599         * Number of times startCopy() has been attempted and had a non-fatal
14600         * error.
14601         */
14602        private int mRetries = 0;
14603
14604        /** User handle for the user requesting the information or installation. */
14605        private final UserHandle mUser;
14606        String traceMethod;
14607        int traceCookie;
14608
14609        HandlerParams(UserHandle user) {
14610            mUser = user;
14611        }
14612
14613        UserHandle getUser() {
14614            return mUser;
14615        }
14616
14617        HandlerParams setTraceMethod(String traceMethod) {
14618            this.traceMethod = traceMethod;
14619            return this;
14620        }
14621
14622        HandlerParams setTraceCookie(int traceCookie) {
14623            this.traceCookie = traceCookie;
14624            return this;
14625        }
14626
14627        final boolean startCopy() {
14628            boolean res;
14629            try {
14630                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14631
14632                if (++mRetries > MAX_RETRIES) {
14633                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14634                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14635                    handleServiceError();
14636                    return false;
14637                } else {
14638                    handleStartCopy();
14639                    res = true;
14640                }
14641            } catch (RemoteException e) {
14642                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14643                mHandler.sendEmptyMessage(MCS_RECONNECT);
14644                res = false;
14645            }
14646            handleReturnCode();
14647            return res;
14648        }
14649
14650        final void serviceError() {
14651            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14652            handleServiceError();
14653            handleReturnCode();
14654        }
14655
14656        abstract void handleStartCopy() throws RemoteException;
14657        abstract void handleServiceError();
14658        abstract void handleReturnCode();
14659    }
14660
14661    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14662        for (File path : paths) {
14663            try {
14664                mcs.clearDirectory(path.getAbsolutePath());
14665            } catch (RemoteException e) {
14666            }
14667        }
14668    }
14669
14670    static class OriginInfo {
14671        /**
14672         * Location where install is coming from, before it has been
14673         * copied/renamed into place. This could be a single monolithic APK
14674         * file, or a cluster directory. This location may be untrusted.
14675         */
14676        final File file;
14677        final String cid;
14678
14679        /**
14680         * Flag indicating that {@link #file} or {@link #cid} has already been
14681         * staged, meaning downstream users don't need to defensively copy the
14682         * contents.
14683         */
14684        final boolean staged;
14685
14686        /**
14687         * Flag indicating that {@link #file} or {@link #cid} is an already
14688         * installed app that is being moved.
14689         */
14690        final boolean existing;
14691
14692        final String resolvedPath;
14693        final File resolvedFile;
14694
14695        static OriginInfo fromNothing() {
14696            return new OriginInfo(null, null, false, false);
14697        }
14698
14699        static OriginInfo fromUntrustedFile(File file) {
14700            return new OriginInfo(file, null, false, false);
14701        }
14702
14703        static OriginInfo fromExistingFile(File file) {
14704            return new OriginInfo(file, null, false, true);
14705        }
14706
14707        static OriginInfo fromStagedFile(File file) {
14708            return new OriginInfo(file, null, true, false);
14709        }
14710
14711        static OriginInfo fromStagedContainer(String cid) {
14712            return new OriginInfo(null, cid, true, false);
14713        }
14714
14715        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14716            this.file = file;
14717            this.cid = cid;
14718            this.staged = staged;
14719            this.existing = existing;
14720
14721            if (cid != null) {
14722                resolvedPath = PackageHelper.getSdDir(cid);
14723                resolvedFile = new File(resolvedPath);
14724            } else if (file != null) {
14725                resolvedPath = file.getAbsolutePath();
14726                resolvedFile = file;
14727            } else {
14728                resolvedPath = null;
14729                resolvedFile = null;
14730            }
14731        }
14732    }
14733
14734    static class MoveInfo {
14735        final int moveId;
14736        final String fromUuid;
14737        final String toUuid;
14738        final String packageName;
14739        final String dataAppName;
14740        final int appId;
14741        final String seinfo;
14742        final int targetSdkVersion;
14743
14744        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14745                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14746            this.moveId = moveId;
14747            this.fromUuid = fromUuid;
14748            this.toUuid = toUuid;
14749            this.packageName = packageName;
14750            this.dataAppName = dataAppName;
14751            this.appId = appId;
14752            this.seinfo = seinfo;
14753            this.targetSdkVersion = targetSdkVersion;
14754        }
14755    }
14756
14757    static class VerificationInfo {
14758        /** A constant used to indicate that a uid value is not present. */
14759        public static final int NO_UID = -1;
14760
14761        /** URI referencing where the package was downloaded from. */
14762        final Uri originatingUri;
14763
14764        /** HTTP referrer URI associated with the originatingURI. */
14765        final Uri referrer;
14766
14767        /** UID of the application that the install request originated from. */
14768        final int originatingUid;
14769
14770        /** UID of application requesting the install */
14771        final int installerUid;
14772
14773        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14774            this.originatingUri = originatingUri;
14775            this.referrer = referrer;
14776            this.originatingUid = originatingUid;
14777            this.installerUid = installerUid;
14778        }
14779    }
14780
14781    class InstallParams extends HandlerParams {
14782        final OriginInfo origin;
14783        final MoveInfo move;
14784        final IPackageInstallObserver2 observer;
14785        int installFlags;
14786        final String installerPackageName;
14787        final String volumeUuid;
14788        private InstallArgs mArgs;
14789        private int mRet;
14790        final String packageAbiOverride;
14791        final String[] grantedRuntimePermissions;
14792        final VerificationInfo verificationInfo;
14793        final Certificate[][] certificates;
14794        final int installReason;
14795
14796        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14797                int installFlags, String installerPackageName, String volumeUuid,
14798                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14799                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14800            super(user);
14801            this.origin = origin;
14802            this.move = move;
14803            this.observer = observer;
14804            this.installFlags = installFlags;
14805            this.installerPackageName = installerPackageName;
14806            this.volumeUuid = volumeUuid;
14807            this.verificationInfo = verificationInfo;
14808            this.packageAbiOverride = packageAbiOverride;
14809            this.grantedRuntimePermissions = grantedPermissions;
14810            this.certificates = certificates;
14811            this.installReason = installReason;
14812        }
14813
14814        @Override
14815        public String toString() {
14816            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14817                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14818        }
14819
14820        private int installLocationPolicy(PackageInfoLite pkgLite) {
14821            String packageName = pkgLite.packageName;
14822            int installLocation = pkgLite.installLocation;
14823            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14824            // reader
14825            synchronized (mPackages) {
14826                // Currently installed package which the new package is attempting to replace or
14827                // null if no such package is installed.
14828                PackageParser.Package installedPkg = mPackages.get(packageName);
14829                // Package which currently owns the data which the new package will own if installed.
14830                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14831                // will be null whereas dataOwnerPkg will contain information about the package
14832                // which was uninstalled while keeping its data.
14833                PackageParser.Package dataOwnerPkg = installedPkg;
14834                if (dataOwnerPkg  == null) {
14835                    PackageSetting ps = mSettings.mPackages.get(packageName);
14836                    if (ps != null) {
14837                        dataOwnerPkg = ps.pkg;
14838                    }
14839                }
14840
14841                if (dataOwnerPkg != null) {
14842                    // If installed, the package will get access to data left on the device by its
14843                    // predecessor. As a security measure, this is permited only if this is not a
14844                    // version downgrade or if the predecessor package is marked as debuggable and
14845                    // a downgrade is explicitly requested.
14846                    //
14847                    // On debuggable platform builds, downgrades are permitted even for
14848                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14849                    // not offer security guarantees and thus it's OK to disable some security
14850                    // mechanisms to make debugging/testing easier on those builds. However, even on
14851                    // debuggable builds downgrades of packages are permitted only if requested via
14852                    // installFlags. This is because we aim to keep the behavior of debuggable
14853                    // platform builds as close as possible to the behavior of non-debuggable
14854                    // platform builds.
14855                    final boolean downgradeRequested =
14856                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14857                    final boolean packageDebuggable =
14858                                (dataOwnerPkg.applicationInfo.flags
14859                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14860                    final boolean downgradePermitted =
14861                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14862                    if (!downgradePermitted) {
14863                        try {
14864                            checkDowngrade(dataOwnerPkg, pkgLite);
14865                        } catch (PackageManagerException e) {
14866                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14867                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14868                        }
14869                    }
14870                }
14871
14872                if (installedPkg != null) {
14873                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14874                        // Check for updated system application.
14875                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14876                            if (onSd) {
14877                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14878                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14879                            }
14880                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14881                        } else {
14882                            if (onSd) {
14883                                // Install flag overrides everything.
14884                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14885                            }
14886                            // If current upgrade specifies particular preference
14887                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14888                                // Application explicitly specified internal.
14889                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14890                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14891                                // App explictly prefers external. Let policy decide
14892                            } else {
14893                                // Prefer previous location
14894                                if (isExternal(installedPkg)) {
14895                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14896                                }
14897                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14898                            }
14899                        }
14900                    } else {
14901                        // Invalid install. Return error code
14902                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14903                    }
14904                }
14905            }
14906            // All the special cases have been taken care of.
14907            // Return result based on recommended install location.
14908            if (onSd) {
14909                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14910            }
14911            return pkgLite.recommendedInstallLocation;
14912        }
14913
14914        /*
14915         * Invoke remote method to get package information and install
14916         * location values. Override install location based on default
14917         * policy if needed and then create install arguments based
14918         * on the install location.
14919         */
14920        public void handleStartCopy() throws RemoteException {
14921            int ret = PackageManager.INSTALL_SUCCEEDED;
14922
14923            // If we're already staged, we've firmly committed to an install location
14924            if (origin.staged) {
14925                if (origin.file != null) {
14926                    installFlags |= PackageManager.INSTALL_INTERNAL;
14927                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14928                } else if (origin.cid != null) {
14929                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14930                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14931                } else {
14932                    throw new IllegalStateException("Invalid stage location");
14933                }
14934            }
14935
14936            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14937            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14938            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14939            PackageInfoLite pkgLite = null;
14940
14941            if (onInt && onSd) {
14942                // Check if both bits are set.
14943                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14944                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14945            } else if (onSd && ephemeral) {
14946                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14947                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14948            } else {
14949                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14950                        packageAbiOverride);
14951
14952                if (DEBUG_EPHEMERAL && ephemeral) {
14953                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14954                }
14955
14956                /*
14957                 * If we have too little free space, try to free cache
14958                 * before giving up.
14959                 */
14960                if (!origin.staged && pkgLite.recommendedInstallLocation
14961                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14962                    // TODO: focus freeing disk space on the target device
14963                    final StorageManager storage = StorageManager.from(mContext);
14964                    final long lowThreshold = storage.getStorageLowBytes(
14965                            Environment.getDataDirectory());
14966
14967                    final long sizeBytes = mContainerService.calculateInstalledSize(
14968                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14969
14970                    try {
14971                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14972                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14973                                installFlags, packageAbiOverride);
14974                    } catch (InstallerException e) {
14975                        Slog.w(TAG, "Failed to free cache", e);
14976                    }
14977
14978                    /*
14979                     * The cache free must have deleted the file we
14980                     * downloaded to install.
14981                     *
14982                     * TODO: fix the "freeCache" call to not delete
14983                     *       the file we care about.
14984                     */
14985                    if (pkgLite.recommendedInstallLocation
14986                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14987                        pkgLite.recommendedInstallLocation
14988                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14989                    }
14990                }
14991            }
14992
14993            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14994                int loc = pkgLite.recommendedInstallLocation;
14995                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14996                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14997                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14998                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14999                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15000                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15001                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15002                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15003                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15004                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15005                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15006                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15007                } else {
15008                    // Override with defaults if needed.
15009                    loc = installLocationPolicy(pkgLite);
15010                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15011                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15012                    } else if (!onSd && !onInt) {
15013                        // Override install location with flags
15014                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15015                            // Set the flag to install on external media.
15016                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15017                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15018                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15019                            if (DEBUG_EPHEMERAL) {
15020                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15021                            }
15022                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15023                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15024                                    |PackageManager.INSTALL_INTERNAL);
15025                        } else {
15026                            // Make sure the flag for installing on external
15027                            // media is unset
15028                            installFlags |= PackageManager.INSTALL_INTERNAL;
15029                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15030                        }
15031                    }
15032                }
15033            }
15034
15035            final InstallArgs args = createInstallArgs(this);
15036            mArgs = args;
15037
15038            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15039                // TODO: http://b/22976637
15040                // Apps installed for "all" users use the device owner to verify the app
15041                UserHandle verifierUser = getUser();
15042                if (verifierUser == UserHandle.ALL) {
15043                    verifierUser = UserHandle.SYSTEM;
15044                }
15045
15046                /*
15047                 * Determine if we have any installed package verifiers. If we
15048                 * do, then we'll defer to them to verify the packages.
15049                 */
15050                final int requiredUid = mRequiredVerifierPackage == null ? -1
15051                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15052                                verifierUser.getIdentifier());
15053                if (!origin.existing && requiredUid != -1
15054                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15055                    final Intent verification = new Intent(
15056                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15057                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15058                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15059                            PACKAGE_MIME_TYPE);
15060                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15061
15062                    // Query all live verifiers based on current user state
15063                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15064                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15065
15066                    if (DEBUG_VERIFY) {
15067                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15068                                + verification.toString() + " with " + pkgLite.verifiers.length
15069                                + " optional verifiers");
15070                    }
15071
15072                    final int verificationId = mPendingVerificationToken++;
15073
15074                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15075
15076                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15077                            installerPackageName);
15078
15079                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15080                            installFlags);
15081
15082                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15083                            pkgLite.packageName);
15084
15085                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15086                            pkgLite.versionCode);
15087
15088                    if (verificationInfo != null) {
15089                        if (verificationInfo.originatingUri != null) {
15090                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15091                                    verificationInfo.originatingUri);
15092                        }
15093                        if (verificationInfo.referrer != null) {
15094                            verification.putExtra(Intent.EXTRA_REFERRER,
15095                                    verificationInfo.referrer);
15096                        }
15097                        if (verificationInfo.originatingUid >= 0) {
15098                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15099                                    verificationInfo.originatingUid);
15100                        }
15101                        if (verificationInfo.installerUid >= 0) {
15102                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15103                                    verificationInfo.installerUid);
15104                        }
15105                    }
15106
15107                    final PackageVerificationState verificationState = new PackageVerificationState(
15108                            requiredUid, args);
15109
15110                    mPendingVerification.append(verificationId, verificationState);
15111
15112                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15113                            receivers, verificationState);
15114
15115                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15116                    final long idleDuration = getVerificationTimeout();
15117
15118                    /*
15119                     * If any sufficient verifiers were listed in the package
15120                     * manifest, attempt to ask them.
15121                     */
15122                    if (sufficientVerifiers != null) {
15123                        final int N = sufficientVerifiers.size();
15124                        if (N == 0) {
15125                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15126                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15127                        } else {
15128                            for (int i = 0; i < N; i++) {
15129                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15130                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15131                                        verifierComponent.getPackageName(), idleDuration,
15132                                        verifierUser.getIdentifier(), false, "package verifier");
15133
15134                                final Intent sufficientIntent = new Intent(verification);
15135                                sufficientIntent.setComponent(verifierComponent);
15136                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15137                            }
15138                        }
15139                    }
15140
15141                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15142                            mRequiredVerifierPackage, receivers);
15143                    if (ret == PackageManager.INSTALL_SUCCEEDED
15144                            && mRequiredVerifierPackage != null) {
15145                        Trace.asyncTraceBegin(
15146                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15147                        /*
15148                         * Send the intent to the required verification agent,
15149                         * but only start the verification timeout after the
15150                         * target BroadcastReceivers have run.
15151                         */
15152                        verification.setComponent(requiredVerifierComponent);
15153                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15154                                mRequiredVerifierPackage, idleDuration,
15155                                verifierUser.getIdentifier(), false, "package verifier");
15156                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15157                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15158                                new BroadcastReceiver() {
15159                                    @Override
15160                                    public void onReceive(Context context, Intent intent) {
15161                                        final Message msg = mHandler
15162                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15163                                        msg.arg1 = verificationId;
15164                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15165                                    }
15166                                }, null, 0, null, null);
15167
15168                        /*
15169                         * We don't want the copy to proceed until verification
15170                         * succeeds, so null out this field.
15171                         */
15172                        mArgs = null;
15173                    }
15174                } else {
15175                    /*
15176                     * No package verification is enabled, so immediately start
15177                     * the remote call to initiate copy using temporary file.
15178                     */
15179                    ret = args.copyApk(mContainerService, true);
15180                }
15181            }
15182
15183            mRet = ret;
15184        }
15185
15186        @Override
15187        void handleReturnCode() {
15188            // If mArgs is null, then MCS couldn't be reached. When it
15189            // reconnects, it will try again to install. At that point, this
15190            // will succeed.
15191            if (mArgs != null) {
15192                processPendingInstall(mArgs, mRet);
15193            }
15194        }
15195
15196        @Override
15197        void handleServiceError() {
15198            mArgs = createInstallArgs(this);
15199            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15200        }
15201
15202        public boolean isForwardLocked() {
15203            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15204        }
15205    }
15206
15207    /**
15208     * Used during creation of InstallArgs
15209     *
15210     * @param installFlags package installation flags
15211     * @return true if should be installed on external storage
15212     */
15213    private static boolean installOnExternalAsec(int installFlags) {
15214        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15215            return false;
15216        }
15217        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15218            return true;
15219        }
15220        return false;
15221    }
15222
15223    /**
15224     * Used during creation of InstallArgs
15225     *
15226     * @param installFlags package installation flags
15227     * @return true if should be installed as forward locked
15228     */
15229    private static boolean installForwardLocked(int installFlags) {
15230        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15231    }
15232
15233    private InstallArgs createInstallArgs(InstallParams params) {
15234        if (params.move != null) {
15235            return new MoveInstallArgs(params);
15236        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15237            return new AsecInstallArgs(params);
15238        } else {
15239            return new FileInstallArgs(params);
15240        }
15241    }
15242
15243    /**
15244     * Create args that describe an existing installed package. Typically used
15245     * when cleaning up old installs, or used as a move source.
15246     */
15247    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15248            String resourcePath, String[] instructionSets) {
15249        final boolean isInAsec;
15250        if (installOnExternalAsec(installFlags)) {
15251            /* Apps on SD card are always in ASEC containers. */
15252            isInAsec = true;
15253        } else if (installForwardLocked(installFlags)
15254                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15255            /*
15256             * Forward-locked apps are only in ASEC containers if they're the
15257             * new style
15258             */
15259            isInAsec = true;
15260        } else {
15261            isInAsec = false;
15262        }
15263
15264        if (isInAsec) {
15265            return new AsecInstallArgs(codePath, instructionSets,
15266                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15267        } else {
15268            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15269        }
15270    }
15271
15272    static abstract class InstallArgs {
15273        /** @see InstallParams#origin */
15274        final OriginInfo origin;
15275        /** @see InstallParams#move */
15276        final MoveInfo move;
15277
15278        final IPackageInstallObserver2 observer;
15279        // Always refers to PackageManager flags only
15280        final int installFlags;
15281        final String installerPackageName;
15282        final String volumeUuid;
15283        final UserHandle user;
15284        final String abiOverride;
15285        final String[] installGrantPermissions;
15286        /** If non-null, drop an async trace when the install completes */
15287        final String traceMethod;
15288        final int traceCookie;
15289        final Certificate[][] certificates;
15290        final int installReason;
15291
15292        // The list of instruction sets supported by this app. This is currently
15293        // only used during the rmdex() phase to clean up resources. We can get rid of this
15294        // if we move dex files under the common app path.
15295        /* nullable */ String[] instructionSets;
15296
15297        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15298                int installFlags, String installerPackageName, String volumeUuid,
15299                UserHandle user, String[] instructionSets,
15300                String abiOverride, String[] installGrantPermissions,
15301                String traceMethod, int traceCookie, Certificate[][] certificates,
15302                int installReason) {
15303            this.origin = origin;
15304            this.move = move;
15305            this.installFlags = installFlags;
15306            this.observer = observer;
15307            this.installerPackageName = installerPackageName;
15308            this.volumeUuid = volumeUuid;
15309            this.user = user;
15310            this.instructionSets = instructionSets;
15311            this.abiOverride = abiOverride;
15312            this.installGrantPermissions = installGrantPermissions;
15313            this.traceMethod = traceMethod;
15314            this.traceCookie = traceCookie;
15315            this.certificates = certificates;
15316            this.installReason = installReason;
15317        }
15318
15319        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15320        abstract int doPreInstall(int status);
15321
15322        /**
15323         * Rename package into final resting place. All paths on the given
15324         * scanned package should be updated to reflect the rename.
15325         */
15326        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15327        abstract int doPostInstall(int status, int uid);
15328
15329        /** @see PackageSettingBase#codePathString */
15330        abstract String getCodePath();
15331        /** @see PackageSettingBase#resourcePathString */
15332        abstract String getResourcePath();
15333
15334        // Need installer lock especially for dex file removal.
15335        abstract void cleanUpResourcesLI();
15336        abstract boolean doPostDeleteLI(boolean delete);
15337
15338        /**
15339         * Called before the source arguments are copied. This is used mostly
15340         * for MoveParams when it needs to read the source file to put it in the
15341         * destination.
15342         */
15343        int doPreCopy() {
15344            return PackageManager.INSTALL_SUCCEEDED;
15345        }
15346
15347        /**
15348         * Called after the source arguments are copied. This is used mostly for
15349         * MoveParams when it needs to read the source file to put it in the
15350         * destination.
15351         */
15352        int doPostCopy(int uid) {
15353            return PackageManager.INSTALL_SUCCEEDED;
15354        }
15355
15356        protected boolean isFwdLocked() {
15357            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15358        }
15359
15360        protected boolean isExternalAsec() {
15361            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15362        }
15363
15364        protected boolean isEphemeral() {
15365            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15366        }
15367
15368        UserHandle getUser() {
15369            return user;
15370        }
15371    }
15372
15373    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15374        if (!allCodePaths.isEmpty()) {
15375            if (instructionSets == null) {
15376                throw new IllegalStateException("instructionSet == null");
15377            }
15378            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15379            for (String codePath : allCodePaths) {
15380                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15381                    try {
15382                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15383                    } catch (InstallerException ignored) {
15384                    }
15385                }
15386            }
15387        }
15388    }
15389
15390    /**
15391     * Logic to handle installation of non-ASEC applications, including copying
15392     * and renaming logic.
15393     */
15394    class FileInstallArgs extends InstallArgs {
15395        private File codeFile;
15396        private File resourceFile;
15397
15398        // Example topology:
15399        // /data/app/com.example/base.apk
15400        // /data/app/com.example/split_foo.apk
15401        // /data/app/com.example/lib/arm/libfoo.so
15402        // /data/app/com.example/lib/arm64/libfoo.so
15403        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15404
15405        /** New install */
15406        FileInstallArgs(InstallParams params) {
15407            super(params.origin, params.move, params.observer, params.installFlags,
15408                    params.installerPackageName, params.volumeUuid,
15409                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15410                    params.grantedRuntimePermissions,
15411                    params.traceMethod, params.traceCookie, params.certificates,
15412                    params.installReason);
15413            if (isFwdLocked()) {
15414                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15415            }
15416        }
15417
15418        /** Existing install */
15419        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15420            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15421                    null, null, null, 0, null /*certificates*/,
15422                    PackageManager.INSTALL_REASON_UNKNOWN);
15423            this.codeFile = (codePath != null) ? new File(codePath) : null;
15424            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15425        }
15426
15427        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15428            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15429            try {
15430                return doCopyApk(imcs, temp);
15431            } finally {
15432                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15433            }
15434        }
15435
15436        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15437            if (origin.staged) {
15438                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15439                codeFile = origin.file;
15440                resourceFile = origin.file;
15441                return PackageManager.INSTALL_SUCCEEDED;
15442            }
15443
15444            try {
15445                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15446                final File tempDir =
15447                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15448                codeFile = tempDir;
15449                resourceFile = tempDir;
15450            } catch (IOException e) {
15451                Slog.w(TAG, "Failed to create copy file: " + e);
15452                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15453            }
15454
15455            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15456                @Override
15457                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15458                    if (!FileUtils.isValidExtFilename(name)) {
15459                        throw new IllegalArgumentException("Invalid filename: " + name);
15460                    }
15461                    try {
15462                        final File file = new File(codeFile, name);
15463                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15464                                O_RDWR | O_CREAT, 0644);
15465                        Os.chmod(file.getAbsolutePath(), 0644);
15466                        return new ParcelFileDescriptor(fd);
15467                    } catch (ErrnoException e) {
15468                        throw new RemoteException("Failed to open: " + e.getMessage());
15469                    }
15470                }
15471            };
15472
15473            int ret = PackageManager.INSTALL_SUCCEEDED;
15474            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15475            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15476                Slog.e(TAG, "Failed to copy package");
15477                return ret;
15478            }
15479
15480            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15481            NativeLibraryHelper.Handle handle = null;
15482            try {
15483                handle = NativeLibraryHelper.Handle.create(codeFile);
15484                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15485                        abiOverride);
15486            } catch (IOException e) {
15487                Slog.e(TAG, "Copying native libraries failed", e);
15488                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15489            } finally {
15490                IoUtils.closeQuietly(handle);
15491            }
15492
15493            return ret;
15494        }
15495
15496        int doPreInstall(int status) {
15497            if (status != PackageManager.INSTALL_SUCCEEDED) {
15498                cleanUp();
15499            }
15500            return status;
15501        }
15502
15503        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15504            if (status != PackageManager.INSTALL_SUCCEEDED) {
15505                cleanUp();
15506                return false;
15507            }
15508
15509            final File targetDir = codeFile.getParentFile();
15510            final File beforeCodeFile = codeFile;
15511            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15512
15513            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15514            try {
15515                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15516            } catch (ErrnoException e) {
15517                Slog.w(TAG, "Failed to rename", e);
15518                return false;
15519            }
15520
15521            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15522                Slog.w(TAG, "Failed to restorecon");
15523                return false;
15524            }
15525
15526            // Reflect the rename internally
15527            codeFile = afterCodeFile;
15528            resourceFile = afterCodeFile;
15529
15530            // Reflect the rename in scanned details
15531            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15532            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15533                    afterCodeFile, pkg.baseCodePath));
15534            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15535                    afterCodeFile, pkg.splitCodePaths));
15536
15537            // Reflect the rename in app info
15538            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15539            pkg.setApplicationInfoCodePath(pkg.codePath);
15540            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15541            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15542            pkg.setApplicationInfoResourcePath(pkg.codePath);
15543            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15544            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15545
15546            return true;
15547        }
15548
15549        int doPostInstall(int status, int uid) {
15550            if (status != PackageManager.INSTALL_SUCCEEDED) {
15551                cleanUp();
15552            }
15553            return status;
15554        }
15555
15556        @Override
15557        String getCodePath() {
15558            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15559        }
15560
15561        @Override
15562        String getResourcePath() {
15563            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15564        }
15565
15566        private boolean cleanUp() {
15567            if (codeFile == null || !codeFile.exists()) {
15568                return false;
15569            }
15570
15571            removeCodePathLI(codeFile);
15572
15573            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15574                resourceFile.delete();
15575            }
15576
15577            return true;
15578        }
15579
15580        void cleanUpResourcesLI() {
15581            // Try enumerating all code paths before deleting
15582            List<String> allCodePaths = Collections.EMPTY_LIST;
15583            if (codeFile != null && codeFile.exists()) {
15584                try {
15585                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15586                    allCodePaths = pkg.getAllCodePaths();
15587                } catch (PackageParserException e) {
15588                    // Ignored; we tried our best
15589                }
15590            }
15591
15592            cleanUp();
15593            removeDexFiles(allCodePaths, instructionSets);
15594        }
15595
15596        boolean doPostDeleteLI(boolean delete) {
15597            // XXX err, shouldn't we respect the delete flag?
15598            cleanUpResourcesLI();
15599            return true;
15600        }
15601    }
15602
15603    private boolean isAsecExternal(String cid) {
15604        final String asecPath = PackageHelper.getSdFilesystem(cid);
15605        return !asecPath.startsWith(mAsecInternalPath);
15606    }
15607
15608    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15609            PackageManagerException {
15610        if (copyRet < 0) {
15611            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15612                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15613                throw new PackageManagerException(copyRet, message);
15614            }
15615        }
15616    }
15617
15618    /**
15619     * Extract the StorageManagerService "container ID" from the full code path of an
15620     * .apk.
15621     */
15622    static String cidFromCodePath(String fullCodePath) {
15623        int eidx = fullCodePath.lastIndexOf("/");
15624        String subStr1 = fullCodePath.substring(0, eidx);
15625        int sidx = subStr1.lastIndexOf("/");
15626        return subStr1.substring(sidx+1, eidx);
15627    }
15628
15629    /**
15630     * Logic to handle installation of ASEC applications, including copying and
15631     * renaming logic.
15632     */
15633    class AsecInstallArgs extends InstallArgs {
15634        static final String RES_FILE_NAME = "pkg.apk";
15635        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15636
15637        String cid;
15638        String packagePath;
15639        String resourcePath;
15640
15641        /** New install */
15642        AsecInstallArgs(InstallParams params) {
15643            super(params.origin, params.move, params.observer, params.installFlags,
15644                    params.installerPackageName, params.volumeUuid,
15645                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15646                    params.grantedRuntimePermissions,
15647                    params.traceMethod, params.traceCookie, params.certificates,
15648                    params.installReason);
15649        }
15650
15651        /** Existing install */
15652        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15653                        boolean isExternal, boolean isForwardLocked) {
15654            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15655                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15656                    instructionSets, null, null, null, 0, null /*certificates*/,
15657                    PackageManager.INSTALL_REASON_UNKNOWN);
15658            // Hackily pretend we're still looking at a full code path
15659            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15660                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15661            }
15662
15663            // Extract cid from fullCodePath
15664            int eidx = fullCodePath.lastIndexOf("/");
15665            String subStr1 = fullCodePath.substring(0, eidx);
15666            int sidx = subStr1.lastIndexOf("/");
15667            cid = subStr1.substring(sidx+1, eidx);
15668            setMountPath(subStr1);
15669        }
15670
15671        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15672            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15673                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15674                    instructionSets, null, null, null, 0, null /*certificates*/,
15675                    PackageManager.INSTALL_REASON_UNKNOWN);
15676            this.cid = cid;
15677            setMountPath(PackageHelper.getSdDir(cid));
15678        }
15679
15680        void createCopyFile() {
15681            cid = mInstallerService.allocateExternalStageCidLegacy();
15682        }
15683
15684        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15685            if (origin.staged && origin.cid != null) {
15686                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15687                cid = origin.cid;
15688                setMountPath(PackageHelper.getSdDir(cid));
15689                return PackageManager.INSTALL_SUCCEEDED;
15690            }
15691
15692            if (temp) {
15693                createCopyFile();
15694            } else {
15695                /*
15696                 * Pre-emptively destroy the container since it's destroyed if
15697                 * copying fails due to it existing anyway.
15698                 */
15699                PackageHelper.destroySdDir(cid);
15700            }
15701
15702            final String newMountPath = imcs.copyPackageToContainer(
15703                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15704                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15705
15706            if (newMountPath != null) {
15707                setMountPath(newMountPath);
15708                return PackageManager.INSTALL_SUCCEEDED;
15709            } else {
15710                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15711            }
15712        }
15713
15714        @Override
15715        String getCodePath() {
15716            return packagePath;
15717        }
15718
15719        @Override
15720        String getResourcePath() {
15721            return resourcePath;
15722        }
15723
15724        int doPreInstall(int status) {
15725            if (status != PackageManager.INSTALL_SUCCEEDED) {
15726                // Destroy container
15727                PackageHelper.destroySdDir(cid);
15728            } else {
15729                boolean mounted = PackageHelper.isContainerMounted(cid);
15730                if (!mounted) {
15731                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15732                            Process.SYSTEM_UID);
15733                    if (newMountPath != null) {
15734                        setMountPath(newMountPath);
15735                    } else {
15736                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15737                    }
15738                }
15739            }
15740            return status;
15741        }
15742
15743        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15744            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15745            String newMountPath = null;
15746            if (PackageHelper.isContainerMounted(cid)) {
15747                // Unmount the container
15748                if (!PackageHelper.unMountSdDir(cid)) {
15749                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15750                    return false;
15751                }
15752            }
15753            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15754                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15755                        " which might be stale. Will try to clean up.");
15756                // Clean up the stale container and proceed to recreate.
15757                if (!PackageHelper.destroySdDir(newCacheId)) {
15758                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15759                    return false;
15760                }
15761                // Successfully cleaned up stale container. Try to rename again.
15762                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15763                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15764                            + " inspite of cleaning it up.");
15765                    return false;
15766                }
15767            }
15768            if (!PackageHelper.isContainerMounted(newCacheId)) {
15769                Slog.w(TAG, "Mounting container " + newCacheId);
15770                newMountPath = PackageHelper.mountSdDir(newCacheId,
15771                        getEncryptKey(), Process.SYSTEM_UID);
15772            } else {
15773                newMountPath = PackageHelper.getSdDir(newCacheId);
15774            }
15775            if (newMountPath == null) {
15776                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15777                return false;
15778            }
15779            Log.i(TAG, "Succesfully renamed " + cid +
15780                    " to " + newCacheId +
15781                    " at new path: " + newMountPath);
15782            cid = newCacheId;
15783
15784            final File beforeCodeFile = new File(packagePath);
15785            setMountPath(newMountPath);
15786            final File afterCodeFile = new File(packagePath);
15787
15788            // Reflect the rename in scanned details
15789            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15790            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15791                    afterCodeFile, pkg.baseCodePath));
15792            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15793                    afterCodeFile, pkg.splitCodePaths));
15794
15795            // Reflect the rename in app info
15796            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15797            pkg.setApplicationInfoCodePath(pkg.codePath);
15798            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15799            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15800            pkg.setApplicationInfoResourcePath(pkg.codePath);
15801            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15802            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15803
15804            return true;
15805        }
15806
15807        private void setMountPath(String mountPath) {
15808            final File mountFile = new File(mountPath);
15809
15810            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15811            if (monolithicFile.exists()) {
15812                packagePath = monolithicFile.getAbsolutePath();
15813                if (isFwdLocked()) {
15814                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15815                } else {
15816                    resourcePath = packagePath;
15817                }
15818            } else {
15819                packagePath = mountFile.getAbsolutePath();
15820                resourcePath = packagePath;
15821            }
15822        }
15823
15824        int doPostInstall(int status, int uid) {
15825            if (status != PackageManager.INSTALL_SUCCEEDED) {
15826                cleanUp();
15827            } else {
15828                final int groupOwner;
15829                final String protectedFile;
15830                if (isFwdLocked()) {
15831                    groupOwner = UserHandle.getSharedAppGid(uid);
15832                    protectedFile = RES_FILE_NAME;
15833                } else {
15834                    groupOwner = -1;
15835                    protectedFile = null;
15836                }
15837
15838                if (uid < Process.FIRST_APPLICATION_UID
15839                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15840                    Slog.e(TAG, "Failed to finalize " + cid);
15841                    PackageHelper.destroySdDir(cid);
15842                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15843                }
15844
15845                boolean mounted = PackageHelper.isContainerMounted(cid);
15846                if (!mounted) {
15847                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15848                }
15849            }
15850            return status;
15851        }
15852
15853        private void cleanUp() {
15854            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15855
15856            // Destroy secure container
15857            PackageHelper.destroySdDir(cid);
15858        }
15859
15860        private List<String> getAllCodePaths() {
15861            final File codeFile = new File(getCodePath());
15862            if (codeFile != null && codeFile.exists()) {
15863                try {
15864                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15865                    return pkg.getAllCodePaths();
15866                } catch (PackageParserException e) {
15867                    // Ignored; we tried our best
15868                }
15869            }
15870            return Collections.EMPTY_LIST;
15871        }
15872
15873        void cleanUpResourcesLI() {
15874            // Enumerate all code paths before deleting
15875            cleanUpResourcesLI(getAllCodePaths());
15876        }
15877
15878        private void cleanUpResourcesLI(List<String> allCodePaths) {
15879            cleanUp();
15880            removeDexFiles(allCodePaths, instructionSets);
15881        }
15882
15883        String getPackageName() {
15884            return getAsecPackageName(cid);
15885        }
15886
15887        boolean doPostDeleteLI(boolean delete) {
15888            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15889            final List<String> allCodePaths = getAllCodePaths();
15890            boolean mounted = PackageHelper.isContainerMounted(cid);
15891            if (mounted) {
15892                // Unmount first
15893                if (PackageHelper.unMountSdDir(cid)) {
15894                    mounted = false;
15895                }
15896            }
15897            if (!mounted && delete) {
15898                cleanUpResourcesLI(allCodePaths);
15899            }
15900            return !mounted;
15901        }
15902
15903        @Override
15904        int doPreCopy() {
15905            if (isFwdLocked()) {
15906                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15907                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15908                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15909                }
15910            }
15911
15912            return PackageManager.INSTALL_SUCCEEDED;
15913        }
15914
15915        @Override
15916        int doPostCopy(int uid) {
15917            if (isFwdLocked()) {
15918                if (uid < Process.FIRST_APPLICATION_UID
15919                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15920                                RES_FILE_NAME)) {
15921                    Slog.e(TAG, "Failed to finalize " + cid);
15922                    PackageHelper.destroySdDir(cid);
15923                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15924                }
15925            }
15926
15927            return PackageManager.INSTALL_SUCCEEDED;
15928        }
15929    }
15930
15931    /**
15932     * Logic to handle movement of existing installed applications.
15933     */
15934    class MoveInstallArgs extends InstallArgs {
15935        private File codeFile;
15936        private File resourceFile;
15937
15938        /** New install */
15939        MoveInstallArgs(InstallParams params) {
15940            super(params.origin, params.move, params.observer, params.installFlags,
15941                    params.installerPackageName, params.volumeUuid,
15942                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15943                    params.grantedRuntimePermissions,
15944                    params.traceMethod, params.traceCookie, params.certificates,
15945                    params.installReason);
15946        }
15947
15948        int copyApk(IMediaContainerService imcs, boolean temp) {
15949            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15950                    + move.fromUuid + " to " + move.toUuid);
15951            synchronized (mInstaller) {
15952                try {
15953                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15954                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15955                } catch (InstallerException e) {
15956                    Slog.w(TAG, "Failed to move app", e);
15957                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15958                }
15959            }
15960
15961            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15962            resourceFile = codeFile;
15963            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15964
15965            return PackageManager.INSTALL_SUCCEEDED;
15966        }
15967
15968        int doPreInstall(int status) {
15969            if (status != PackageManager.INSTALL_SUCCEEDED) {
15970                cleanUp(move.toUuid);
15971            }
15972            return status;
15973        }
15974
15975        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15976            if (status != PackageManager.INSTALL_SUCCEEDED) {
15977                cleanUp(move.toUuid);
15978                return false;
15979            }
15980
15981            // Reflect the move in app info
15982            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15983            pkg.setApplicationInfoCodePath(pkg.codePath);
15984            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15985            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15986            pkg.setApplicationInfoResourcePath(pkg.codePath);
15987            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15988            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15989
15990            return true;
15991        }
15992
15993        int doPostInstall(int status, int uid) {
15994            if (status == PackageManager.INSTALL_SUCCEEDED) {
15995                cleanUp(move.fromUuid);
15996            } else {
15997                cleanUp(move.toUuid);
15998            }
15999            return status;
16000        }
16001
16002        @Override
16003        String getCodePath() {
16004            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16005        }
16006
16007        @Override
16008        String getResourcePath() {
16009            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16010        }
16011
16012        private boolean cleanUp(String volumeUuid) {
16013            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16014                    move.dataAppName);
16015            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16016            final int[] userIds = sUserManager.getUserIds();
16017            synchronized (mInstallLock) {
16018                // Clean up both app data and code
16019                // All package moves are frozen until finished
16020                for (int userId : userIds) {
16021                    try {
16022                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16023                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16024                    } catch (InstallerException e) {
16025                        Slog.w(TAG, String.valueOf(e));
16026                    }
16027                }
16028                removeCodePathLI(codeFile);
16029            }
16030            return true;
16031        }
16032
16033        void cleanUpResourcesLI() {
16034            throw new UnsupportedOperationException();
16035        }
16036
16037        boolean doPostDeleteLI(boolean delete) {
16038            throw new UnsupportedOperationException();
16039        }
16040    }
16041
16042    static String getAsecPackageName(String packageCid) {
16043        int idx = packageCid.lastIndexOf("-");
16044        if (idx == -1) {
16045            return packageCid;
16046        }
16047        return packageCid.substring(0, idx);
16048    }
16049
16050    // Utility method used to create code paths based on package name and available index.
16051    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16052        String idxStr = "";
16053        int idx = 1;
16054        // Fall back to default value of idx=1 if prefix is not
16055        // part of oldCodePath
16056        if (oldCodePath != null) {
16057            String subStr = oldCodePath;
16058            // Drop the suffix right away
16059            if (suffix != null && subStr.endsWith(suffix)) {
16060                subStr = subStr.substring(0, subStr.length() - suffix.length());
16061            }
16062            // If oldCodePath already contains prefix find out the
16063            // ending index to either increment or decrement.
16064            int sidx = subStr.lastIndexOf(prefix);
16065            if (sidx != -1) {
16066                subStr = subStr.substring(sidx + prefix.length());
16067                if (subStr != null) {
16068                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16069                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16070                    }
16071                    try {
16072                        idx = Integer.parseInt(subStr);
16073                        if (idx <= 1) {
16074                            idx++;
16075                        } else {
16076                            idx--;
16077                        }
16078                    } catch(NumberFormatException e) {
16079                    }
16080                }
16081            }
16082        }
16083        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16084        return prefix + idxStr;
16085    }
16086
16087    private File getNextCodePath(File targetDir, String packageName) {
16088        File result;
16089        SecureRandom random = new SecureRandom();
16090        byte[] bytes = new byte[16];
16091        do {
16092            random.nextBytes(bytes);
16093            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16094            result = new File(targetDir, packageName + "-" + suffix);
16095        } while (result.exists());
16096        return result;
16097    }
16098
16099    // Utility method that returns the relative package path with respect
16100    // to the installation directory. Like say for /data/data/com.test-1.apk
16101    // string com.test-1 is returned.
16102    static String deriveCodePathName(String codePath) {
16103        if (codePath == null) {
16104            return null;
16105        }
16106        final File codeFile = new File(codePath);
16107        final String name = codeFile.getName();
16108        if (codeFile.isDirectory()) {
16109            return name;
16110        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16111            final int lastDot = name.lastIndexOf('.');
16112            return name.substring(0, lastDot);
16113        } else {
16114            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16115            return null;
16116        }
16117    }
16118
16119    static class PackageInstalledInfo {
16120        String name;
16121        int uid;
16122        // The set of users that originally had this package installed.
16123        int[] origUsers;
16124        // The set of users that now have this package installed.
16125        int[] newUsers;
16126        PackageParser.Package pkg;
16127        int returnCode;
16128        String returnMsg;
16129        PackageRemovedInfo removedInfo;
16130        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16131
16132        public void setError(int code, String msg) {
16133            setReturnCode(code);
16134            setReturnMessage(msg);
16135            Slog.w(TAG, msg);
16136        }
16137
16138        public void setError(String msg, PackageParserException e) {
16139            setReturnCode(e.error);
16140            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16141            Slog.w(TAG, msg, e);
16142        }
16143
16144        public void setError(String msg, PackageManagerException e) {
16145            returnCode = e.error;
16146            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16147            Slog.w(TAG, msg, e);
16148        }
16149
16150        public void setReturnCode(int returnCode) {
16151            this.returnCode = returnCode;
16152            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16153            for (int i = 0; i < childCount; i++) {
16154                addedChildPackages.valueAt(i).returnCode = returnCode;
16155            }
16156        }
16157
16158        private void setReturnMessage(String returnMsg) {
16159            this.returnMsg = returnMsg;
16160            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16161            for (int i = 0; i < childCount; i++) {
16162                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16163            }
16164        }
16165
16166        // In some error cases we want to convey more info back to the observer
16167        String origPackage;
16168        String origPermission;
16169    }
16170
16171    /*
16172     * Install a non-existing package.
16173     */
16174    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16175            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16176            PackageInstalledInfo res, int installReason) {
16177        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16178
16179        // Remember this for later, in case we need to rollback this install
16180        String pkgName = pkg.packageName;
16181
16182        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16183
16184        synchronized(mPackages) {
16185            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16186            if (renamedPackage != null) {
16187                // A package with the same name is already installed, though
16188                // it has been renamed to an older name.  The package we
16189                // are trying to install should be installed as an update to
16190                // the existing one, but that has not been requested, so bail.
16191                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16192                        + " without first uninstalling package running as "
16193                        + renamedPackage);
16194                return;
16195            }
16196            if (mPackages.containsKey(pkgName)) {
16197                // Don't allow installation over an existing package with the same name.
16198                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16199                        + " without first uninstalling.");
16200                return;
16201            }
16202        }
16203
16204        try {
16205            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16206                    System.currentTimeMillis(), user);
16207
16208            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16209
16210            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16211                prepareAppDataAfterInstallLIF(newPackage);
16212
16213            } else {
16214                // Remove package from internal structures, but keep around any
16215                // data that might have already existed
16216                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16217                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16218            }
16219        } catch (PackageManagerException e) {
16220            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16221        }
16222
16223        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16224    }
16225
16226    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16227        // Can't rotate keys during boot or if sharedUser.
16228        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16229                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16230            return false;
16231        }
16232        // app is using upgradeKeySets; make sure all are valid
16233        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16234        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16235        for (int i = 0; i < upgradeKeySets.length; i++) {
16236            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16237                Slog.wtf(TAG, "Package "
16238                         + (oldPs.name != null ? oldPs.name : "<null>")
16239                         + " contains upgrade-key-set reference to unknown key-set: "
16240                         + upgradeKeySets[i]
16241                         + " reverting to signatures check.");
16242                return false;
16243            }
16244        }
16245        return true;
16246    }
16247
16248    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16249        // Upgrade keysets are being used.  Determine if new package has a superset of the
16250        // required keys.
16251        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16252        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16253        for (int i = 0; i < upgradeKeySets.length; i++) {
16254            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16255            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16256                return true;
16257            }
16258        }
16259        return false;
16260    }
16261
16262    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16263        try (DigestInputStream digestStream =
16264                new DigestInputStream(new FileInputStream(file), digest)) {
16265            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16266        }
16267    }
16268
16269    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16270            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16271            int installReason) {
16272        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16273
16274        final PackageParser.Package oldPackage;
16275        final PackageSetting ps;
16276        final String pkgName = pkg.packageName;
16277        final int[] allUsers;
16278        final int[] installedUsers;
16279
16280        synchronized(mPackages) {
16281            oldPackage = mPackages.get(pkgName);
16282            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16283
16284            // don't allow upgrade to target a release SDK from a pre-release SDK
16285            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16286                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16287            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16288                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16289            if (oldTargetsPreRelease
16290                    && !newTargetsPreRelease
16291                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16292                Slog.w(TAG, "Can't install package targeting released sdk");
16293                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16294                return;
16295            }
16296
16297            ps = mSettings.mPackages.get(pkgName);
16298
16299            // verify signatures are valid
16300            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16301                if (!checkUpgradeKeySetLP(ps, pkg)) {
16302                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16303                            "New package not signed by keys specified by upgrade-keysets: "
16304                                    + pkgName);
16305                    return;
16306                }
16307            } else {
16308                // default to original signature matching
16309                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16310                        != PackageManager.SIGNATURE_MATCH) {
16311                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16312                            "New package has a different signature: " + pkgName);
16313                    return;
16314                }
16315            }
16316
16317            // don't allow a system upgrade unless the upgrade hash matches
16318            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16319                byte[] digestBytes = null;
16320                try {
16321                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16322                    updateDigest(digest, new File(pkg.baseCodePath));
16323                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16324                        for (String path : pkg.splitCodePaths) {
16325                            updateDigest(digest, new File(path));
16326                        }
16327                    }
16328                    digestBytes = digest.digest();
16329                } catch (NoSuchAlgorithmException | IOException e) {
16330                    res.setError(INSTALL_FAILED_INVALID_APK,
16331                            "Could not compute hash: " + pkgName);
16332                    return;
16333                }
16334                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16335                    res.setError(INSTALL_FAILED_INVALID_APK,
16336                            "New package fails restrict-update check: " + pkgName);
16337                    return;
16338                }
16339                // retain upgrade restriction
16340                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16341            }
16342
16343            // Check for shared user id changes
16344            String invalidPackageName =
16345                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16346            if (invalidPackageName != null) {
16347                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16348                        "Package " + invalidPackageName + " tried to change user "
16349                                + oldPackage.mSharedUserId);
16350                return;
16351            }
16352
16353            // In case of rollback, remember per-user/profile install state
16354            allUsers = sUserManager.getUserIds();
16355            installedUsers = ps.queryInstalledUsers(allUsers, true);
16356
16357            // don't allow an upgrade from full to ephemeral
16358            if (isInstantApp) {
16359                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16360                    for (int currentUser : allUsers) {
16361                        if (!ps.getInstantApp(currentUser)) {
16362                            // can't downgrade from full to instant
16363                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16364                                    + " for user: " + currentUser);
16365                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16366                            return;
16367                        }
16368                    }
16369                } else if (!ps.getInstantApp(user.getIdentifier())) {
16370                    // can't downgrade from full to instant
16371                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16372                            + " for user: " + user.getIdentifier());
16373                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16374                    return;
16375                }
16376            }
16377        }
16378
16379        // Update what is removed
16380        res.removedInfo = new PackageRemovedInfo(this);
16381        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16382        res.removedInfo.removedPackage = oldPackage.packageName;
16383        res.removedInfo.installerPackageName = ps.installerPackageName;
16384        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16385        res.removedInfo.isUpdate = true;
16386        res.removedInfo.origUsers = installedUsers;
16387        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16388        for (int i = 0; i < installedUsers.length; i++) {
16389            final int userId = installedUsers[i];
16390            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16391        }
16392
16393        final int childCount = (oldPackage.childPackages != null)
16394                ? oldPackage.childPackages.size() : 0;
16395        for (int i = 0; i < childCount; i++) {
16396            boolean childPackageUpdated = false;
16397            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16398            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16399            if (res.addedChildPackages != null) {
16400                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16401                if (childRes != null) {
16402                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16403                    childRes.removedInfo.removedPackage = childPkg.packageName;
16404                    if (childPs != null) {
16405                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16406                    }
16407                    childRes.removedInfo.isUpdate = true;
16408                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16409                    childPackageUpdated = true;
16410                }
16411            }
16412            if (!childPackageUpdated) {
16413                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16414                childRemovedRes.removedPackage = childPkg.packageName;
16415                if (childPs != null) {
16416                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16417                }
16418                childRemovedRes.isUpdate = false;
16419                childRemovedRes.dataRemoved = true;
16420                synchronized (mPackages) {
16421                    if (childPs != null) {
16422                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16423                    }
16424                }
16425                if (res.removedInfo.removedChildPackages == null) {
16426                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16427                }
16428                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16429            }
16430        }
16431
16432        boolean sysPkg = (isSystemApp(oldPackage));
16433        if (sysPkg) {
16434            // Set the system/privileged flags as needed
16435            final boolean privileged =
16436                    (oldPackage.applicationInfo.privateFlags
16437                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16438            final int systemPolicyFlags = policyFlags
16439                    | PackageParser.PARSE_IS_SYSTEM
16440                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16441
16442            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16443                    user, allUsers, installerPackageName, res, installReason);
16444        } else {
16445            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16446                    user, allUsers, installerPackageName, res, installReason);
16447        }
16448    }
16449
16450    public List<String> getPreviousCodePaths(String packageName) {
16451        final PackageSetting ps = mSettings.mPackages.get(packageName);
16452        final List<String> result = new ArrayList<String>();
16453        if (ps != null && ps.oldCodePaths != null) {
16454            result.addAll(ps.oldCodePaths);
16455        }
16456        return result;
16457    }
16458
16459    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16460            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16461            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16462            int installReason) {
16463        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16464                + deletedPackage);
16465
16466        String pkgName = deletedPackage.packageName;
16467        boolean deletedPkg = true;
16468        boolean addedPkg = false;
16469        boolean updatedSettings = false;
16470        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16471        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16472                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16473
16474        final long origUpdateTime = (pkg.mExtras != null)
16475                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16476
16477        // First delete the existing package while retaining the data directory
16478        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16479                res.removedInfo, true, pkg)) {
16480            // If the existing package wasn't successfully deleted
16481            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16482            deletedPkg = false;
16483        } else {
16484            // Successfully deleted the old package; proceed with replace.
16485
16486            // If deleted package lived in a container, give users a chance to
16487            // relinquish resources before killing.
16488            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16489                if (DEBUG_INSTALL) {
16490                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16491                }
16492                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16493                final ArrayList<String> pkgList = new ArrayList<String>(1);
16494                pkgList.add(deletedPackage.applicationInfo.packageName);
16495                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16496            }
16497
16498            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16499                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16500            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16501
16502            try {
16503                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16504                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16505                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16506                        installReason);
16507
16508                // Update the in-memory copy of the previous code paths.
16509                PackageSetting ps = mSettings.mPackages.get(pkgName);
16510                if (!killApp) {
16511                    if (ps.oldCodePaths == null) {
16512                        ps.oldCodePaths = new ArraySet<>();
16513                    }
16514                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16515                    if (deletedPackage.splitCodePaths != null) {
16516                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16517                    }
16518                } else {
16519                    ps.oldCodePaths = null;
16520                }
16521                if (ps.childPackageNames != null) {
16522                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16523                        final String childPkgName = ps.childPackageNames.get(i);
16524                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16525                        childPs.oldCodePaths = ps.oldCodePaths;
16526                    }
16527                }
16528                // set instant app status, but, only if it's explicitly specified
16529                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16530                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16531                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16532                prepareAppDataAfterInstallLIF(newPackage);
16533                addedPkg = true;
16534                mDexManager.notifyPackageUpdated(newPackage.packageName,
16535                        newPackage.baseCodePath, newPackage.splitCodePaths);
16536            } catch (PackageManagerException e) {
16537                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16538            }
16539        }
16540
16541        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16542            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16543
16544            // Revert all internal state mutations and added folders for the failed install
16545            if (addedPkg) {
16546                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16547                        res.removedInfo, true, null);
16548            }
16549
16550            // Restore the old package
16551            if (deletedPkg) {
16552                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16553                File restoreFile = new File(deletedPackage.codePath);
16554                // Parse old package
16555                boolean oldExternal = isExternal(deletedPackage);
16556                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16557                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16558                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16559                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16560                try {
16561                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16562                            null);
16563                } catch (PackageManagerException e) {
16564                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16565                            + e.getMessage());
16566                    return;
16567                }
16568
16569                synchronized (mPackages) {
16570                    // Ensure the installer package name up to date
16571                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16572
16573                    // Update permissions for restored package
16574                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16575
16576                    mSettings.writeLPr();
16577                }
16578
16579                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16580            }
16581        } else {
16582            synchronized (mPackages) {
16583                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16584                if (ps != null) {
16585                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16586                    if (res.removedInfo.removedChildPackages != null) {
16587                        final int childCount = res.removedInfo.removedChildPackages.size();
16588                        // Iterate in reverse as we may modify the collection
16589                        for (int i = childCount - 1; i >= 0; i--) {
16590                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16591                            if (res.addedChildPackages.containsKey(childPackageName)) {
16592                                res.removedInfo.removedChildPackages.removeAt(i);
16593                            } else {
16594                                PackageRemovedInfo childInfo = res.removedInfo
16595                                        .removedChildPackages.valueAt(i);
16596                                childInfo.removedForAllUsers = mPackages.get(
16597                                        childInfo.removedPackage) == null;
16598                            }
16599                        }
16600                    }
16601                }
16602            }
16603        }
16604    }
16605
16606    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16607            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16608            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16609            int installReason) {
16610        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16611                + ", old=" + deletedPackage);
16612
16613        final boolean disabledSystem;
16614
16615        // Remove existing system package
16616        removePackageLI(deletedPackage, true);
16617
16618        synchronized (mPackages) {
16619            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16620        }
16621        if (!disabledSystem) {
16622            // We didn't need to disable the .apk as a current system package,
16623            // which means we are replacing another update that is already
16624            // installed.  We need to make sure to delete the older one's .apk.
16625            res.removedInfo.args = createInstallArgsForExisting(0,
16626                    deletedPackage.applicationInfo.getCodePath(),
16627                    deletedPackage.applicationInfo.getResourcePath(),
16628                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16629        } else {
16630            res.removedInfo.args = null;
16631        }
16632
16633        // Successfully disabled the old package. Now proceed with re-installation
16634        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16635                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16636        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16637
16638        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16639        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16640                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16641
16642        PackageParser.Package newPackage = null;
16643        try {
16644            // Add the package to the internal data structures
16645            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16646
16647            // Set the update and install times
16648            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16649            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16650                    System.currentTimeMillis());
16651
16652            // Update the package dynamic state if succeeded
16653            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16654                // Now that the install succeeded make sure we remove data
16655                // directories for any child package the update removed.
16656                final int deletedChildCount = (deletedPackage.childPackages != null)
16657                        ? deletedPackage.childPackages.size() : 0;
16658                final int newChildCount = (newPackage.childPackages != null)
16659                        ? newPackage.childPackages.size() : 0;
16660                for (int i = 0; i < deletedChildCount; i++) {
16661                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16662                    boolean childPackageDeleted = true;
16663                    for (int j = 0; j < newChildCount; j++) {
16664                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16665                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16666                            childPackageDeleted = false;
16667                            break;
16668                        }
16669                    }
16670                    if (childPackageDeleted) {
16671                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16672                                deletedChildPkg.packageName);
16673                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16674                            PackageRemovedInfo removedChildRes = res.removedInfo
16675                                    .removedChildPackages.get(deletedChildPkg.packageName);
16676                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16677                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16678                        }
16679                    }
16680                }
16681
16682                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16683                        installReason);
16684                prepareAppDataAfterInstallLIF(newPackage);
16685
16686                mDexManager.notifyPackageUpdated(newPackage.packageName,
16687                            newPackage.baseCodePath, newPackage.splitCodePaths);
16688            }
16689        } catch (PackageManagerException e) {
16690            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16691            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16692        }
16693
16694        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16695            // Re installation failed. Restore old information
16696            // Remove new pkg information
16697            if (newPackage != null) {
16698                removeInstalledPackageLI(newPackage, true);
16699            }
16700            // Add back the old system package
16701            try {
16702                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16703            } catch (PackageManagerException e) {
16704                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16705            }
16706
16707            synchronized (mPackages) {
16708                if (disabledSystem) {
16709                    enableSystemPackageLPw(deletedPackage);
16710                }
16711
16712                // Ensure the installer package name up to date
16713                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16714
16715                // Update permissions for restored package
16716                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16717
16718                mSettings.writeLPr();
16719            }
16720
16721            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16722                    + " after failed upgrade");
16723        }
16724    }
16725
16726    /**
16727     * Checks whether the parent or any of the child packages have a change shared
16728     * user. For a package to be a valid update the shred users of the parent and
16729     * the children should match. We may later support changing child shared users.
16730     * @param oldPkg The updated package.
16731     * @param newPkg The update package.
16732     * @return The shared user that change between the versions.
16733     */
16734    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16735            PackageParser.Package newPkg) {
16736        // Check parent shared user
16737        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16738            return newPkg.packageName;
16739        }
16740        // Check child shared users
16741        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16742        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16743        for (int i = 0; i < newChildCount; i++) {
16744            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16745            // If this child was present, did it have the same shared user?
16746            for (int j = 0; j < oldChildCount; j++) {
16747                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16748                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16749                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16750                    return newChildPkg.packageName;
16751                }
16752            }
16753        }
16754        return null;
16755    }
16756
16757    private void removeNativeBinariesLI(PackageSetting ps) {
16758        // Remove the lib path for the parent package
16759        if (ps != null) {
16760            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16761            // Remove the lib path for the child packages
16762            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16763            for (int i = 0; i < childCount; i++) {
16764                PackageSetting childPs = null;
16765                synchronized (mPackages) {
16766                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16767                }
16768                if (childPs != null) {
16769                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16770                            .legacyNativeLibraryPathString);
16771                }
16772            }
16773        }
16774    }
16775
16776    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16777        // Enable the parent package
16778        mSettings.enableSystemPackageLPw(pkg.packageName);
16779        // Enable the child packages
16780        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16781        for (int i = 0; i < childCount; i++) {
16782            PackageParser.Package childPkg = pkg.childPackages.get(i);
16783            mSettings.enableSystemPackageLPw(childPkg.packageName);
16784        }
16785    }
16786
16787    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16788            PackageParser.Package newPkg) {
16789        // Disable the parent package (parent always replaced)
16790        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16791        // Disable the child packages
16792        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16793        for (int i = 0; i < childCount; i++) {
16794            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16795            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16796            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16797        }
16798        return disabled;
16799    }
16800
16801    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16802            String installerPackageName) {
16803        // Enable the parent package
16804        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16805        // Enable the child packages
16806        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16807        for (int i = 0; i < childCount; i++) {
16808            PackageParser.Package childPkg = pkg.childPackages.get(i);
16809            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16810        }
16811    }
16812
16813    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16814        // Collect all used permissions in the UID
16815        ArraySet<String> usedPermissions = new ArraySet<>();
16816        final int packageCount = su.packages.size();
16817        for (int i = 0; i < packageCount; i++) {
16818            PackageSetting ps = su.packages.valueAt(i);
16819            if (ps.pkg == null) {
16820                continue;
16821            }
16822            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16823            for (int j = 0; j < requestedPermCount; j++) {
16824                String permission = ps.pkg.requestedPermissions.get(j);
16825                BasePermission bp = mSettings.mPermissions.get(permission);
16826                if (bp != null) {
16827                    usedPermissions.add(permission);
16828                }
16829            }
16830        }
16831
16832        PermissionsState permissionsState = su.getPermissionsState();
16833        // Prune install permissions
16834        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16835        final int installPermCount = installPermStates.size();
16836        for (int i = installPermCount - 1; i >= 0;  i--) {
16837            PermissionState permissionState = installPermStates.get(i);
16838            if (!usedPermissions.contains(permissionState.getName())) {
16839                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16840                if (bp != null) {
16841                    permissionsState.revokeInstallPermission(bp);
16842                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16843                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16844                }
16845            }
16846        }
16847
16848        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16849
16850        // Prune runtime permissions
16851        for (int userId : allUserIds) {
16852            List<PermissionState> runtimePermStates = permissionsState
16853                    .getRuntimePermissionStates(userId);
16854            final int runtimePermCount = runtimePermStates.size();
16855            for (int i = runtimePermCount - 1; i >= 0; i--) {
16856                PermissionState permissionState = runtimePermStates.get(i);
16857                if (!usedPermissions.contains(permissionState.getName())) {
16858                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16859                    if (bp != null) {
16860                        permissionsState.revokeRuntimePermission(bp, userId);
16861                        permissionsState.updatePermissionFlags(bp, userId,
16862                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16863                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16864                                runtimePermissionChangedUserIds, userId);
16865                    }
16866                }
16867            }
16868        }
16869
16870        return runtimePermissionChangedUserIds;
16871    }
16872
16873    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16874            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16875        // Update the parent package setting
16876        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16877                res, user, installReason);
16878        // Update the child packages setting
16879        final int childCount = (newPackage.childPackages != null)
16880                ? newPackage.childPackages.size() : 0;
16881        for (int i = 0; i < childCount; i++) {
16882            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16883            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16884            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16885                    childRes.origUsers, childRes, user, installReason);
16886        }
16887    }
16888
16889    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16890            String installerPackageName, int[] allUsers, int[] installedForUsers,
16891            PackageInstalledInfo res, UserHandle user, int installReason) {
16892        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16893
16894        String pkgName = newPackage.packageName;
16895        synchronized (mPackages) {
16896            //write settings. the installStatus will be incomplete at this stage.
16897            //note that the new package setting would have already been
16898            //added to mPackages. It hasn't been persisted yet.
16899            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16900            // TODO: Remove this write? It's also written at the end of this method
16901            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16902            mSettings.writeLPr();
16903            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16904        }
16905
16906        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16907        synchronized (mPackages) {
16908            updatePermissionsLPw(newPackage.packageName, newPackage,
16909                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16910                            ? UPDATE_PERMISSIONS_ALL : 0));
16911            // For system-bundled packages, we assume that installing an upgraded version
16912            // of the package implies that the user actually wants to run that new code,
16913            // so we enable the package.
16914            PackageSetting ps = mSettings.mPackages.get(pkgName);
16915            final int userId = user.getIdentifier();
16916            if (ps != null) {
16917                if (isSystemApp(newPackage)) {
16918                    if (DEBUG_INSTALL) {
16919                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16920                    }
16921                    // Enable system package for requested users
16922                    if (res.origUsers != null) {
16923                        for (int origUserId : res.origUsers) {
16924                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16925                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16926                                        origUserId, installerPackageName);
16927                            }
16928                        }
16929                    }
16930                    // Also convey the prior install/uninstall state
16931                    if (allUsers != null && installedForUsers != null) {
16932                        for (int currentUserId : allUsers) {
16933                            final boolean installed = ArrayUtils.contains(
16934                                    installedForUsers, currentUserId);
16935                            if (DEBUG_INSTALL) {
16936                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16937                            }
16938                            ps.setInstalled(installed, currentUserId);
16939                        }
16940                        // these install state changes will be persisted in the
16941                        // upcoming call to mSettings.writeLPr().
16942                    }
16943                }
16944                // It's implied that when a user requests installation, they want the app to be
16945                // installed and enabled.
16946                if (userId != UserHandle.USER_ALL) {
16947                    ps.setInstalled(true, userId);
16948                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16949                }
16950
16951                // When replacing an existing package, preserve the original install reason for all
16952                // users that had the package installed before.
16953                final Set<Integer> previousUserIds = new ArraySet<>();
16954                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16955                    final int installReasonCount = res.removedInfo.installReasons.size();
16956                    for (int i = 0; i < installReasonCount; i++) {
16957                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16958                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16959                        ps.setInstallReason(previousInstallReason, previousUserId);
16960                        previousUserIds.add(previousUserId);
16961                    }
16962                }
16963
16964                // Set install reason for users that are having the package newly installed.
16965                if (userId == UserHandle.USER_ALL) {
16966                    for (int currentUserId : sUserManager.getUserIds()) {
16967                        if (!previousUserIds.contains(currentUserId)) {
16968                            ps.setInstallReason(installReason, currentUserId);
16969                        }
16970                    }
16971                } else if (!previousUserIds.contains(userId)) {
16972                    ps.setInstallReason(installReason, userId);
16973                }
16974                mSettings.writeKernelMappingLPr(ps);
16975            }
16976            res.name = pkgName;
16977            res.uid = newPackage.applicationInfo.uid;
16978            res.pkg = newPackage;
16979            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16980            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16981            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16982            //to update install status
16983            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16984            mSettings.writeLPr();
16985            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16986        }
16987
16988        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16989    }
16990
16991    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16992        try {
16993            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16994            installPackageLI(args, res);
16995        } finally {
16996            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16997        }
16998    }
16999
17000    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17001        final int installFlags = args.installFlags;
17002        final String installerPackageName = args.installerPackageName;
17003        final String volumeUuid = args.volumeUuid;
17004        final File tmpPackageFile = new File(args.getCodePath());
17005        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17006        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17007                || (args.volumeUuid != null));
17008        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17009        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17010        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17011        boolean replace = false;
17012        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17013        if (args.move != null) {
17014            // moving a complete application; perform an initial scan on the new install location
17015            scanFlags |= SCAN_INITIAL;
17016        }
17017        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17018            scanFlags |= SCAN_DONT_KILL_APP;
17019        }
17020        if (instantApp) {
17021            scanFlags |= SCAN_AS_INSTANT_APP;
17022        }
17023        if (fullApp) {
17024            scanFlags |= SCAN_AS_FULL_APP;
17025        }
17026
17027        // Result object to be returned
17028        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17029
17030        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17031
17032        // Sanity check
17033        if (instantApp && (forwardLocked || onExternal)) {
17034            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17035                    + " external=" + onExternal);
17036            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17037            return;
17038        }
17039
17040        // Retrieve PackageSettings and parse package
17041        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17042                | PackageParser.PARSE_ENFORCE_CODE
17043                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17044                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17045                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17046                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17047        PackageParser pp = new PackageParser();
17048        pp.setSeparateProcesses(mSeparateProcesses);
17049        pp.setDisplayMetrics(mMetrics);
17050        pp.setCallback(mPackageParserCallback);
17051
17052        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17053        final PackageParser.Package pkg;
17054        try {
17055            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17056        } catch (PackageParserException e) {
17057            res.setError("Failed parse during installPackageLI", e);
17058            return;
17059        } finally {
17060            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17061        }
17062
17063        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17064        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17065            Slog.w(TAG, "Instant app package " + pkg.packageName
17066                    + " does not target O, this will be a fatal error.");
17067            // STOPSHIP: Make this a fatal error
17068            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17069        }
17070        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17071            Slog.w(TAG, "Instant app package " + pkg.packageName
17072                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17073            // STOPSHIP: Make this a fatal error
17074            pkg.applicationInfo.targetSandboxVersion = 2;
17075        }
17076
17077        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17078            // Static shared libraries have synthetic package names
17079            renameStaticSharedLibraryPackage(pkg);
17080
17081            // No static shared libs on external storage
17082            if (onExternal) {
17083                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17084                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17085                        "Packages declaring static-shared libs cannot be updated");
17086                return;
17087            }
17088        }
17089
17090        // If we are installing a clustered package add results for the children
17091        if (pkg.childPackages != null) {
17092            synchronized (mPackages) {
17093                final int childCount = pkg.childPackages.size();
17094                for (int i = 0; i < childCount; i++) {
17095                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17096                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17097                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17098                    childRes.pkg = childPkg;
17099                    childRes.name = childPkg.packageName;
17100                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17101                    if (childPs != null) {
17102                        childRes.origUsers = childPs.queryInstalledUsers(
17103                                sUserManager.getUserIds(), true);
17104                    }
17105                    if ((mPackages.containsKey(childPkg.packageName))) {
17106                        childRes.removedInfo = new PackageRemovedInfo(this);
17107                        childRes.removedInfo.removedPackage = childPkg.packageName;
17108                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17109                    }
17110                    if (res.addedChildPackages == null) {
17111                        res.addedChildPackages = new ArrayMap<>();
17112                    }
17113                    res.addedChildPackages.put(childPkg.packageName, childRes);
17114                }
17115            }
17116        }
17117
17118        // If package doesn't declare API override, mark that we have an install
17119        // time CPU ABI override.
17120        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17121            pkg.cpuAbiOverride = args.abiOverride;
17122        }
17123
17124        String pkgName = res.name = pkg.packageName;
17125        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17126            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17127                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17128                return;
17129            }
17130        }
17131
17132        try {
17133            // either use what we've been given or parse directly from the APK
17134            if (args.certificates != null) {
17135                try {
17136                    PackageParser.populateCertificates(pkg, args.certificates);
17137                } catch (PackageParserException e) {
17138                    // there was something wrong with the certificates we were given;
17139                    // try to pull them from the APK
17140                    PackageParser.collectCertificates(pkg, parseFlags);
17141                }
17142            } else {
17143                PackageParser.collectCertificates(pkg, parseFlags);
17144            }
17145        } catch (PackageParserException e) {
17146            res.setError("Failed collect during installPackageLI", e);
17147            return;
17148        }
17149
17150        // Get rid of all references to package scan path via parser.
17151        pp = null;
17152        String oldCodePath = null;
17153        boolean systemApp = false;
17154        synchronized (mPackages) {
17155            // Check if installing already existing package
17156            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17157                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17158                if (pkg.mOriginalPackages != null
17159                        && pkg.mOriginalPackages.contains(oldName)
17160                        && mPackages.containsKey(oldName)) {
17161                    // This package is derived from an original package,
17162                    // and this device has been updating from that original
17163                    // name.  We must continue using the original name, so
17164                    // rename the new package here.
17165                    pkg.setPackageName(oldName);
17166                    pkgName = pkg.packageName;
17167                    replace = true;
17168                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17169                            + oldName + " pkgName=" + pkgName);
17170                } else if (mPackages.containsKey(pkgName)) {
17171                    // This package, under its official name, already exists
17172                    // on the device; we should replace it.
17173                    replace = true;
17174                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17175                }
17176
17177                // Child packages are installed through the parent package
17178                if (pkg.parentPackage != null) {
17179                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17180                            "Package " + pkg.packageName + " is child of package "
17181                                    + pkg.parentPackage.parentPackage + ". Child packages "
17182                                    + "can be updated only through the parent package.");
17183                    return;
17184                }
17185
17186                if (replace) {
17187                    // Prevent apps opting out from runtime permissions
17188                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17189                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17190                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17191                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17192                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17193                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17194                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17195                                        + " doesn't support runtime permissions but the old"
17196                                        + " target SDK " + oldTargetSdk + " does.");
17197                        return;
17198                    }
17199                    // Prevent apps from downgrading their targetSandbox.
17200                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17201                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17202                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17203                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17204                                "Package " + pkg.packageName + " new target sandbox "
17205                                + newTargetSandbox + " is incompatible with the previous value of"
17206                                + oldTargetSandbox + ".");
17207                        return;
17208                    }
17209
17210                    // Prevent installing of child packages
17211                    if (oldPackage.parentPackage != null) {
17212                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17213                                "Package " + pkg.packageName + " is child of package "
17214                                        + oldPackage.parentPackage + ". Child packages "
17215                                        + "can be updated only through the parent package.");
17216                        return;
17217                    }
17218                }
17219            }
17220
17221            PackageSetting ps = mSettings.mPackages.get(pkgName);
17222            if (ps != null) {
17223                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17224
17225                // Static shared libs have same package with different versions where
17226                // we internally use a synthetic package name to allow multiple versions
17227                // of the same package, therefore we need to compare signatures against
17228                // the package setting for the latest library version.
17229                PackageSetting signatureCheckPs = ps;
17230                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17231                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17232                    if (libraryEntry != null) {
17233                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17234                    }
17235                }
17236
17237                // Quick sanity check that we're signed correctly if updating;
17238                // we'll check this again later when scanning, but we want to
17239                // bail early here before tripping over redefined permissions.
17240                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17241                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17242                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17243                                + pkg.packageName + " upgrade keys do not match the "
17244                                + "previously installed version");
17245                        return;
17246                    }
17247                } else {
17248                    try {
17249                        verifySignaturesLP(signatureCheckPs, pkg);
17250                    } catch (PackageManagerException e) {
17251                        res.setError(e.error, e.getMessage());
17252                        return;
17253                    }
17254                }
17255
17256                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17257                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17258                    systemApp = (ps.pkg.applicationInfo.flags &
17259                            ApplicationInfo.FLAG_SYSTEM) != 0;
17260                }
17261                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17262            }
17263
17264            int N = pkg.permissions.size();
17265            for (int i = N-1; i >= 0; i--) {
17266                PackageParser.Permission perm = pkg.permissions.get(i);
17267                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17268
17269                // Don't allow anyone but the system to define ephemeral permissions.
17270                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17271                        && !systemApp) {
17272                    Slog.w(TAG, "Non-System package " + pkg.packageName
17273                            + " attempting to delcare ephemeral permission "
17274                            + perm.info.name + "; Removing ephemeral.");
17275                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17276                }
17277                // Check whether the newly-scanned package wants to define an already-defined perm
17278                if (bp != null) {
17279                    // If the defining package is signed with our cert, it's okay.  This
17280                    // also includes the "updating the same package" case, of course.
17281                    // "updating same package" could also involve key-rotation.
17282                    final boolean sigsOk;
17283                    if (bp.sourcePackage.equals(pkg.packageName)
17284                            && (bp.packageSetting instanceof PackageSetting)
17285                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17286                                    scanFlags))) {
17287                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17288                    } else {
17289                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17290                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17291                    }
17292                    if (!sigsOk) {
17293                        // If the owning package is the system itself, we log but allow
17294                        // install to proceed; we fail the install on all other permission
17295                        // redefinitions.
17296                        if (!bp.sourcePackage.equals("android")) {
17297                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17298                                    + pkg.packageName + " attempting to redeclare permission "
17299                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17300                            res.origPermission = perm.info.name;
17301                            res.origPackage = bp.sourcePackage;
17302                            return;
17303                        } else {
17304                            Slog.w(TAG, "Package " + pkg.packageName
17305                                    + " attempting to redeclare system permission "
17306                                    + perm.info.name + "; ignoring new declaration");
17307                            pkg.permissions.remove(i);
17308                        }
17309                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17310                        // Prevent apps to change protection level to dangerous from any other
17311                        // type as this would allow a privilege escalation where an app adds a
17312                        // normal/signature permission in other app's group and later redefines
17313                        // it as dangerous leading to the group auto-grant.
17314                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17315                                == PermissionInfo.PROTECTION_DANGEROUS) {
17316                            if (bp != null && !bp.isRuntime()) {
17317                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17318                                        + "non-runtime permission " + perm.info.name
17319                                        + " to runtime; keeping old protection level");
17320                                perm.info.protectionLevel = bp.protectionLevel;
17321                            }
17322                        }
17323                    }
17324                }
17325            }
17326        }
17327
17328        if (systemApp) {
17329            if (onExternal) {
17330                // Abort update; system app can't be replaced with app on sdcard
17331                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17332                        "Cannot install updates to system apps on sdcard");
17333                return;
17334            } else if (instantApp) {
17335                // Abort update; system app can't be replaced with an instant app
17336                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17337                        "Cannot update a system app with an instant app");
17338                return;
17339            }
17340        }
17341
17342        if (args.move != null) {
17343            // We did an in-place move, so dex is ready to roll
17344            scanFlags |= SCAN_NO_DEX;
17345            scanFlags |= SCAN_MOVE;
17346
17347            synchronized (mPackages) {
17348                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17349                if (ps == null) {
17350                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17351                            "Missing settings for moved package " + pkgName);
17352                }
17353
17354                // We moved the entire application as-is, so bring over the
17355                // previously derived ABI information.
17356                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17357                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17358            }
17359
17360        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17361            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17362            scanFlags |= SCAN_NO_DEX;
17363
17364            try {
17365                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17366                    args.abiOverride : pkg.cpuAbiOverride);
17367                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17368                        true /*extractLibs*/, mAppLib32InstallDir);
17369            } catch (PackageManagerException pme) {
17370                Slog.e(TAG, "Error deriving application ABI", pme);
17371                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17372                return;
17373            }
17374
17375            // Shared libraries for the package need to be updated.
17376            synchronized (mPackages) {
17377                try {
17378                    updateSharedLibrariesLPr(pkg, null);
17379                } catch (PackageManagerException e) {
17380                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17381                }
17382            }
17383
17384            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17385            // Do not run PackageDexOptimizer through the local performDexOpt
17386            // method because `pkg` may not be in `mPackages` yet.
17387            //
17388            // Also, don't fail application installs if the dexopt step fails.
17389            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17390                    null /* instructionSets */, false /* checkProfiles */,
17391                    getCompilerFilterForReason(REASON_INSTALL),
17392                    getOrCreateCompilerPackageStats(pkg),
17393                    mDexManager.isUsedByOtherApps(pkg.packageName));
17394            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17395
17396            // Notify BackgroundDexOptService that the package has been changed.
17397            // If this is an update of a package which used to fail to compile,
17398            // BDOS will remove it from its blacklist.
17399            // TODO: Layering violation
17400            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17401        }
17402
17403        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17404            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17405            return;
17406        }
17407
17408        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17409
17410        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17411                "installPackageLI")) {
17412            if (replace) {
17413                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17414                    // Static libs have a synthetic package name containing the version
17415                    // and cannot be updated as an update would get a new package name,
17416                    // unless this is the exact same version code which is useful for
17417                    // development.
17418                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17419                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17420                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17421                                + "static-shared libs cannot be updated");
17422                        return;
17423                    }
17424                }
17425                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17426                        installerPackageName, res, args.installReason);
17427            } else {
17428                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17429                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17430            }
17431        }
17432
17433        synchronized (mPackages) {
17434            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17435            if (ps != null) {
17436                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17437                ps.setUpdateAvailable(false /*updateAvailable*/);
17438            }
17439
17440            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17441            for (int i = 0; i < childCount; i++) {
17442                PackageParser.Package childPkg = pkg.childPackages.get(i);
17443                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17444                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17445                if (childPs != null) {
17446                    childRes.newUsers = childPs.queryInstalledUsers(
17447                            sUserManager.getUserIds(), true);
17448                }
17449            }
17450
17451            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17452                updateSequenceNumberLP(pkgName, res.newUsers);
17453                updateInstantAppInstallerLocked(pkgName);
17454            }
17455        }
17456    }
17457
17458    private void startIntentFilterVerifications(int userId, boolean replacing,
17459            PackageParser.Package pkg) {
17460        if (mIntentFilterVerifierComponent == null) {
17461            Slog.w(TAG, "No IntentFilter verification will not be done as "
17462                    + "there is no IntentFilterVerifier available!");
17463            return;
17464        }
17465
17466        final int verifierUid = getPackageUid(
17467                mIntentFilterVerifierComponent.getPackageName(),
17468                MATCH_DEBUG_TRIAGED_MISSING,
17469                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17470
17471        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17472        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17473        mHandler.sendMessage(msg);
17474
17475        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17476        for (int i = 0; i < childCount; i++) {
17477            PackageParser.Package childPkg = pkg.childPackages.get(i);
17478            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17479            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17480            mHandler.sendMessage(msg);
17481        }
17482    }
17483
17484    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17485            PackageParser.Package pkg) {
17486        int size = pkg.activities.size();
17487        if (size == 0) {
17488            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17489                    "No activity, so no need to verify any IntentFilter!");
17490            return;
17491        }
17492
17493        final boolean hasDomainURLs = hasDomainURLs(pkg);
17494        if (!hasDomainURLs) {
17495            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17496                    "No domain URLs, so no need to verify any IntentFilter!");
17497            return;
17498        }
17499
17500        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17501                + " if any IntentFilter from the " + size
17502                + " Activities needs verification ...");
17503
17504        int count = 0;
17505        final String packageName = pkg.packageName;
17506
17507        synchronized (mPackages) {
17508            // If this is a new install and we see that we've already run verification for this
17509            // package, we have nothing to do: it means the state was restored from backup.
17510            if (!replacing) {
17511                IntentFilterVerificationInfo ivi =
17512                        mSettings.getIntentFilterVerificationLPr(packageName);
17513                if (ivi != null) {
17514                    if (DEBUG_DOMAIN_VERIFICATION) {
17515                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17516                                + ivi.getStatusString());
17517                    }
17518                    return;
17519                }
17520            }
17521
17522            // If any filters need to be verified, then all need to be.
17523            boolean needToVerify = false;
17524            for (PackageParser.Activity a : pkg.activities) {
17525                for (ActivityIntentInfo filter : a.intents) {
17526                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17527                        if (DEBUG_DOMAIN_VERIFICATION) {
17528                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17529                        }
17530                        needToVerify = true;
17531                        break;
17532                    }
17533                }
17534            }
17535
17536            if (needToVerify) {
17537                final int verificationId = mIntentFilterVerificationToken++;
17538                for (PackageParser.Activity a : pkg.activities) {
17539                    for (ActivityIntentInfo filter : a.intents) {
17540                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17541                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17542                                    "Verification needed for IntentFilter:" + filter.toString());
17543                            mIntentFilterVerifier.addOneIntentFilterVerification(
17544                                    verifierUid, userId, verificationId, filter, packageName);
17545                            count++;
17546                        }
17547                    }
17548                }
17549            }
17550        }
17551
17552        if (count > 0) {
17553            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17554                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17555                    +  " for userId:" + userId);
17556            mIntentFilterVerifier.startVerifications(userId);
17557        } else {
17558            if (DEBUG_DOMAIN_VERIFICATION) {
17559                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17560            }
17561        }
17562    }
17563
17564    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17565        final ComponentName cn  = filter.activity.getComponentName();
17566        final String packageName = cn.getPackageName();
17567
17568        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17569                packageName);
17570        if (ivi == null) {
17571            return true;
17572        }
17573        int status = ivi.getStatus();
17574        switch (status) {
17575            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17576            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17577                return true;
17578
17579            default:
17580                // Nothing to do
17581                return false;
17582        }
17583    }
17584
17585    private static boolean isMultiArch(ApplicationInfo info) {
17586        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17587    }
17588
17589    private static boolean isExternal(PackageParser.Package pkg) {
17590        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17591    }
17592
17593    private static boolean isExternal(PackageSetting ps) {
17594        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17595    }
17596
17597    private static boolean isSystemApp(PackageParser.Package pkg) {
17598        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17599    }
17600
17601    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17602        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17603    }
17604
17605    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17606        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17607    }
17608
17609    private static boolean isSystemApp(PackageSetting ps) {
17610        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17611    }
17612
17613    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17614        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17615    }
17616
17617    private int packageFlagsToInstallFlags(PackageSetting ps) {
17618        int installFlags = 0;
17619        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17620            // This existing package was an external ASEC install when we have
17621            // the external flag without a UUID
17622            installFlags |= PackageManager.INSTALL_EXTERNAL;
17623        }
17624        if (ps.isForwardLocked()) {
17625            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17626        }
17627        return installFlags;
17628    }
17629
17630    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17631        if (isExternal(pkg)) {
17632            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17633                return StorageManager.UUID_PRIMARY_PHYSICAL;
17634            } else {
17635                return pkg.volumeUuid;
17636            }
17637        } else {
17638            return StorageManager.UUID_PRIVATE_INTERNAL;
17639        }
17640    }
17641
17642    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17643        if (isExternal(pkg)) {
17644            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17645                return mSettings.getExternalVersion();
17646            } else {
17647                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17648            }
17649        } else {
17650            return mSettings.getInternalVersion();
17651        }
17652    }
17653
17654    private void deleteTempPackageFiles() {
17655        final FilenameFilter filter = new FilenameFilter() {
17656            public boolean accept(File dir, String name) {
17657                return name.startsWith("vmdl") && name.endsWith(".tmp");
17658            }
17659        };
17660        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17661            file.delete();
17662        }
17663    }
17664
17665    @Override
17666    public void deletePackageAsUser(String packageName, int versionCode,
17667            IPackageDeleteObserver observer, int userId, int flags) {
17668        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17669                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17670    }
17671
17672    @Override
17673    public void deletePackageVersioned(VersionedPackage versionedPackage,
17674            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17675        mContext.enforceCallingOrSelfPermission(
17676                android.Manifest.permission.DELETE_PACKAGES, null);
17677        Preconditions.checkNotNull(versionedPackage);
17678        Preconditions.checkNotNull(observer);
17679        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17680                PackageManager.VERSION_CODE_HIGHEST,
17681                Integer.MAX_VALUE, "versionCode must be >= -1");
17682
17683        final String packageName = versionedPackage.getPackageName();
17684        // TODO: We will change version code to long, so in the new API it is long
17685        final int versionCode = (int) versionedPackage.getVersionCode();
17686        final String internalPackageName;
17687        synchronized (mPackages) {
17688            // Normalize package name to handle renamed packages and static libs
17689            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17690                    // TODO: We will change version code to long, so in the new API it is long
17691                    (int) versionedPackage.getVersionCode());
17692        }
17693
17694        final int uid = Binder.getCallingUid();
17695        if (!isOrphaned(internalPackageName)
17696                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17697            try {
17698                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17699                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17700                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17701                observer.onUserActionRequired(intent);
17702            } catch (RemoteException re) {
17703            }
17704            return;
17705        }
17706        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17707        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17708        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17709            mContext.enforceCallingOrSelfPermission(
17710                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17711                    "deletePackage for user " + userId);
17712        }
17713
17714        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17715            try {
17716                observer.onPackageDeleted(packageName,
17717                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17718            } catch (RemoteException re) {
17719            }
17720            return;
17721        }
17722
17723        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17724            try {
17725                observer.onPackageDeleted(packageName,
17726                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17727            } catch (RemoteException re) {
17728            }
17729            return;
17730        }
17731
17732        if (DEBUG_REMOVE) {
17733            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17734                    + " deleteAllUsers: " + deleteAllUsers + " version="
17735                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17736                    ? "VERSION_CODE_HIGHEST" : versionCode));
17737        }
17738        // Queue up an async operation since the package deletion may take a little while.
17739        mHandler.post(new Runnable() {
17740            public void run() {
17741                mHandler.removeCallbacks(this);
17742                int returnCode;
17743                if (!deleteAllUsers) {
17744                    returnCode = deletePackageX(internalPackageName, versionCode,
17745                            userId, deleteFlags);
17746                } else {
17747                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17748                            internalPackageName, users);
17749                    // If nobody is blocking uninstall, proceed with delete for all users
17750                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17751                        returnCode = deletePackageX(internalPackageName, versionCode,
17752                                userId, deleteFlags);
17753                    } else {
17754                        // Otherwise uninstall individually for users with blockUninstalls=false
17755                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17756                        for (int userId : users) {
17757                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17758                                returnCode = deletePackageX(internalPackageName, versionCode,
17759                                        userId, userFlags);
17760                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17761                                    Slog.w(TAG, "Package delete failed for user " + userId
17762                                            + ", returnCode " + returnCode);
17763                                }
17764                            }
17765                        }
17766                        // The app has only been marked uninstalled for certain users.
17767                        // We still need to report that delete was blocked
17768                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17769                    }
17770                }
17771                try {
17772                    observer.onPackageDeleted(packageName, returnCode, null);
17773                } catch (RemoteException e) {
17774                    Log.i(TAG, "Observer no longer exists.");
17775                } //end catch
17776            } //end run
17777        });
17778    }
17779
17780    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17781        if (pkg.staticSharedLibName != null) {
17782            return pkg.manifestPackageName;
17783        }
17784        return pkg.packageName;
17785    }
17786
17787    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17788        // Handle renamed packages
17789        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17790        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17791
17792        // Is this a static library?
17793        SparseArray<SharedLibraryEntry> versionedLib =
17794                mStaticLibsByDeclaringPackage.get(packageName);
17795        if (versionedLib == null || versionedLib.size() <= 0) {
17796            return packageName;
17797        }
17798
17799        // Figure out which lib versions the caller can see
17800        SparseIntArray versionsCallerCanSee = null;
17801        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17802        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17803                && callingAppId != Process.ROOT_UID) {
17804            versionsCallerCanSee = new SparseIntArray();
17805            String libName = versionedLib.valueAt(0).info.getName();
17806            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17807            if (uidPackages != null) {
17808                for (String uidPackage : uidPackages) {
17809                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17810                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17811                    if (libIdx >= 0) {
17812                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17813                        versionsCallerCanSee.append(libVersion, libVersion);
17814                    }
17815                }
17816            }
17817        }
17818
17819        // Caller can see nothing - done
17820        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17821            return packageName;
17822        }
17823
17824        // Find the version the caller can see and the app version code
17825        SharedLibraryEntry highestVersion = null;
17826        final int versionCount = versionedLib.size();
17827        for (int i = 0; i < versionCount; i++) {
17828            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17829            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17830                    libEntry.info.getVersion()) < 0) {
17831                continue;
17832            }
17833            // TODO: We will change version code to long, so in the new API it is long
17834            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17835            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17836                if (libVersionCode == versionCode) {
17837                    return libEntry.apk;
17838                }
17839            } else if (highestVersion == null) {
17840                highestVersion = libEntry;
17841            } else if (libVersionCode  > highestVersion.info
17842                    .getDeclaringPackage().getVersionCode()) {
17843                highestVersion = libEntry;
17844            }
17845        }
17846
17847        if (highestVersion != null) {
17848            return highestVersion.apk;
17849        }
17850
17851        return packageName;
17852    }
17853
17854    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17855        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17856              || callingUid == Process.SYSTEM_UID) {
17857            return true;
17858        }
17859        final int callingUserId = UserHandle.getUserId(callingUid);
17860        // If the caller installed the pkgName, then allow it to silently uninstall.
17861        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17862            return true;
17863        }
17864
17865        // Allow package verifier to silently uninstall.
17866        if (mRequiredVerifierPackage != null &&
17867                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17868            return true;
17869        }
17870
17871        // Allow package uninstaller to silently uninstall.
17872        if (mRequiredUninstallerPackage != null &&
17873                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17874            return true;
17875        }
17876
17877        // Allow storage manager to silently uninstall.
17878        if (mStorageManagerPackage != null &&
17879                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17880            return true;
17881        }
17882        return false;
17883    }
17884
17885    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17886        int[] result = EMPTY_INT_ARRAY;
17887        for (int userId : userIds) {
17888            if (getBlockUninstallForUser(packageName, userId)) {
17889                result = ArrayUtils.appendInt(result, userId);
17890            }
17891        }
17892        return result;
17893    }
17894
17895    @Override
17896    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17897        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17898    }
17899
17900    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17901        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17902                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17903        try {
17904            if (dpm != null) {
17905                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17906                        /* callingUserOnly =*/ false);
17907                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17908                        : deviceOwnerComponentName.getPackageName();
17909                // Does the package contains the device owner?
17910                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17911                // this check is probably not needed, since DO should be registered as a device
17912                // admin on some user too. (Original bug for this: b/17657954)
17913                if (packageName.equals(deviceOwnerPackageName)) {
17914                    return true;
17915                }
17916                // Does it contain a device admin for any user?
17917                int[] users;
17918                if (userId == UserHandle.USER_ALL) {
17919                    users = sUserManager.getUserIds();
17920                } else {
17921                    users = new int[]{userId};
17922                }
17923                for (int i = 0; i < users.length; ++i) {
17924                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17925                        return true;
17926                    }
17927                }
17928            }
17929        } catch (RemoteException e) {
17930        }
17931        return false;
17932    }
17933
17934    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17935        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17936    }
17937
17938    /**
17939     *  This method is an internal method that could be get invoked either
17940     *  to delete an installed package or to clean up a failed installation.
17941     *  After deleting an installed package, a broadcast is sent to notify any
17942     *  listeners that the package has been removed. For cleaning up a failed
17943     *  installation, the broadcast is not necessary since the package's
17944     *  installation wouldn't have sent the initial broadcast either
17945     *  The key steps in deleting a package are
17946     *  deleting the package information in internal structures like mPackages,
17947     *  deleting the packages base directories through installd
17948     *  updating mSettings to reflect current status
17949     *  persisting settings for later use
17950     *  sending a broadcast if necessary
17951     */
17952    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17953        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17954        final boolean res;
17955
17956        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17957                ? UserHandle.USER_ALL : userId;
17958
17959        if (isPackageDeviceAdmin(packageName, removeUser)) {
17960            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17961            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17962        }
17963
17964        PackageSetting uninstalledPs = null;
17965        PackageParser.Package pkg = null;
17966
17967        // for the uninstall-updates case and restricted profiles, remember the per-
17968        // user handle installed state
17969        int[] allUsers;
17970        synchronized (mPackages) {
17971            uninstalledPs = mSettings.mPackages.get(packageName);
17972            if (uninstalledPs == null) {
17973                Slog.w(TAG, "Not removing non-existent package " + packageName);
17974                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17975            }
17976
17977            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17978                    && uninstalledPs.versionCode != versionCode) {
17979                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17980                        + uninstalledPs.versionCode + " != " + versionCode);
17981                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17982            }
17983
17984            // Static shared libs can be declared by any package, so let us not
17985            // allow removing a package if it provides a lib others depend on.
17986            pkg = mPackages.get(packageName);
17987            if (pkg != null && pkg.staticSharedLibName != null) {
17988                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17989                        pkg.staticSharedLibVersion);
17990                if (libEntry != null) {
17991                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17992                            libEntry.info, 0, userId);
17993                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17994                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17995                                + " hosting lib " + libEntry.info.getName() + " version "
17996                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17997                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17998                    }
17999                }
18000            }
18001
18002            allUsers = sUserManager.getUserIds();
18003            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18004        }
18005
18006        final int freezeUser;
18007        if (isUpdatedSystemApp(uninstalledPs)
18008                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18009            // We're downgrading a system app, which will apply to all users, so
18010            // freeze them all during the downgrade
18011            freezeUser = UserHandle.USER_ALL;
18012        } else {
18013            freezeUser = removeUser;
18014        }
18015
18016        synchronized (mInstallLock) {
18017            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18018            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18019                    deleteFlags, "deletePackageX")) {
18020                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18021                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18022            }
18023            synchronized (mPackages) {
18024                if (res) {
18025                    if (pkg != null) {
18026                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18027                    }
18028                    updateSequenceNumberLP(packageName, info.removedUsers);
18029                    updateInstantAppInstallerLocked(packageName);
18030                }
18031            }
18032        }
18033
18034        if (res) {
18035            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18036            info.sendPackageRemovedBroadcasts(killApp);
18037            info.sendSystemPackageUpdatedBroadcasts();
18038            info.sendSystemPackageAppearedBroadcasts();
18039        }
18040        // Force a gc here.
18041        Runtime.getRuntime().gc();
18042        // Delete the resources here after sending the broadcast to let
18043        // other processes clean up before deleting resources.
18044        if (info.args != null) {
18045            synchronized (mInstallLock) {
18046                info.args.doPostDeleteLI(true);
18047            }
18048        }
18049
18050        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18051    }
18052
18053    static class PackageRemovedInfo {
18054        final PackageSender packageSender;
18055        String removedPackage;
18056        String installerPackageName;
18057        int uid = -1;
18058        int removedAppId = -1;
18059        int[] origUsers;
18060        int[] removedUsers = null;
18061        int[] broadcastUsers = null;
18062        SparseArray<Integer> installReasons;
18063        boolean isRemovedPackageSystemUpdate = false;
18064        boolean isUpdate;
18065        boolean dataRemoved;
18066        boolean removedForAllUsers;
18067        boolean isStaticSharedLib;
18068        // Clean up resources deleted packages.
18069        InstallArgs args = null;
18070        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18071        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18072
18073        PackageRemovedInfo(PackageSender packageSender) {
18074            this.packageSender = packageSender;
18075        }
18076
18077        void sendPackageRemovedBroadcasts(boolean killApp) {
18078            sendPackageRemovedBroadcastInternal(killApp);
18079            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18080            for (int i = 0; i < childCount; i++) {
18081                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18082                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18083            }
18084        }
18085
18086        void sendSystemPackageUpdatedBroadcasts() {
18087            if (isRemovedPackageSystemUpdate) {
18088                sendSystemPackageUpdatedBroadcastsInternal();
18089                final int childCount = (removedChildPackages != null)
18090                        ? removedChildPackages.size() : 0;
18091                for (int i = 0; i < childCount; i++) {
18092                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18093                    if (childInfo.isRemovedPackageSystemUpdate) {
18094                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18095                    }
18096                }
18097            }
18098        }
18099
18100        void sendSystemPackageAppearedBroadcasts() {
18101            final int packageCount = (appearedChildPackages != null)
18102                    ? appearedChildPackages.size() : 0;
18103            for (int i = 0; i < packageCount; i++) {
18104                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18105                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18106                    true, UserHandle.getAppId(installedInfo.uid),
18107                    installedInfo.newUsers);
18108            }
18109        }
18110
18111        private void sendSystemPackageUpdatedBroadcastsInternal() {
18112            Bundle extras = new Bundle(2);
18113            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18114            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18115            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18116                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18117            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18118                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18119            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18120                null, null, 0, removedPackage, null, null);
18121            if (installerPackageName != null) {
18122                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18123                        removedPackage, extras, 0 /*flags*/,
18124                        installerPackageName, null, null);
18125                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18126                        removedPackage, extras, 0 /*flags*/,
18127                        installerPackageName, null, null);
18128            }
18129        }
18130
18131        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18132            // Don't send static shared library removal broadcasts as these
18133            // libs are visible only the the apps that depend on them an one
18134            // cannot remove the library if it has a dependency.
18135            if (isStaticSharedLib) {
18136                return;
18137            }
18138            Bundle extras = new Bundle(2);
18139            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18140            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18141            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18142            if (isUpdate || isRemovedPackageSystemUpdate) {
18143                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18144            }
18145            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18146            if (removedPackage != null) {
18147                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18148                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18149                if (installerPackageName != null) {
18150                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18151                            removedPackage, extras, 0 /*flags*/,
18152                            installerPackageName, null, broadcastUsers);
18153                }
18154                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18155                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18156                        removedPackage, extras,
18157                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18158                        null, null, broadcastUsers);
18159                }
18160            }
18161            if (removedAppId >= 0) {
18162                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18163                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18164            }
18165        }
18166
18167        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18168            removedUsers = userIds;
18169            if (removedUsers == null) {
18170                broadcastUsers = null;
18171                return;
18172            }
18173
18174            broadcastUsers = EMPTY_INT_ARRAY;
18175            for (int i = userIds.length - 1; i >= 0; --i) {
18176                final int userId = userIds[i];
18177                if (deletedPackageSetting.getInstantApp(userId)) {
18178                    continue;
18179                }
18180                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18181            }
18182        }
18183    }
18184
18185    /*
18186     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18187     * flag is not set, the data directory is removed as well.
18188     * make sure this flag is set for partially installed apps. If not its meaningless to
18189     * delete a partially installed application.
18190     */
18191    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18192            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18193        String packageName = ps.name;
18194        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18195        // Retrieve object to delete permissions for shared user later on
18196        final PackageParser.Package deletedPkg;
18197        final PackageSetting deletedPs;
18198        // reader
18199        synchronized (mPackages) {
18200            deletedPkg = mPackages.get(packageName);
18201            deletedPs = mSettings.mPackages.get(packageName);
18202            if (outInfo != null) {
18203                outInfo.removedPackage = packageName;
18204                outInfo.installerPackageName = ps.installerPackageName;
18205                outInfo.isStaticSharedLib = deletedPkg != null
18206                        && deletedPkg.staticSharedLibName != null;
18207                outInfo.populateUsers(deletedPs == null ? null
18208                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18209            }
18210        }
18211
18212        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18213
18214        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18215            final PackageParser.Package resolvedPkg;
18216            if (deletedPkg != null) {
18217                resolvedPkg = deletedPkg;
18218            } else {
18219                // We don't have a parsed package when it lives on an ejected
18220                // adopted storage device, so fake something together
18221                resolvedPkg = new PackageParser.Package(ps.name);
18222                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18223            }
18224            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18225                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18226            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18227            if (outInfo != null) {
18228                outInfo.dataRemoved = true;
18229            }
18230            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18231        }
18232
18233        int removedAppId = -1;
18234
18235        // writer
18236        synchronized (mPackages) {
18237            boolean installedStateChanged = false;
18238            if (deletedPs != null) {
18239                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18240                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18241                    clearDefaultBrowserIfNeeded(packageName);
18242                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18243                    removedAppId = mSettings.removePackageLPw(packageName);
18244                    if (outInfo != null) {
18245                        outInfo.removedAppId = removedAppId;
18246                    }
18247                    updatePermissionsLPw(deletedPs.name, null, 0);
18248                    if (deletedPs.sharedUser != null) {
18249                        // Remove permissions associated with package. Since runtime
18250                        // permissions are per user we have to kill the removed package
18251                        // or packages running under the shared user of the removed
18252                        // package if revoking the permissions requested only by the removed
18253                        // package is successful and this causes a change in gids.
18254                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18255                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18256                                    userId);
18257                            if (userIdToKill == UserHandle.USER_ALL
18258                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18259                                // If gids changed for this user, kill all affected packages.
18260                                mHandler.post(new Runnable() {
18261                                    @Override
18262                                    public void run() {
18263                                        // This has to happen with no lock held.
18264                                        killApplication(deletedPs.name, deletedPs.appId,
18265                                                KILL_APP_REASON_GIDS_CHANGED);
18266                                    }
18267                                });
18268                                break;
18269                            }
18270                        }
18271                    }
18272                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18273                }
18274                // make sure to preserve per-user disabled state if this removal was just
18275                // a downgrade of a system app to the factory package
18276                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18277                    if (DEBUG_REMOVE) {
18278                        Slog.d(TAG, "Propagating install state across downgrade");
18279                    }
18280                    for (int userId : allUserHandles) {
18281                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18282                        if (DEBUG_REMOVE) {
18283                            Slog.d(TAG, "    user " + userId + " => " + installed);
18284                        }
18285                        if (installed != ps.getInstalled(userId)) {
18286                            installedStateChanged = true;
18287                        }
18288                        ps.setInstalled(installed, userId);
18289                    }
18290                }
18291            }
18292            // can downgrade to reader
18293            if (writeSettings) {
18294                // Save settings now
18295                mSettings.writeLPr();
18296            }
18297            if (installedStateChanged) {
18298                mSettings.writeKernelMappingLPr(ps);
18299            }
18300        }
18301        if (removedAppId != -1) {
18302            // A user ID was deleted here. Go through all users and remove it
18303            // from KeyStore.
18304            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18305        }
18306    }
18307
18308    static boolean locationIsPrivileged(File path) {
18309        try {
18310            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18311                    .getCanonicalPath();
18312            return path.getCanonicalPath().startsWith(privilegedAppDir);
18313        } catch (IOException e) {
18314            Slog.e(TAG, "Unable to access code path " + path);
18315        }
18316        return false;
18317    }
18318
18319    /*
18320     * Tries to delete system package.
18321     */
18322    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18323            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18324            boolean writeSettings) {
18325        if (deletedPs.parentPackageName != null) {
18326            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18327            return false;
18328        }
18329
18330        final boolean applyUserRestrictions
18331                = (allUserHandles != null) && (outInfo.origUsers != null);
18332        final PackageSetting disabledPs;
18333        // Confirm if the system package has been updated
18334        // An updated system app can be deleted. This will also have to restore
18335        // the system pkg from system partition
18336        // reader
18337        synchronized (mPackages) {
18338            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18339        }
18340
18341        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18342                + " disabledPs=" + disabledPs);
18343
18344        if (disabledPs == null) {
18345            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18346            return false;
18347        } else if (DEBUG_REMOVE) {
18348            Slog.d(TAG, "Deleting system pkg from data partition");
18349        }
18350
18351        if (DEBUG_REMOVE) {
18352            if (applyUserRestrictions) {
18353                Slog.d(TAG, "Remembering install states:");
18354                for (int userId : allUserHandles) {
18355                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18356                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18357                }
18358            }
18359        }
18360
18361        // Delete the updated package
18362        outInfo.isRemovedPackageSystemUpdate = true;
18363        if (outInfo.removedChildPackages != null) {
18364            final int childCount = (deletedPs.childPackageNames != null)
18365                    ? deletedPs.childPackageNames.size() : 0;
18366            for (int i = 0; i < childCount; i++) {
18367                String childPackageName = deletedPs.childPackageNames.get(i);
18368                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18369                        .contains(childPackageName)) {
18370                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18371                            childPackageName);
18372                    if (childInfo != null) {
18373                        childInfo.isRemovedPackageSystemUpdate = true;
18374                    }
18375                }
18376            }
18377        }
18378
18379        if (disabledPs.versionCode < deletedPs.versionCode) {
18380            // Delete data for downgrades
18381            flags &= ~PackageManager.DELETE_KEEP_DATA;
18382        } else {
18383            // Preserve data by setting flag
18384            flags |= PackageManager.DELETE_KEEP_DATA;
18385        }
18386
18387        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18388                outInfo, writeSettings, disabledPs.pkg);
18389        if (!ret) {
18390            return false;
18391        }
18392
18393        // writer
18394        synchronized (mPackages) {
18395            // Reinstate the old system package
18396            enableSystemPackageLPw(disabledPs.pkg);
18397            // Remove any native libraries from the upgraded package.
18398            removeNativeBinariesLI(deletedPs);
18399        }
18400
18401        // Install the system package
18402        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18403        int parseFlags = mDefParseFlags
18404                | PackageParser.PARSE_MUST_BE_APK
18405                | PackageParser.PARSE_IS_SYSTEM
18406                | PackageParser.PARSE_IS_SYSTEM_DIR;
18407        if (locationIsPrivileged(disabledPs.codePath)) {
18408            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18409        }
18410
18411        final PackageParser.Package newPkg;
18412        try {
18413            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18414                0 /* currentTime */, null);
18415        } catch (PackageManagerException e) {
18416            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18417                    + e.getMessage());
18418            return false;
18419        }
18420
18421        try {
18422            // update shared libraries for the newly re-installed system package
18423            updateSharedLibrariesLPr(newPkg, null);
18424        } catch (PackageManagerException e) {
18425            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18426        }
18427
18428        prepareAppDataAfterInstallLIF(newPkg);
18429
18430        // writer
18431        synchronized (mPackages) {
18432            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18433
18434            // Propagate the permissions state as we do not want to drop on the floor
18435            // runtime permissions. The update permissions method below will take
18436            // care of removing obsolete permissions and grant install permissions.
18437            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18438            updatePermissionsLPw(newPkg.packageName, newPkg,
18439                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18440
18441            if (applyUserRestrictions) {
18442                boolean installedStateChanged = false;
18443                if (DEBUG_REMOVE) {
18444                    Slog.d(TAG, "Propagating install state across reinstall");
18445                }
18446                for (int userId : allUserHandles) {
18447                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18448                    if (DEBUG_REMOVE) {
18449                        Slog.d(TAG, "    user " + userId + " => " + installed);
18450                    }
18451                    if (installed != ps.getInstalled(userId)) {
18452                        installedStateChanged = true;
18453                    }
18454                    ps.setInstalled(installed, userId);
18455
18456                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18457                }
18458                // Regardless of writeSettings we need to ensure that this restriction
18459                // state propagation is persisted
18460                mSettings.writeAllUsersPackageRestrictionsLPr();
18461                if (installedStateChanged) {
18462                    mSettings.writeKernelMappingLPr(ps);
18463                }
18464            }
18465            // can downgrade to reader here
18466            if (writeSettings) {
18467                mSettings.writeLPr();
18468            }
18469        }
18470        return true;
18471    }
18472
18473    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18474            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18475            PackageRemovedInfo outInfo, boolean writeSettings,
18476            PackageParser.Package replacingPackage) {
18477        synchronized (mPackages) {
18478            if (outInfo != null) {
18479                outInfo.uid = ps.appId;
18480            }
18481
18482            if (outInfo != null && outInfo.removedChildPackages != null) {
18483                final int childCount = (ps.childPackageNames != null)
18484                        ? ps.childPackageNames.size() : 0;
18485                for (int i = 0; i < childCount; i++) {
18486                    String childPackageName = ps.childPackageNames.get(i);
18487                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18488                    if (childPs == null) {
18489                        return false;
18490                    }
18491                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18492                            childPackageName);
18493                    if (childInfo != null) {
18494                        childInfo.uid = childPs.appId;
18495                    }
18496                }
18497            }
18498        }
18499
18500        // Delete package data from internal structures and also remove data if flag is set
18501        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18502
18503        // Delete the child packages data
18504        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18505        for (int i = 0; i < childCount; i++) {
18506            PackageSetting childPs;
18507            synchronized (mPackages) {
18508                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18509            }
18510            if (childPs != null) {
18511                PackageRemovedInfo childOutInfo = (outInfo != null
18512                        && outInfo.removedChildPackages != null)
18513                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18514                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18515                        && (replacingPackage != null
18516                        && !replacingPackage.hasChildPackage(childPs.name))
18517                        ? flags & ~DELETE_KEEP_DATA : flags;
18518                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18519                        deleteFlags, writeSettings);
18520            }
18521        }
18522
18523        // Delete application code and resources only for parent packages
18524        if (ps.parentPackageName == null) {
18525            if (deleteCodeAndResources && (outInfo != null)) {
18526                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18527                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18528                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18529            }
18530        }
18531
18532        return true;
18533    }
18534
18535    @Override
18536    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18537            int userId) {
18538        mContext.enforceCallingOrSelfPermission(
18539                android.Manifest.permission.DELETE_PACKAGES, null);
18540        synchronized (mPackages) {
18541            // Cannot block uninstall of static shared libs as they are
18542            // considered a part of the using app (emulating static linking).
18543            // Also static libs are installed always on internal storage.
18544            PackageParser.Package pkg = mPackages.get(packageName);
18545            if (pkg != null && pkg.staticSharedLibName != null) {
18546                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18547                        + " providing static shared library: " + pkg.staticSharedLibName);
18548                return false;
18549            }
18550            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18551            mSettings.writePackageRestrictionsLPr(userId);
18552        }
18553        return true;
18554    }
18555
18556    @Override
18557    public boolean getBlockUninstallForUser(String packageName, int userId) {
18558        synchronized (mPackages) {
18559            return mSettings.getBlockUninstallLPr(userId, packageName);
18560        }
18561    }
18562
18563    @Override
18564    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18565        int callingUid = Binder.getCallingUid();
18566        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18567            throw new SecurityException(
18568                    "setRequiredForSystemUser can only be run by the system or root");
18569        }
18570        synchronized (mPackages) {
18571            PackageSetting ps = mSettings.mPackages.get(packageName);
18572            if (ps == null) {
18573                Log.w(TAG, "Package doesn't exist: " + packageName);
18574                return false;
18575            }
18576            if (systemUserApp) {
18577                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18578            } else {
18579                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18580            }
18581            mSettings.writeLPr();
18582        }
18583        return true;
18584    }
18585
18586    /*
18587     * This method handles package deletion in general
18588     */
18589    private boolean deletePackageLIF(String packageName, UserHandle user,
18590            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18591            PackageRemovedInfo outInfo, boolean writeSettings,
18592            PackageParser.Package replacingPackage) {
18593        if (packageName == null) {
18594            Slog.w(TAG, "Attempt to delete null packageName.");
18595            return false;
18596        }
18597
18598        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18599
18600        PackageSetting ps;
18601        synchronized (mPackages) {
18602            ps = mSettings.mPackages.get(packageName);
18603            if (ps == null) {
18604                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18605                return false;
18606            }
18607
18608            if (ps.parentPackageName != null && (!isSystemApp(ps)
18609                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18610                if (DEBUG_REMOVE) {
18611                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18612                            + ((user == null) ? UserHandle.USER_ALL : user));
18613                }
18614                final int removedUserId = (user != null) ? user.getIdentifier()
18615                        : UserHandle.USER_ALL;
18616                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18617                    return false;
18618                }
18619                markPackageUninstalledForUserLPw(ps, user);
18620                scheduleWritePackageRestrictionsLocked(user);
18621                return true;
18622            }
18623        }
18624
18625        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18626                && user.getIdentifier() != UserHandle.USER_ALL)) {
18627            // The caller is asking that the package only be deleted for a single
18628            // user.  To do this, we just mark its uninstalled state and delete
18629            // its data. If this is a system app, we only allow this to happen if
18630            // they have set the special DELETE_SYSTEM_APP which requests different
18631            // semantics than normal for uninstalling system apps.
18632            markPackageUninstalledForUserLPw(ps, user);
18633
18634            if (!isSystemApp(ps)) {
18635                // Do not uninstall the APK if an app should be cached
18636                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18637                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18638                    // Other user still have this package installed, so all
18639                    // we need to do is clear this user's data and save that
18640                    // it is uninstalled.
18641                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18642                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18643                        return false;
18644                    }
18645                    scheduleWritePackageRestrictionsLocked(user);
18646                    return true;
18647                } else {
18648                    // We need to set it back to 'installed' so the uninstall
18649                    // broadcasts will be sent correctly.
18650                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18651                    ps.setInstalled(true, user.getIdentifier());
18652                    mSettings.writeKernelMappingLPr(ps);
18653                }
18654            } else {
18655                // This is a system app, so we assume that the
18656                // other users still have this package installed, so all
18657                // we need to do is clear this user's data and save that
18658                // it is uninstalled.
18659                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18660                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18661                    return false;
18662                }
18663                scheduleWritePackageRestrictionsLocked(user);
18664                return true;
18665            }
18666        }
18667
18668        // If we are deleting a composite package for all users, keep track
18669        // of result for each child.
18670        if (ps.childPackageNames != null && outInfo != null) {
18671            synchronized (mPackages) {
18672                final int childCount = ps.childPackageNames.size();
18673                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18674                for (int i = 0; i < childCount; i++) {
18675                    String childPackageName = ps.childPackageNames.get(i);
18676                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18677                    childInfo.removedPackage = childPackageName;
18678                    childInfo.installerPackageName = ps.installerPackageName;
18679                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18680                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18681                    if (childPs != null) {
18682                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18683                    }
18684                }
18685            }
18686        }
18687
18688        boolean ret = false;
18689        if (isSystemApp(ps)) {
18690            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18691            // When an updated system application is deleted we delete the existing resources
18692            // as well and fall back to existing code in system partition
18693            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18694        } else {
18695            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18696            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18697                    outInfo, writeSettings, replacingPackage);
18698        }
18699
18700        // Take a note whether we deleted the package for all users
18701        if (outInfo != null) {
18702            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18703            if (outInfo.removedChildPackages != null) {
18704                synchronized (mPackages) {
18705                    final int childCount = outInfo.removedChildPackages.size();
18706                    for (int i = 0; i < childCount; i++) {
18707                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18708                        if (childInfo != null) {
18709                            childInfo.removedForAllUsers = mPackages.get(
18710                                    childInfo.removedPackage) == null;
18711                        }
18712                    }
18713                }
18714            }
18715            // If we uninstalled an update to a system app there may be some
18716            // child packages that appeared as they are declared in the system
18717            // app but were not declared in the update.
18718            if (isSystemApp(ps)) {
18719                synchronized (mPackages) {
18720                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18721                    final int childCount = (updatedPs.childPackageNames != null)
18722                            ? updatedPs.childPackageNames.size() : 0;
18723                    for (int i = 0; i < childCount; i++) {
18724                        String childPackageName = updatedPs.childPackageNames.get(i);
18725                        if (outInfo.removedChildPackages == null
18726                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18727                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18728                            if (childPs == null) {
18729                                continue;
18730                            }
18731                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18732                            installRes.name = childPackageName;
18733                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18734                            installRes.pkg = mPackages.get(childPackageName);
18735                            installRes.uid = childPs.pkg.applicationInfo.uid;
18736                            if (outInfo.appearedChildPackages == null) {
18737                                outInfo.appearedChildPackages = new ArrayMap<>();
18738                            }
18739                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18740                        }
18741                    }
18742                }
18743            }
18744        }
18745
18746        return ret;
18747    }
18748
18749    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18750        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18751                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18752        for (int nextUserId : userIds) {
18753            if (DEBUG_REMOVE) {
18754                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18755            }
18756            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18757                    false /*installed*/,
18758                    true /*stopped*/,
18759                    true /*notLaunched*/,
18760                    false /*hidden*/,
18761                    false /*suspended*/,
18762                    false /*instantApp*/,
18763                    null /*lastDisableAppCaller*/,
18764                    null /*enabledComponents*/,
18765                    null /*disabledComponents*/,
18766                    ps.readUserState(nextUserId).domainVerificationStatus,
18767                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18768        }
18769        mSettings.writeKernelMappingLPr(ps);
18770    }
18771
18772    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18773            PackageRemovedInfo outInfo) {
18774        final PackageParser.Package pkg;
18775        synchronized (mPackages) {
18776            pkg = mPackages.get(ps.name);
18777        }
18778
18779        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18780                : new int[] {userId};
18781        for (int nextUserId : userIds) {
18782            if (DEBUG_REMOVE) {
18783                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18784                        + nextUserId);
18785            }
18786
18787            destroyAppDataLIF(pkg, userId,
18788                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18789            destroyAppProfilesLIF(pkg, userId);
18790            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18791            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18792            schedulePackageCleaning(ps.name, nextUserId, false);
18793            synchronized (mPackages) {
18794                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18795                    scheduleWritePackageRestrictionsLocked(nextUserId);
18796                }
18797                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18798            }
18799        }
18800
18801        if (outInfo != null) {
18802            outInfo.removedPackage = ps.name;
18803            outInfo.installerPackageName = ps.installerPackageName;
18804            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18805            outInfo.removedAppId = ps.appId;
18806            outInfo.removedUsers = userIds;
18807            outInfo.broadcastUsers = userIds;
18808        }
18809
18810        return true;
18811    }
18812
18813    private final class ClearStorageConnection implements ServiceConnection {
18814        IMediaContainerService mContainerService;
18815
18816        @Override
18817        public void onServiceConnected(ComponentName name, IBinder service) {
18818            synchronized (this) {
18819                mContainerService = IMediaContainerService.Stub
18820                        .asInterface(Binder.allowBlocking(service));
18821                notifyAll();
18822            }
18823        }
18824
18825        @Override
18826        public void onServiceDisconnected(ComponentName name) {
18827        }
18828    }
18829
18830    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18831        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18832
18833        final boolean mounted;
18834        if (Environment.isExternalStorageEmulated()) {
18835            mounted = true;
18836        } else {
18837            final String status = Environment.getExternalStorageState();
18838
18839            mounted = status.equals(Environment.MEDIA_MOUNTED)
18840                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18841        }
18842
18843        if (!mounted) {
18844            return;
18845        }
18846
18847        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18848        int[] users;
18849        if (userId == UserHandle.USER_ALL) {
18850            users = sUserManager.getUserIds();
18851        } else {
18852            users = new int[] { userId };
18853        }
18854        final ClearStorageConnection conn = new ClearStorageConnection();
18855        if (mContext.bindServiceAsUser(
18856                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18857            try {
18858                for (int curUser : users) {
18859                    long timeout = SystemClock.uptimeMillis() + 5000;
18860                    synchronized (conn) {
18861                        long now;
18862                        while (conn.mContainerService == null &&
18863                                (now = SystemClock.uptimeMillis()) < timeout) {
18864                            try {
18865                                conn.wait(timeout - now);
18866                            } catch (InterruptedException e) {
18867                            }
18868                        }
18869                    }
18870                    if (conn.mContainerService == null) {
18871                        return;
18872                    }
18873
18874                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18875                    clearDirectory(conn.mContainerService,
18876                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18877                    if (allData) {
18878                        clearDirectory(conn.mContainerService,
18879                                userEnv.buildExternalStorageAppDataDirs(packageName));
18880                        clearDirectory(conn.mContainerService,
18881                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18882                    }
18883                }
18884            } finally {
18885                mContext.unbindService(conn);
18886            }
18887        }
18888    }
18889
18890    @Override
18891    public void clearApplicationProfileData(String packageName) {
18892        enforceSystemOrRoot("Only the system can clear all profile data");
18893
18894        final PackageParser.Package pkg;
18895        synchronized (mPackages) {
18896            pkg = mPackages.get(packageName);
18897        }
18898
18899        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18900            synchronized (mInstallLock) {
18901                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18902            }
18903        }
18904    }
18905
18906    @Override
18907    public void clearApplicationUserData(final String packageName,
18908            final IPackageDataObserver observer, final int userId) {
18909        mContext.enforceCallingOrSelfPermission(
18910                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18911
18912        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18913                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18914
18915        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18916            throw new SecurityException("Cannot clear data for a protected package: "
18917                    + packageName);
18918        }
18919        // Queue up an async operation since the package deletion may take a little while.
18920        mHandler.post(new Runnable() {
18921            public void run() {
18922                mHandler.removeCallbacks(this);
18923                final boolean succeeded;
18924                try (PackageFreezer freezer = freezePackage(packageName,
18925                        "clearApplicationUserData")) {
18926                    synchronized (mInstallLock) {
18927                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18928                    }
18929                    clearExternalStorageDataSync(packageName, userId, true);
18930                    synchronized (mPackages) {
18931                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18932                                packageName, userId);
18933                    }
18934                }
18935                if (succeeded) {
18936                    // invoke DeviceStorageMonitor's update method to clear any notifications
18937                    DeviceStorageMonitorInternal dsm = LocalServices
18938                            .getService(DeviceStorageMonitorInternal.class);
18939                    if (dsm != null) {
18940                        dsm.checkMemory();
18941                    }
18942                }
18943                if(observer != null) {
18944                    try {
18945                        observer.onRemoveCompleted(packageName, succeeded);
18946                    } catch (RemoteException e) {
18947                        Log.i(TAG, "Observer no longer exists.");
18948                    }
18949                } //end if observer
18950            } //end run
18951        });
18952    }
18953
18954    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18955        if (packageName == null) {
18956            Slog.w(TAG, "Attempt to delete null packageName.");
18957            return false;
18958        }
18959
18960        // Try finding details about the requested package
18961        PackageParser.Package pkg;
18962        synchronized (mPackages) {
18963            pkg = mPackages.get(packageName);
18964            if (pkg == null) {
18965                final PackageSetting ps = mSettings.mPackages.get(packageName);
18966                if (ps != null) {
18967                    pkg = ps.pkg;
18968                }
18969            }
18970
18971            if (pkg == null) {
18972                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18973                return false;
18974            }
18975
18976            PackageSetting ps = (PackageSetting) pkg.mExtras;
18977            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18978        }
18979
18980        clearAppDataLIF(pkg, userId,
18981                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18982
18983        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18984        removeKeystoreDataIfNeeded(userId, appId);
18985
18986        UserManagerInternal umInternal = getUserManagerInternal();
18987        final int flags;
18988        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18989            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18990        } else if (umInternal.isUserRunning(userId)) {
18991            flags = StorageManager.FLAG_STORAGE_DE;
18992        } else {
18993            flags = 0;
18994        }
18995        prepareAppDataContentsLIF(pkg, userId, flags);
18996
18997        return true;
18998    }
18999
19000    /**
19001     * Reverts user permission state changes (permissions and flags) in
19002     * all packages for a given user.
19003     *
19004     * @param userId The device user for which to do a reset.
19005     */
19006    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19007        final int packageCount = mPackages.size();
19008        for (int i = 0; i < packageCount; i++) {
19009            PackageParser.Package pkg = mPackages.valueAt(i);
19010            PackageSetting ps = (PackageSetting) pkg.mExtras;
19011            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19012        }
19013    }
19014
19015    private void resetNetworkPolicies(int userId) {
19016        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19017    }
19018
19019    /**
19020     * Reverts user permission state changes (permissions and flags).
19021     *
19022     * @param ps The package for which to reset.
19023     * @param userId The device user for which to do a reset.
19024     */
19025    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19026            final PackageSetting ps, final int userId) {
19027        if (ps.pkg == null) {
19028            return;
19029        }
19030
19031        // These are flags that can change base on user actions.
19032        final int userSettableMask = FLAG_PERMISSION_USER_SET
19033                | FLAG_PERMISSION_USER_FIXED
19034                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19035                | FLAG_PERMISSION_REVIEW_REQUIRED;
19036
19037        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19038                | FLAG_PERMISSION_POLICY_FIXED;
19039
19040        boolean writeInstallPermissions = false;
19041        boolean writeRuntimePermissions = false;
19042
19043        final int permissionCount = ps.pkg.requestedPermissions.size();
19044        for (int i = 0; i < permissionCount; i++) {
19045            String permission = ps.pkg.requestedPermissions.get(i);
19046
19047            BasePermission bp = mSettings.mPermissions.get(permission);
19048            if (bp == null) {
19049                continue;
19050            }
19051
19052            // If shared user we just reset the state to which only this app contributed.
19053            if (ps.sharedUser != null) {
19054                boolean used = false;
19055                final int packageCount = ps.sharedUser.packages.size();
19056                for (int j = 0; j < packageCount; j++) {
19057                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19058                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19059                            && pkg.pkg.requestedPermissions.contains(permission)) {
19060                        used = true;
19061                        break;
19062                    }
19063                }
19064                if (used) {
19065                    continue;
19066                }
19067            }
19068
19069            PermissionsState permissionsState = ps.getPermissionsState();
19070
19071            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19072
19073            // Always clear the user settable flags.
19074            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19075                    bp.name) != null;
19076            // If permission review is enabled and this is a legacy app, mark the
19077            // permission as requiring a review as this is the initial state.
19078            int flags = 0;
19079            if (mPermissionReviewRequired
19080                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19081                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19082            }
19083            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19084                if (hasInstallState) {
19085                    writeInstallPermissions = true;
19086                } else {
19087                    writeRuntimePermissions = true;
19088                }
19089            }
19090
19091            // Below is only runtime permission handling.
19092            if (!bp.isRuntime()) {
19093                continue;
19094            }
19095
19096            // Never clobber system or policy.
19097            if ((oldFlags & policyOrSystemFlags) != 0) {
19098                continue;
19099            }
19100
19101            // If this permission was granted by default, make sure it is.
19102            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19103                if (permissionsState.grantRuntimePermission(bp, userId)
19104                        != PERMISSION_OPERATION_FAILURE) {
19105                    writeRuntimePermissions = true;
19106                }
19107            // If permission review is enabled the permissions for a legacy apps
19108            // are represented as constantly granted runtime ones, so don't revoke.
19109            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19110                // Otherwise, reset the permission.
19111                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19112                switch (revokeResult) {
19113                    case PERMISSION_OPERATION_SUCCESS:
19114                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19115                        writeRuntimePermissions = true;
19116                        final int appId = ps.appId;
19117                        mHandler.post(new Runnable() {
19118                            @Override
19119                            public void run() {
19120                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19121                            }
19122                        });
19123                    } break;
19124                }
19125            }
19126        }
19127
19128        // Synchronously write as we are taking permissions away.
19129        if (writeRuntimePermissions) {
19130            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19131        }
19132
19133        // Synchronously write as we are taking permissions away.
19134        if (writeInstallPermissions) {
19135            mSettings.writeLPr();
19136        }
19137    }
19138
19139    /**
19140     * Remove entries from the keystore daemon. Will only remove it if the
19141     * {@code appId} is valid.
19142     */
19143    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19144        if (appId < 0) {
19145            return;
19146        }
19147
19148        final KeyStore keyStore = KeyStore.getInstance();
19149        if (keyStore != null) {
19150            if (userId == UserHandle.USER_ALL) {
19151                for (final int individual : sUserManager.getUserIds()) {
19152                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19153                }
19154            } else {
19155                keyStore.clearUid(UserHandle.getUid(userId, appId));
19156            }
19157        } else {
19158            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19159        }
19160    }
19161
19162    @Override
19163    public void deleteApplicationCacheFiles(final String packageName,
19164            final IPackageDataObserver observer) {
19165        final int userId = UserHandle.getCallingUserId();
19166        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19167    }
19168
19169    @Override
19170    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19171            final IPackageDataObserver observer) {
19172        mContext.enforceCallingOrSelfPermission(
19173                android.Manifest.permission.DELETE_CACHE_FILES, null);
19174        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19175                /* requireFullPermission= */ true, /* checkShell= */ false,
19176                "delete application cache files");
19177
19178        final PackageParser.Package pkg;
19179        synchronized (mPackages) {
19180            pkg = mPackages.get(packageName);
19181        }
19182
19183        // Queue up an async operation since the package deletion may take a little while.
19184        mHandler.post(new Runnable() {
19185            public void run() {
19186                synchronized (mInstallLock) {
19187                    final int flags = StorageManager.FLAG_STORAGE_DE
19188                            | StorageManager.FLAG_STORAGE_CE;
19189                    // We're only clearing cache files, so we don't care if the
19190                    // app is unfrozen and still able to run
19191                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19192                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19193                }
19194                clearExternalStorageDataSync(packageName, userId, false);
19195                if (observer != null) {
19196                    try {
19197                        observer.onRemoveCompleted(packageName, true);
19198                    } catch (RemoteException e) {
19199                        Log.i(TAG, "Observer no longer exists.");
19200                    }
19201                }
19202            }
19203        });
19204    }
19205
19206    @Override
19207    public void getPackageSizeInfo(final String packageName, int userHandle,
19208            final IPackageStatsObserver observer) {
19209        throw new UnsupportedOperationException(
19210                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19211    }
19212
19213    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19214        final PackageSetting ps;
19215        synchronized (mPackages) {
19216            ps = mSettings.mPackages.get(packageName);
19217            if (ps == null) {
19218                Slog.w(TAG, "Failed to find settings for " + packageName);
19219                return false;
19220            }
19221        }
19222
19223        final String[] packageNames = { packageName };
19224        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19225        final String[] codePaths = { ps.codePathString };
19226
19227        try {
19228            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19229                    ps.appId, ceDataInodes, codePaths, stats);
19230
19231            // For now, ignore code size of packages on system partition
19232            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19233                stats.codeSize = 0;
19234            }
19235
19236            // External clients expect these to be tracked separately
19237            stats.dataSize -= stats.cacheSize;
19238
19239        } catch (InstallerException e) {
19240            Slog.w(TAG, String.valueOf(e));
19241            return false;
19242        }
19243
19244        return true;
19245    }
19246
19247    private int getUidTargetSdkVersionLockedLPr(int uid) {
19248        Object obj = mSettings.getUserIdLPr(uid);
19249        if (obj instanceof SharedUserSetting) {
19250            final SharedUserSetting sus = (SharedUserSetting) obj;
19251            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19252            final Iterator<PackageSetting> it = sus.packages.iterator();
19253            while (it.hasNext()) {
19254                final PackageSetting ps = it.next();
19255                if (ps.pkg != null) {
19256                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19257                    if (v < vers) vers = v;
19258                }
19259            }
19260            return vers;
19261        } else if (obj instanceof PackageSetting) {
19262            final PackageSetting ps = (PackageSetting) obj;
19263            if (ps.pkg != null) {
19264                return ps.pkg.applicationInfo.targetSdkVersion;
19265            }
19266        }
19267        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19268    }
19269
19270    @Override
19271    public void addPreferredActivity(IntentFilter filter, int match,
19272            ComponentName[] set, ComponentName activity, int userId) {
19273        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19274                "Adding preferred");
19275    }
19276
19277    private void addPreferredActivityInternal(IntentFilter filter, int match,
19278            ComponentName[] set, ComponentName activity, boolean always, int userId,
19279            String opname) {
19280        // writer
19281        int callingUid = Binder.getCallingUid();
19282        enforceCrossUserPermission(callingUid, userId,
19283                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19284        if (filter.countActions() == 0) {
19285            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19286            return;
19287        }
19288        synchronized (mPackages) {
19289            if (mContext.checkCallingOrSelfPermission(
19290                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19291                    != PackageManager.PERMISSION_GRANTED) {
19292                if (getUidTargetSdkVersionLockedLPr(callingUid)
19293                        < Build.VERSION_CODES.FROYO) {
19294                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19295                            + callingUid);
19296                    return;
19297                }
19298                mContext.enforceCallingOrSelfPermission(
19299                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19300            }
19301
19302            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19303            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19304                    + userId + ":");
19305            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19306            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19307            scheduleWritePackageRestrictionsLocked(userId);
19308            postPreferredActivityChangedBroadcast(userId);
19309        }
19310    }
19311
19312    private void postPreferredActivityChangedBroadcast(int userId) {
19313        mHandler.post(() -> {
19314            final IActivityManager am = ActivityManager.getService();
19315            if (am == null) {
19316                return;
19317            }
19318
19319            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19320            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19321            try {
19322                am.broadcastIntent(null, intent, null, null,
19323                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19324                        null, false, false, userId);
19325            } catch (RemoteException e) {
19326            }
19327        });
19328    }
19329
19330    @Override
19331    public void replacePreferredActivity(IntentFilter filter, int match,
19332            ComponentName[] set, ComponentName activity, int userId) {
19333        if (filter.countActions() != 1) {
19334            throw new IllegalArgumentException(
19335                    "replacePreferredActivity expects filter to have only 1 action.");
19336        }
19337        if (filter.countDataAuthorities() != 0
19338                || filter.countDataPaths() != 0
19339                || filter.countDataSchemes() > 1
19340                || filter.countDataTypes() != 0) {
19341            throw new IllegalArgumentException(
19342                    "replacePreferredActivity expects filter to have no data authorities, " +
19343                    "paths, or types; and at most one scheme.");
19344        }
19345
19346        final int callingUid = Binder.getCallingUid();
19347        enforceCrossUserPermission(callingUid, userId,
19348                true /* requireFullPermission */, false /* checkShell */,
19349                "replace preferred activity");
19350        synchronized (mPackages) {
19351            if (mContext.checkCallingOrSelfPermission(
19352                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19353                    != PackageManager.PERMISSION_GRANTED) {
19354                if (getUidTargetSdkVersionLockedLPr(callingUid)
19355                        < Build.VERSION_CODES.FROYO) {
19356                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19357                            + Binder.getCallingUid());
19358                    return;
19359                }
19360                mContext.enforceCallingOrSelfPermission(
19361                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19362            }
19363
19364            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19365            if (pir != null) {
19366                // Get all of the existing entries that exactly match this filter.
19367                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19368                if (existing != null && existing.size() == 1) {
19369                    PreferredActivity cur = existing.get(0);
19370                    if (DEBUG_PREFERRED) {
19371                        Slog.i(TAG, "Checking replace of preferred:");
19372                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19373                        if (!cur.mPref.mAlways) {
19374                            Slog.i(TAG, "  -- CUR; not mAlways!");
19375                        } else {
19376                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19377                            Slog.i(TAG, "  -- CUR: mSet="
19378                                    + Arrays.toString(cur.mPref.mSetComponents));
19379                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19380                            Slog.i(TAG, "  -- NEW: mMatch="
19381                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19382                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19383                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19384                        }
19385                    }
19386                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19387                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19388                            && cur.mPref.sameSet(set)) {
19389                        // Setting the preferred activity to what it happens to be already
19390                        if (DEBUG_PREFERRED) {
19391                            Slog.i(TAG, "Replacing with same preferred activity "
19392                                    + cur.mPref.mShortComponent + " for user "
19393                                    + userId + ":");
19394                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19395                        }
19396                        return;
19397                    }
19398                }
19399
19400                if (existing != null) {
19401                    if (DEBUG_PREFERRED) {
19402                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19403                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19404                    }
19405                    for (int i = 0; i < existing.size(); i++) {
19406                        PreferredActivity pa = existing.get(i);
19407                        if (DEBUG_PREFERRED) {
19408                            Slog.i(TAG, "Removing existing preferred activity "
19409                                    + pa.mPref.mComponent + ":");
19410                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19411                        }
19412                        pir.removeFilter(pa);
19413                    }
19414                }
19415            }
19416            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19417                    "Replacing preferred");
19418        }
19419    }
19420
19421    @Override
19422    public void clearPackagePreferredActivities(String packageName) {
19423        final int uid = Binder.getCallingUid();
19424        // writer
19425        synchronized (mPackages) {
19426            PackageParser.Package pkg = mPackages.get(packageName);
19427            if (pkg == null || pkg.applicationInfo.uid != uid) {
19428                if (mContext.checkCallingOrSelfPermission(
19429                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19430                        != PackageManager.PERMISSION_GRANTED) {
19431                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19432                            < Build.VERSION_CODES.FROYO) {
19433                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19434                                + Binder.getCallingUid());
19435                        return;
19436                    }
19437                    mContext.enforceCallingOrSelfPermission(
19438                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19439                }
19440            }
19441
19442            int user = UserHandle.getCallingUserId();
19443            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19444                scheduleWritePackageRestrictionsLocked(user);
19445            }
19446        }
19447    }
19448
19449    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19450    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19451        ArrayList<PreferredActivity> removed = null;
19452        boolean changed = false;
19453        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19454            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19455            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19456            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19457                continue;
19458            }
19459            Iterator<PreferredActivity> it = pir.filterIterator();
19460            while (it.hasNext()) {
19461                PreferredActivity pa = it.next();
19462                // Mark entry for removal only if it matches the package name
19463                // and the entry is of type "always".
19464                if (packageName == null ||
19465                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19466                                && pa.mPref.mAlways)) {
19467                    if (removed == null) {
19468                        removed = new ArrayList<PreferredActivity>();
19469                    }
19470                    removed.add(pa);
19471                }
19472            }
19473            if (removed != null) {
19474                for (int j=0; j<removed.size(); j++) {
19475                    PreferredActivity pa = removed.get(j);
19476                    pir.removeFilter(pa);
19477                }
19478                changed = true;
19479            }
19480        }
19481        if (changed) {
19482            postPreferredActivityChangedBroadcast(userId);
19483        }
19484        return changed;
19485    }
19486
19487    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19488    private void clearIntentFilterVerificationsLPw(int userId) {
19489        final int packageCount = mPackages.size();
19490        for (int i = 0; i < packageCount; i++) {
19491            PackageParser.Package pkg = mPackages.valueAt(i);
19492            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19493        }
19494    }
19495
19496    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19497    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19498        if (userId == UserHandle.USER_ALL) {
19499            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19500                    sUserManager.getUserIds())) {
19501                for (int oneUserId : sUserManager.getUserIds()) {
19502                    scheduleWritePackageRestrictionsLocked(oneUserId);
19503                }
19504            }
19505        } else {
19506            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19507                scheduleWritePackageRestrictionsLocked(userId);
19508            }
19509        }
19510    }
19511
19512    /** Clears state for all users, and touches intent filter verification policy */
19513    void clearDefaultBrowserIfNeeded(String packageName) {
19514        for (int oneUserId : sUserManager.getUserIds()) {
19515            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19516        }
19517    }
19518
19519    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19520        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19521        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19522            if (packageName.equals(defaultBrowserPackageName)) {
19523                setDefaultBrowserPackageName(null, userId);
19524            }
19525        }
19526    }
19527
19528    @Override
19529    public void resetApplicationPreferences(int userId) {
19530        mContext.enforceCallingOrSelfPermission(
19531                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19532        final long identity = Binder.clearCallingIdentity();
19533        // writer
19534        try {
19535            synchronized (mPackages) {
19536                clearPackagePreferredActivitiesLPw(null, userId);
19537                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19538                // TODO: We have to reset the default SMS and Phone. This requires
19539                // significant refactoring to keep all default apps in the package
19540                // manager (cleaner but more work) or have the services provide
19541                // callbacks to the package manager to request a default app reset.
19542                applyFactoryDefaultBrowserLPw(userId);
19543                clearIntentFilterVerificationsLPw(userId);
19544                primeDomainVerificationsLPw(userId);
19545                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19546                scheduleWritePackageRestrictionsLocked(userId);
19547            }
19548            resetNetworkPolicies(userId);
19549        } finally {
19550            Binder.restoreCallingIdentity(identity);
19551        }
19552    }
19553
19554    @Override
19555    public int getPreferredActivities(List<IntentFilter> outFilters,
19556            List<ComponentName> outActivities, String packageName) {
19557
19558        int num = 0;
19559        final int userId = UserHandle.getCallingUserId();
19560        // reader
19561        synchronized (mPackages) {
19562            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19563            if (pir != null) {
19564                final Iterator<PreferredActivity> it = pir.filterIterator();
19565                while (it.hasNext()) {
19566                    final PreferredActivity pa = it.next();
19567                    if (packageName == null
19568                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19569                                    && pa.mPref.mAlways)) {
19570                        if (outFilters != null) {
19571                            outFilters.add(new IntentFilter(pa));
19572                        }
19573                        if (outActivities != null) {
19574                            outActivities.add(pa.mPref.mComponent);
19575                        }
19576                    }
19577                }
19578            }
19579        }
19580
19581        return num;
19582    }
19583
19584    @Override
19585    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19586            int userId) {
19587        int callingUid = Binder.getCallingUid();
19588        if (callingUid != Process.SYSTEM_UID) {
19589            throw new SecurityException(
19590                    "addPersistentPreferredActivity can only be run by the system");
19591        }
19592        if (filter.countActions() == 0) {
19593            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19594            return;
19595        }
19596        synchronized (mPackages) {
19597            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19598                    ":");
19599            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19600            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19601                    new PersistentPreferredActivity(filter, activity));
19602            scheduleWritePackageRestrictionsLocked(userId);
19603            postPreferredActivityChangedBroadcast(userId);
19604        }
19605    }
19606
19607    @Override
19608    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19609        int callingUid = Binder.getCallingUid();
19610        if (callingUid != Process.SYSTEM_UID) {
19611            throw new SecurityException(
19612                    "clearPackagePersistentPreferredActivities can only be run by the system");
19613        }
19614        ArrayList<PersistentPreferredActivity> removed = null;
19615        boolean changed = false;
19616        synchronized (mPackages) {
19617            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19618                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19619                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19620                        .valueAt(i);
19621                if (userId != thisUserId) {
19622                    continue;
19623                }
19624                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19625                while (it.hasNext()) {
19626                    PersistentPreferredActivity ppa = it.next();
19627                    // Mark entry for removal only if it matches the package name.
19628                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19629                        if (removed == null) {
19630                            removed = new ArrayList<PersistentPreferredActivity>();
19631                        }
19632                        removed.add(ppa);
19633                    }
19634                }
19635                if (removed != null) {
19636                    for (int j=0; j<removed.size(); j++) {
19637                        PersistentPreferredActivity ppa = removed.get(j);
19638                        ppir.removeFilter(ppa);
19639                    }
19640                    changed = true;
19641                }
19642            }
19643
19644            if (changed) {
19645                scheduleWritePackageRestrictionsLocked(userId);
19646                postPreferredActivityChangedBroadcast(userId);
19647            }
19648        }
19649    }
19650
19651    /**
19652     * Common machinery for picking apart a restored XML blob and passing
19653     * it to a caller-supplied functor to be applied to the running system.
19654     */
19655    private void restoreFromXml(XmlPullParser parser, int userId,
19656            String expectedStartTag, BlobXmlRestorer functor)
19657            throws IOException, XmlPullParserException {
19658        int type;
19659        while ((type = parser.next()) != XmlPullParser.START_TAG
19660                && type != XmlPullParser.END_DOCUMENT) {
19661        }
19662        if (type != XmlPullParser.START_TAG) {
19663            // oops didn't find a start tag?!
19664            if (DEBUG_BACKUP) {
19665                Slog.e(TAG, "Didn't find start tag during restore");
19666            }
19667            return;
19668        }
19669Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19670        // this is supposed to be TAG_PREFERRED_BACKUP
19671        if (!expectedStartTag.equals(parser.getName())) {
19672            if (DEBUG_BACKUP) {
19673                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19674            }
19675            return;
19676        }
19677
19678        // skip interfering stuff, then we're aligned with the backing implementation
19679        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19680Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19681        functor.apply(parser, userId);
19682    }
19683
19684    private interface BlobXmlRestorer {
19685        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19686    }
19687
19688    /**
19689     * Non-Binder method, support for the backup/restore mechanism: write the
19690     * full set of preferred activities in its canonical XML format.  Returns the
19691     * XML output as a byte array, or null if there is none.
19692     */
19693    @Override
19694    public byte[] getPreferredActivityBackup(int userId) {
19695        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19696            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19697        }
19698
19699        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19700        try {
19701            final XmlSerializer serializer = new FastXmlSerializer();
19702            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19703            serializer.startDocument(null, true);
19704            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19705
19706            synchronized (mPackages) {
19707                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19708            }
19709
19710            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19711            serializer.endDocument();
19712            serializer.flush();
19713        } catch (Exception e) {
19714            if (DEBUG_BACKUP) {
19715                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19716            }
19717            return null;
19718        }
19719
19720        return dataStream.toByteArray();
19721    }
19722
19723    @Override
19724    public void restorePreferredActivities(byte[] backup, int userId) {
19725        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19726            throw new SecurityException("Only the system may call restorePreferredActivities()");
19727        }
19728
19729        try {
19730            final XmlPullParser parser = Xml.newPullParser();
19731            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19732            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19733                    new BlobXmlRestorer() {
19734                        @Override
19735                        public void apply(XmlPullParser parser, int userId)
19736                                throws XmlPullParserException, IOException {
19737                            synchronized (mPackages) {
19738                                mSettings.readPreferredActivitiesLPw(parser, userId);
19739                            }
19740                        }
19741                    } );
19742        } catch (Exception e) {
19743            if (DEBUG_BACKUP) {
19744                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19745            }
19746        }
19747    }
19748
19749    /**
19750     * Non-Binder method, support for the backup/restore mechanism: write the
19751     * default browser (etc) settings in its canonical XML format.  Returns the default
19752     * browser XML representation as a byte array, or null if there is none.
19753     */
19754    @Override
19755    public byte[] getDefaultAppsBackup(int userId) {
19756        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19757            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19758        }
19759
19760        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19761        try {
19762            final XmlSerializer serializer = new FastXmlSerializer();
19763            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19764            serializer.startDocument(null, true);
19765            serializer.startTag(null, TAG_DEFAULT_APPS);
19766
19767            synchronized (mPackages) {
19768                mSettings.writeDefaultAppsLPr(serializer, userId);
19769            }
19770
19771            serializer.endTag(null, TAG_DEFAULT_APPS);
19772            serializer.endDocument();
19773            serializer.flush();
19774        } catch (Exception e) {
19775            if (DEBUG_BACKUP) {
19776                Slog.e(TAG, "Unable to write default apps for backup", e);
19777            }
19778            return null;
19779        }
19780
19781        return dataStream.toByteArray();
19782    }
19783
19784    @Override
19785    public void restoreDefaultApps(byte[] backup, int userId) {
19786        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19787            throw new SecurityException("Only the system may call restoreDefaultApps()");
19788        }
19789
19790        try {
19791            final XmlPullParser parser = Xml.newPullParser();
19792            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19793            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19794                    new BlobXmlRestorer() {
19795                        @Override
19796                        public void apply(XmlPullParser parser, int userId)
19797                                throws XmlPullParserException, IOException {
19798                            synchronized (mPackages) {
19799                                mSettings.readDefaultAppsLPw(parser, userId);
19800                            }
19801                        }
19802                    } );
19803        } catch (Exception e) {
19804            if (DEBUG_BACKUP) {
19805                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19806            }
19807        }
19808    }
19809
19810    @Override
19811    public byte[] getIntentFilterVerificationBackup(int userId) {
19812        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19813            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19814        }
19815
19816        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19817        try {
19818            final XmlSerializer serializer = new FastXmlSerializer();
19819            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19820            serializer.startDocument(null, true);
19821            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19822
19823            synchronized (mPackages) {
19824                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19825            }
19826
19827            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19828            serializer.endDocument();
19829            serializer.flush();
19830        } catch (Exception e) {
19831            if (DEBUG_BACKUP) {
19832                Slog.e(TAG, "Unable to write default apps for backup", e);
19833            }
19834            return null;
19835        }
19836
19837        return dataStream.toByteArray();
19838    }
19839
19840    @Override
19841    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19842        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19843            throw new SecurityException("Only the system may call restorePreferredActivities()");
19844        }
19845
19846        try {
19847            final XmlPullParser parser = Xml.newPullParser();
19848            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19849            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19850                    new BlobXmlRestorer() {
19851                        @Override
19852                        public void apply(XmlPullParser parser, int userId)
19853                                throws XmlPullParserException, IOException {
19854                            synchronized (mPackages) {
19855                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19856                                mSettings.writeLPr();
19857                            }
19858                        }
19859                    } );
19860        } catch (Exception e) {
19861            if (DEBUG_BACKUP) {
19862                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19863            }
19864        }
19865    }
19866
19867    @Override
19868    public byte[] getPermissionGrantBackup(int userId) {
19869        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19870            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19871        }
19872
19873        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19874        try {
19875            final XmlSerializer serializer = new FastXmlSerializer();
19876            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19877            serializer.startDocument(null, true);
19878            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19879
19880            synchronized (mPackages) {
19881                serializeRuntimePermissionGrantsLPr(serializer, userId);
19882            }
19883
19884            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19885            serializer.endDocument();
19886            serializer.flush();
19887        } catch (Exception e) {
19888            if (DEBUG_BACKUP) {
19889                Slog.e(TAG, "Unable to write default apps for backup", e);
19890            }
19891            return null;
19892        }
19893
19894        return dataStream.toByteArray();
19895    }
19896
19897    @Override
19898    public void restorePermissionGrants(byte[] backup, int userId) {
19899        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19900            throw new SecurityException("Only the system may call restorePermissionGrants()");
19901        }
19902
19903        try {
19904            final XmlPullParser parser = Xml.newPullParser();
19905            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19906            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19907                    new BlobXmlRestorer() {
19908                        @Override
19909                        public void apply(XmlPullParser parser, int userId)
19910                                throws XmlPullParserException, IOException {
19911                            synchronized (mPackages) {
19912                                processRestoredPermissionGrantsLPr(parser, userId);
19913                            }
19914                        }
19915                    } );
19916        } catch (Exception e) {
19917            if (DEBUG_BACKUP) {
19918                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19919            }
19920        }
19921    }
19922
19923    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19924            throws IOException {
19925        serializer.startTag(null, TAG_ALL_GRANTS);
19926
19927        final int N = mSettings.mPackages.size();
19928        for (int i = 0; i < N; i++) {
19929            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19930            boolean pkgGrantsKnown = false;
19931
19932            PermissionsState packagePerms = ps.getPermissionsState();
19933
19934            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19935                final int grantFlags = state.getFlags();
19936                // only look at grants that are not system/policy fixed
19937                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19938                    final boolean isGranted = state.isGranted();
19939                    // And only back up the user-twiddled state bits
19940                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19941                        final String packageName = mSettings.mPackages.keyAt(i);
19942                        if (!pkgGrantsKnown) {
19943                            serializer.startTag(null, TAG_GRANT);
19944                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19945                            pkgGrantsKnown = true;
19946                        }
19947
19948                        final boolean userSet =
19949                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19950                        final boolean userFixed =
19951                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19952                        final boolean revoke =
19953                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19954
19955                        serializer.startTag(null, TAG_PERMISSION);
19956                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19957                        if (isGranted) {
19958                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19959                        }
19960                        if (userSet) {
19961                            serializer.attribute(null, ATTR_USER_SET, "true");
19962                        }
19963                        if (userFixed) {
19964                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19965                        }
19966                        if (revoke) {
19967                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19968                        }
19969                        serializer.endTag(null, TAG_PERMISSION);
19970                    }
19971                }
19972            }
19973
19974            if (pkgGrantsKnown) {
19975                serializer.endTag(null, TAG_GRANT);
19976            }
19977        }
19978
19979        serializer.endTag(null, TAG_ALL_GRANTS);
19980    }
19981
19982    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19983            throws XmlPullParserException, IOException {
19984        String pkgName = null;
19985        int outerDepth = parser.getDepth();
19986        int type;
19987        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19988                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19989            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19990                continue;
19991            }
19992
19993            final String tagName = parser.getName();
19994            if (tagName.equals(TAG_GRANT)) {
19995                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19996                if (DEBUG_BACKUP) {
19997                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19998                }
19999            } else if (tagName.equals(TAG_PERMISSION)) {
20000
20001                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20002                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20003
20004                int newFlagSet = 0;
20005                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20006                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20007                }
20008                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20009                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20010                }
20011                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20012                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20013                }
20014                if (DEBUG_BACKUP) {
20015                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20016                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20017                }
20018                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20019                if (ps != null) {
20020                    // Already installed so we apply the grant immediately
20021                    if (DEBUG_BACKUP) {
20022                        Slog.v(TAG, "        + already installed; applying");
20023                    }
20024                    PermissionsState perms = ps.getPermissionsState();
20025                    BasePermission bp = mSettings.mPermissions.get(permName);
20026                    if (bp != null) {
20027                        if (isGranted) {
20028                            perms.grantRuntimePermission(bp, userId);
20029                        }
20030                        if (newFlagSet != 0) {
20031                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20032                        }
20033                    }
20034                } else {
20035                    // Need to wait for post-restore install to apply the grant
20036                    if (DEBUG_BACKUP) {
20037                        Slog.v(TAG, "        - not yet installed; saving for later");
20038                    }
20039                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20040                            isGranted, newFlagSet, userId);
20041                }
20042            } else {
20043                PackageManagerService.reportSettingsProblem(Log.WARN,
20044                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20045                XmlUtils.skipCurrentTag(parser);
20046            }
20047        }
20048
20049        scheduleWriteSettingsLocked();
20050        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20051    }
20052
20053    @Override
20054    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20055            int sourceUserId, int targetUserId, int flags) {
20056        mContext.enforceCallingOrSelfPermission(
20057                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20058        int callingUid = Binder.getCallingUid();
20059        enforceOwnerRights(ownerPackage, callingUid);
20060        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20061        if (intentFilter.countActions() == 0) {
20062            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20063            return;
20064        }
20065        synchronized (mPackages) {
20066            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20067                    ownerPackage, targetUserId, flags);
20068            CrossProfileIntentResolver resolver =
20069                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20070            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20071            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20072            if (existing != null) {
20073                int size = existing.size();
20074                for (int i = 0; i < size; i++) {
20075                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20076                        return;
20077                    }
20078                }
20079            }
20080            resolver.addFilter(newFilter);
20081            scheduleWritePackageRestrictionsLocked(sourceUserId);
20082        }
20083    }
20084
20085    @Override
20086    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20087        mContext.enforceCallingOrSelfPermission(
20088                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20089        int callingUid = Binder.getCallingUid();
20090        enforceOwnerRights(ownerPackage, callingUid);
20091        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20092        synchronized (mPackages) {
20093            CrossProfileIntentResolver resolver =
20094                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20095            ArraySet<CrossProfileIntentFilter> set =
20096                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20097            for (CrossProfileIntentFilter filter : set) {
20098                if (filter.getOwnerPackage().equals(ownerPackage)) {
20099                    resolver.removeFilter(filter);
20100                }
20101            }
20102            scheduleWritePackageRestrictionsLocked(sourceUserId);
20103        }
20104    }
20105
20106    // Enforcing that callingUid is owning pkg on userId
20107    private void enforceOwnerRights(String pkg, int callingUid) {
20108        // The system owns everything.
20109        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20110            return;
20111        }
20112        int callingUserId = UserHandle.getUserId(callingUid);
20113        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20114        if (pi == null) {
20115            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20116                    + callingUserId);
20117        }
20118        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20119            throw new SecurityException("Calling uid " + callingUid
20120                    + " does not own package " + pkg);
20121        }
20122    }
20123
20124    @Override
20125    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20126        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20127    }
20128
20129    /**
20130     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20131     * then reports the most likely home activity or null if there are more than one.
20132     */
20133    public ComponentName getDefaultHomeActivity(int userId) {
20134        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20135        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20136        if (cn != null) {
20137            return cn;
20138        }
20139
20140        // Find the launcher with the highest priority and return that component if there are no
20141        // other home activity with the same priority.
20142        int lastPriority = Integer.MIN_VALUE;
20143        ComponentName lastComponent = null;
20144        final int size = allHomeCandidates.size();
20145        for (int i = 0; i < size; i++) {
20146            final ResolveInfo ri = allHomeCandidates.get(i);
20147            if (ri.priority > lastPriority) {
20148                lastComponent = ri.activityInfo.getComponentName();
20149                lastPriority = ri.priority;
20150            } else if (ri.priority == lastPriority) {
20151                // Two components found with same priority.
20152                lastComponent = null;
20153            }
20154        }
20155        return lastComponent;
20156    }
20157
20158    private Intent getHomeIntent() {
20159        Intent intent = new Intent(Intent.ACTION_MAIN);
20160        intent.addCategory(Intent.CATEGORY_HOME);
20161        intent.addCategory(Intent.CATEGORY_DEFAULT);
20162        return intent;
20163    }
20164
20165    private IntentFilter getHomeFilter() {
20166        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20167        filter.addCategory(Intent.CATEGORY_HOME);
20168        filter.addCategory(Intent.CATEGORY_DEFAULT);
20169        return filter;
20170    }
20171
20172    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20173            int userId) {
20174        Intent intent  = getHomeIntent();
20175        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20176                PackageManager.GET_META_DATA, userId);
20177        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20178                true, false, false, userId);
20179
20180        allHomeCandidates.clear();
20181        if (list != null) {
20182            for (ResolveInfo ri : list) {
20183                allHomeCandidates.add(ri);
20184            }
20185        }
20186        return (preferred == null || preferred.activityInfo == null)
20187                ? null
20188                : new ComponentName(preferred.activityInfo.packageName,
20189                        preferred.activityInfo.name);
20190    }
20191
20192    @Override
20193    public void setHomeActivity(ComponentName comp, int userId) {
20194        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20195        getHomeActivitiesAsUser(homeActivities, userId);
20196
20197        boolean found = false;
20198
20199        final int size = homeActivities.size();
20200        final ComponentName[] set = new ComponentName[size];
20201        for (int i = 0; i < size; i++) {
20202            final ResolveInfo candidate = homeActivities.get(i);
20203            final ActivityInfo info = candidate.activityInfo;
20204            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20205            set[i] = activityName;
20206            if (!found && activityName.equals(comp)) {
20207                found = true;
20208            }
20209        }
20210        if (!found) {
20211            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20212                    + userId);
20213        }
20214        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20215                set, comp, userId);
20216    }
20217
20218    private @Nullable String getSetupWizardPackageName() {
20219        final Intent intent = new Intent(Intent.ACTION_MAIN);
20220        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20221
20222        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20223                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20224                        | MATCH_DISABLED_COMPONENTS,
20225                UserHandle.myUserId());
20226        if (matches.size() == 1) {
20227            return matches.get(0).getComponentInfo().packageName;
20228        } else {
20229            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20230                    + ": matches=" + matches);
20231            return null;
20232        }
20233    }
20234
20235    private @Nullable String getStorageManagerPackageName() {
20236        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20237
20238        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20239                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20240                        | MATCH_DISABLED_COMPONENTS,
20241                UserHandle.myUserId());
20242        if (matches.size() == 1) {
20243            return matches.get(0).getComponentInfo().packageName;
20244        } else {
20245            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20246                    + matches.size() + ": matches=" + matches);
20247            return null;
20248        }
20249    }
20250
20251    @Override
20252    public void setApplicationEnabledSetting(String appPackageName,
20253            int newState, int flags, int userId, String callingPackage) {
20254        if (!sUserManager.exists(userId)) return;
20255        if (callingPackage == null) {
20256            callingPackage = Integer.toString(Binder.getCallingUid());
20257        }
20258        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20259    }
20260
20261    @Override
20262    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20263        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20264        synchronized (mPackages) {
20265            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20266            if (pkgSetting != null) {
20267                pkgSetting.setUpdateAvailable(updateAvailable);
20268            }
20269        }
20270    }
20271
20272    @Override
20273    public void setComponentEnabledSetting(ComponentName componentName,
20274            int newState, int flags, int userId) {
20275        if (!sUserManager.exists(userId)) return;
20276        setEnabledSetting(componentName.getPackageName(),
20277                componentName.getClassName(), newState, flags, userId, null);
20278    }
20279
20280    private void setEnabledSetting(final String packageName, String className, int newState,
20281            final int flags, int userId, String callingPackage) {
20282        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20283              || newState == COMPONENT_ENABLED_STATE_ENABLED
20284              || newState == COMPONENT_ENABLED_STATE_DISABLED
20285              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20286              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20287            throw new IllegalArgumentException("Invalid new component state: "
20288                    + newState);
20289        }
20290        PackageSetting pkgSetting;
20291        final int uid = Binder.getCallingUid();
20292        final int permission;
20293        if (uid == Process.SYSTEM_UID) {
20294            permission = PackageManager.PERMISSION_GRANTED;
20295        } else {
20296            permission = mContext.checkCallingOrSelfPermission(
20297                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20298        }
20299        enforceCrossUserPermission(uid, userId,
20300                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20301        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20302        boolean sendNow = false;
20303        boolean isApp = (className == null);
20304        String componentName = isApp ? packageName : className;
20305        int packageUid = -1;
20306        ArrayList<String> components;
20307
20308        // writer
20309        synchronized (mPackages) {
20310            pkgSetting = mSettings.mPackages.get(packageName);
20311            if (pkgSetting == null) {
20312                if (className == null) {
20313                    throw new IllegalArgumentException("Unknown package: " + packageName);
20314                }
20315                throw new IllegalArgumentException(
20316                        "Unknown component: " + packageName + "/" + className);
20317            }
20318        }
20319
20320        // Limit who can change which apps
20321        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20322            // Don't allow apps that don't have permission to modify other apps
20323            if (!allowedByPermission) {
20324                throw new SecurityException(
20325                        "Permission Denial: attempt to change component state from pid="
20326                        + Binder.getCallingPid()
20327                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20328            }
20329            // Don't allow changing protected packages.
20330            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20331                throw new SecurityException("Cannot disable a protected package: " + packageName);
20332            }
20333        }
20334
20335        synchronized (mPackages) {
20336            if (uid == Process.SHELL_UID
20337                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20338                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20339                // unless it is a test package.
20340                int oldState = pkgSetting.getEnabled(userId);
20341                if (className == null
20342                    &&
20343                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20344                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20345                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20346                    &&
20347                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20348                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20349                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20350                    // ok
20351                } else {
20352                    throw new SecurityException(
20353                            "Shell cannot change component state for " + packageName + "/"
20354                            + className + " to " + newState);
20355                }
20356            }
20357            if (className == null) {
20358                // We're dealing with an application/package level state change
20359                if (pkgSetting.getEnabled(userId) == newState) {
20360                    // Nothing to do
20361                    return;
20362                }
20363                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20364                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20365                    // Don't care about who enables an app.
20366                    callingPackage = null;
20367                }
20368                pkgSetting.setEnabled(newState, userId, callingPackage);
20369                // pkgSetting.pkg.mSetEnabled = newState;
20370            } else {
20371                // We're dealing with a component level state change
20372                // First, verify that this is a valid class name.
20373                PackageParser.Package pkg = pkgSetting.pkg;
20374                if (pkg == null || !pkg.hasComponentClassName(className)) {
20375                    if (pkg != null &&
20376                            pkg.applicationInfo.targetSdkVersion >=
20377                                    Build.VERSION_CODES.JELLY_BEAN) {
20378                        throw new IllegalArgumentException("Component class " + className
20379                                + " does not exist in " + packageName);
20380                    } else {
20381                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20382                                + className + " does not exist in " + packageName);
20383                    }
20384                }
20385                switch (newState) {
20386                case COMPONENT_ENABLED_STATE_ENABLED:
20387                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20388                        return;
20389                    }
20390                    break;
20391                case COMPONENT_ENABLED_STATE_DISABLED:
20392                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20393                        return;
20394                    }
20395                    break;
20396                case COMPONENT_ENABLED_STATE_DEFAULT:
20397                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20398                        return;
20399                    }
20400                    break;
20401                default:
20402                    Slog.e(TAG, "Invalid new component state: " + newState);
20403                    return;
20404                }
20405            }
20406            scheduleWritePackageRestrictionsLocked(userId);
20407            updateSequenceNumberLP(packageName, new int[] { userId });
20408            final long callingId = Binder.clearCallingIdentity();
20409            try {
20410                updateInstantAppInstallerLocked(packageName);
20411            } finally {
20412                Binder.restoreCallingIdentity(callingId);
20413            }
20414            components = mPendingBroadcasts.get(userId, packageName);
20415            final boolean newPackage = components == null;
20416            if (newPackage) {
20417                components = new ArrayList<String>();
20418            }
20419            if (!components.contains(componentName)) {
20420                components.add(componentName);
20421            }
20422            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20423                sendNow = true;
20424                // Purge entry from pending broadcast list if another one exists already
20425                // since we are sending one right away.
20426                mPendingBroadcasts.remove(userId, packageName);
20427            } else {
20428                if (newPackage) {
20429                    mPendingBroadcasts.put(userId, packageName, components);
20430                }
20431                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20432                    // Schedule a message
20433                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20434                }
20435            }
20436        }
20437
20438        long callingId = Binder.clearCallingIdentity();
20439        try {
20440            if (sendNow) {
20441                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20442                sendPackageChangedBroadcast(packageName,
20443                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20444            }
20445        } finally {
20446            Binder.restoreCallingIdentity(callingId);
20447        }
20448    }
20449
20450    @Override
20451    public void flushPackageRestrictionsAsUser(int userId) {
20452        if (!sUserManager.exists(userId)) {
20453            return;
20454        }
20455        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20456                false /* checkShell */, "flushPackageRestrictions");
20457        synchronized (mPackages) {
20458            mSettings.writePackageRestrictionsLPr(userId);
20459            mDirtyUsers.remove(userId);
20460            if (mDirtyUsers.isEmpty()) {
20461                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20462            }
20463        }
20464    }
20465
20466    private void sendPackageChangedBroadcast(String packageName,
20467            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20468        if (DEBUG_INSTALL)
20469            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20470                    + componentNames);
20471        Bundle extras = new Bundle(4);
20472        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20473        String nameList[] = new String[componentNames.size()];
20474        componentNames.toArray(nameList);
20475        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20476        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20477        extras.putInt(Intent.EXTRA_UID, packageUid);
20478        // If this is not reporting a change of the overall package, then only send it
20479        // to registered receivers.  We don't want to launch a swath of apps for every
20480        // little component state change.
20481        final int flags = !componentNames.contains(packageName)
20482                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20483        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20484                new int[] {UserHandle.getUserId(packageUid)});
20485    }
20486
20487    @Override
20488    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20489        if (!sUserManager.exists(userId)) return;
20490        final int uid = Binder.getCallingUid();
20491        final int permission = mContext.checkCallingOrSelfPermission(
20492                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20493        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20494        enforceCrossUserPermission(uid, userId,
20495                true /* requireFullPermission */, true /* checkShell */, "stop package");
20496        // writer
20497        synchronized (mPackages) {
20498            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20499                    allowedByPermission, uid, userId)) {
20500                scheduleWritePackageRestrictionsLocked(userId);
20501            }
20502        }
20503    }
20504
20505    @Override
20506    public String getInstallerPackageName(String packageName) {
20507        // reader
20508        synchronized (mPackages) {
20509            return mSettings.getInstallerPackageNameLPr(packageName);
20510        }
20511    }
20512
20513    public boolean isOrphaned(String packageName) {
20514        // reader
20515        synchronized (mPackages) {
20516            return mSettings.isOrphaned(packageName);
20517        }
20518    }
20519
20520    @Override
20521    public int getApplicationEnabledSetting(String packageName, int userId) {
20522        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20523        int uid = Binder.getCallingUid();
20524        enforceCrossUserPermission(uid, userId,
20525                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20526        // reader
20527        synchronized (mPackages) {
20528            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20529        }
20530    }
20531
20532    @Override
20533    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20534        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20535        int uid = Binder.getCallingUid();
20536        enforceCrossUserPermission(uid, userId,
20537                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20538        // reader
20539        synchronized (mPackages) {
20540            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20541        }
20542    }
20543
20544    @Override
20545    public void enterSafeMode() {
20546        enforceSystemOrRoot("Only the system can request entering safe mode");
20547
20548        if (!mSystemReady) {
20549            mSafeMode = true;
20550        }
20551    }
20552
20553    @Override
20554    public void systemReady() {
20555        mSystemReady = true;
20556        final ContentResolver resolver = mContext.getContentResolver();
20557        ContentObserver co = new ContentObserver(mHandler) {
20558            @Override
20559            public void onChange(boolean selfChange) {
20560                mEphemeralAppsDisabled =
20561                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20562                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20563            }
20564        };
20565        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20566                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20567                false, co, UserHandle.USER_SYSTEM);
20568        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20569                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20570        co.onChange(true);
20571
20572        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20573        // disabled after already being started.
20574        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20575                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20576
20577        // Read the compatibilty setting when the system is ready.
20578        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20579                mContext.getContentResolver(),
20580                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20581        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20582        if (DEBUG_SETTINGS) {
20583            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20584        }
20585
20586        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20587
20588        synchronized (mPackages) {
20589            // Verify that all of the preferred activity components actually
20590            // exist.  It is possible for applications to be updated and at
20591            // that point remove a previously declared activity component that
20592            // had been set as a preferred activity.  We try to clean this up
20593            // the next time we encounter that preferred activity, but it is
20594            // possible for the user flow to never be able to return to that
20595            // situation so here we do a sanity check to make sure we haven't
20596            // left any junk around.
20597            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20598            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20599                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20600                removed.clear();
20601                for (PreferredActivity pa : pir.filterSet()) {
20602                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20603                        removed.add(pa);
20604                    }
20605                }
20606                if (removed.size() > 0) {
20607                    for (int r=0; r<removed.size(); r++) {
20608                        PreferredActivity pa = removed.get(r);
20609                        Slog.w(TAG, "Removing dangling preferred activity: "
20610                                + pa.mPref.mComponent);
20611                        pir.removeFilter(pa);
20612                    }
20613                    mSettings.writePackageRestrictionsLPr(
20614                            mSettings.mPreferredActivities.keyAt(i));
20615                }
20616            }
20617
20618            for (int userId : UserManagerService.getInstance().getUserIds()) {
20619                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20620                    grantPermissionsUserIds = ArrayUtils.appendInt(
20621                            grantPermissionsUserIds, userId);
20622                }
20623            }
20624        }
20625        sUserManager.systemReady();
20626
20627        // If we upgraded grant all default permissions before kicking off.
20628        for (int userId : grantPermissionsUserIds) {
20629            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20630        }
20631
20632        // If we did not grant default permissions, we preload from this the
20633        // default permission exceptions lazily to ensure we don't hit the
20634        // disk on a new user creation.
20635        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20636            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20637        }
20638
20639        // Kick off any messages waiting for system ready
20640        if (mPostSystemReadyMessages != null) {
20641            for (Message msg : mPostSystemReadyMessages) {
20642                msg.sendToTarget();
20643            }
20644            mPostSystemReadyMessages = null;
20645        }
20646
20647        // Watch for external volumes that come and go over time
20648        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20649        storage.registerListener(mStorageListener);
20650
20651        mInstallerService.systemReady();
20652        mPackageDexOptimizer.systemReady();
20653
20654        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20655                StorageManagerInternal.class);
20656        StorageManagerInternal.addExternalStoragePolicy(
20657                new StorageManagerInternal.ExternalStorageMountPolicy() {
20658            @Override
20659            public int getMountMode(int uid, String packageName) {
20660                if (Process.isIsolated(uid)) {
20661                    return Zygote.MOUNT_EXTERNAL_NONE;
20662                }
20663                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20664                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20665                }
20666                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20667                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20668                }
20669                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20670                    return Zygote.MOUNT_EXTERNAL_READ;
20671                }
20672                return Zygote.MOUNT_EXTERNAL_WRITE;
20673            }
20674
20675            @Override
20676            public boolean hasExternalStorage(int uid, String packageName) {
20677                return true;
20678            }
20679        });
20680
20681        // Now that we're mostly running, clean up stale users and apps
20682        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20683        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20684
20685        if (mPrivappPermissionsViolations != null) {
20686            Slog.wtf(TAG,"Signature|privileged permissions not in "
20687                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20688            mPrivappPermissionsViolations = null;
20689        }
20690    }
20691
20692    public void waitForAppDataPrepared() {
20693        if (mPrepareAppDataFuture == null) {
20694            return;
20695        }
20696        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20697        mPrepareAppDataFuture = null;
20698    }
20699
20700    @Override
20701    public boolean isSafeMode() {
20702        return mSafeMode;
20703    }
20704
20705    @Override
20706    public boolean hasSystemUidErrors() {
20707        return mHasSystemUidErrors;
20708    }
20709
20710    static String arrayToString(int[] array) {
20711        StringBuffer buf = new StringBuffer(128);
20712        buf.append('[');
20713        if (array != null) {
20714            for (int i=0; i<array.length; i++) {
20715                if (i > 0) buf.append(", ");
20716                buf.append(array[i]);
20717            }
20718        }
20719        buf.append(']');
20720        return buf.toString();
20721    }
20722
20723    static class DumpState {
20724        public static final int DUMP_LIBS = 1 << 0;
20725        public static final int DUMP_FEATURES = 1 << 1;
20726        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20727        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20728        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20729        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20730        public static final int DUMP_PERMISSIONS = 1 << 6;
20731        public static final int DUMP_PACKAGES = 1 << 7;
20732        public static final int DUMP_SHARED_USERS = 1 << 8;
20733        public static final int DUMP_MESSAGES = 1 << 9;
20734        public static final int DUMP_PROVIDERS = 1 << 10;
20735        public static final int DUMP_VERIFIERS = 1 << 11;
20736        public static final int DUMP_PREFERRED = 1 << 12;
20737        public static final int DUMP_PREFERRED_XML = 1 << 13;
20738        public static final int DUMP_KEYSETS = 1 << 14;
20739        public static final int DUMP_VERSION = 1 << 15;
20740        public static final int DUMP_INSTALLS = 1 << 16;
20741        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20742        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20743        public static final int DUMP_FROZEN = 1 << 19;
20744        public static final int DUMP_DEXOPT = 1 << 20;
20745        public static final int DUMP_COMPILER_STATS = 1 << 21;
20746        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20747        public static final int DUMP_CHANGES = 1 << 23;
20748
20749        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20750
20751        private int mTypes;
20752
20753        private int mOptions;
20754
20755        private boolean mTitlePrinted;
20756
20757        private SharedUserSetting mSharedUser;
20758
20759        public boolean isDumping(int type) {
20760            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20761                return true;
20762            }
20763
20764            return (mTypes & type) != 0;
20765        }
20766
20767        public void setDump(int type) {
20768            mTypes |= type;
20769        }
20770
20771        public boolean isOptionEnabled(int option) {
20772            return (mOptions & option) != 0;
20773        }
20774
20775        public void setOptionEnabled(int option) {
20776            mOptions |= option;
20777        }
20778
20779        public boolean onTitlePrinted() {
20780            final boolean printed = mTitlePrinted;
20781            mTitlePrinted = true;
20782            return printed;
20783        }
20784
20785        public boolean getTitlePrinted() {
20786            return mTitlePrinted;
20787        }
20788
20789        public void setTitlePrinted(boolean enabled) {
20790            mTitlePrinted = enabled;
20791        }
20792
20793        public SharedUserSetting getSharedUser() {
20794            return mSharedUser;
20795        }
20796
20797        public void setSharedUser(SharedUserSetting user) {
20798            mSharedUser = user;
20799        }
20800    }
20801
20802    @Override
20803    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20804            FileDescriptor err, String[] args, ShellCallback callback,
20805            ResultReceiver resultReceiver) {
20806        (new PackageManagerShellCommand(this)).exec(
20807                this, in, out, err, args, callback, resultReceiver);
20808    }
20809
20810    @Override
20811    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20812        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20813
20814        DumpState dumpState = new DumpState();
20815        boolean fullPreferred = false;
20816        boolean checkin = false;
20817
20818        String packageName = null;
20819        ArraySet<String> permissionNames = null;
20820
20821        int opti = 0;
20822        while (opti < args.length) {
20823            String opt = args[opti];
20824            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20825                break;
20826            }
20827            opti++;
20828
20829            if ("-a".equals(opt)) {
20830                // Right now we only know how to print all.
20831            } else if ("-h".equals(opt)) {
20832                pw.println("Package manager dump options:");
20833                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20834                pw.println("    --checkin: dump for a checkin");
20835                pw.println("    -f: print details of intent filters");
20836                pw.println("    -h: print this help");
20837                pw.println("  cmd may be one of:");
20838                pw.println("    l[ibraries]: list known shared libraries");
20839                pw.println("    f[eatures]: list device features");
20840                pw.println("    k[eysets]: print known keysets");
20841                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20842                pw.println("    perm[issions]: dump permissions");
20843                pw.println("    permission [name ...]: dump declaration and use of given permission");
20844                pw.println("    pref[erred]: print preferred package settings");
20845                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20846                pw.println("    prov[iders]: dump content providers");
20847                pw.println("    p[ackages]: dump installed packages");
20848                pw.println("    s[hared-users]: dump shared user IDs");
20849                pw.println("    m[essages]: print collected runtime messages");
20850                pw.println("    v[erifiers]: print package verifier info");
20851                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20852                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20853                pw.println("    version: print database version info");
20854                pw.println("    write: write current settings now");
20855                pw.println("    installs: details about install sessions");
20856                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20857                pw.println("    dexopt: dump dexopt state");
20858                pw.println("    compiler-stats: dump compiler statistics");
20859                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20860                pw.println("    <package.name>: info about given package");
20861                return;
20862            } else if ("--checkin".equals(opt)) {
20863                checkin = true;
20864            } else if ("-f".equals(opt)) {
20865                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20866            } else if ("--proto".equals(opt)) {
20867                dumpProto(fd);
20868                return;
20869            } else {
20870                pw.println("Unknown argument: " + opt + "; use -h for help");
20871            }
20872        }
20873
20874        // Is the caller requesting to dump a particular piece of data?
20875        if (opti < args.length) {
20876            String cmd = args[opti];
20877            opti++;
20878            // Is this a package name?
20879            if ("android".equals(cmd) || cmd.contains(".")) {
20880                packageName = cmd;
20881                // When dumping a single package, we always dump all of its
20882                // filter information since the amount of data will be reasonable.
20883                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20884            } else if ("check-permission".equals(cmd)) {
20885                if (opti >= args.length) {
20886                    pw.println("Error: check-permission missing permission argument");
20887                    return;
20888                }
20889                String perm = args[opti];
20890                opti++;
20891                if (opti >= args.length) {
20892                    pw.println("Error: check-permission missing package argument");
20893                    return;
20894                }
20895
20896                String pkg = args[opti];
20897                opti++;
20898                int user = UserHandle.getUserId(Binder.getCallingUid());
20899                if (opti < args.length) {
20900                    try {
20901                        user = Integer.parseInt(args[opti]);
20902                    } catch (NumberFormatException e) {
20903                        pw.println("Error: check-permission user argument is not a number: "
20904                                + args[opti]);
20905                        return;
20906                    }
20907                }
20908
20909                // Normalize package name to handle renamed packages and static libs
20910                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20911
20912                pw.println(checkPermission(perm, pkg, user));
20913                return;
20914            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20915                dumpState.setDump(DumpState.DUMP_LIBS);
20916            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20917                dumpState.setDump(DumpState.DUMP_FEATURES);
20918            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20919                if (opti >= args.length) {
20920                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20921                            | DumpState.DUMP_SERVICE_RESOLVERS
20922                            | DumpState.DUMP_RECEIVER_RESOLVERS
20923                            | DumpState.DUMP_CONTENT_RESOLVERS);
20924                } else {
20925                    while (opti < args.length) {
20926                        String name = args[opti];
20927                        if ("a".equals(name) || "activity".equals(name)) {
20928                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20929                        } else if ("s".equals(name) || "service".equals(name)) {
20930                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20931                        } else if ("r".equals(name) || "receiver".equals(name)) {
20932                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20933                        } else if ("c".equals(name) || "content".equals(name)) {
20934                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20935                        } else {
20936                            pw.println("Error: unknown resolver table type: " + name);
20937                            return;
20938                        }
20939                        opti++;
20940                    }
20941                }
20942            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20943                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20944            } else if ("permission".equals(cmd)) {
20945                if (opti >= args.length) {
20946                    pw.println("Error: permission requires permission name");
20947                    return;
20948                }
20949                permissionNames = new ArraySet<>();
20950                while (opti < args.length) {
20951                    permissionNames.add(args[opti]);
20952                    opti++;
20953                }
20954                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20955                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20956            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20957                dumpState.setDump(DumpState.DUMP_PREFERRED);
20958            } else if ("preferred-xml".equals(cmd)) {
20959                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20960                if (opti < args.length && "--full".equals(args[opti])) {
20961                    fullPreferred = true;
20962                    opti++;
20963                }
20964            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20965                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20966            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20967                dumpState.setDump(DumpState.DUMP_PACKAGES);
20968            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20969                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20970            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20971                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20972            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20973                dumpState.setDump(DumpState.DUMP_MESSAGES);
20974            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20975                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20976            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20977                    || "intent-filter-verifiers".equals(cmd)) {
20978                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20979            } else if ("version".equals(cmd)) {
20980                dumpState.setDump(DumpState.DUMP_VERSION);
20981            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20982                dumpState.setDump(DumpState.DUMP_KEYSETS);
20983            } else if ("installs".equals(cmd)) {
20984                dumpState.setDump(DumpState.DUMP_INSTALLS);
20985            } else if ("frozen".equals(cmd)) {
20986                dumpState.setDump(DumpState.DUMP_FROZEN);
20987            } else if ("dexopt".equals(cmd)) {
20988                dumpState.setDump(DumpState.DUMP_DEXOPT);
20989            } else if ("compiler-stats".equals(cmd)) {
20990                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20991            } else if ("enabled-overlays".equals(cmd)) {
20992                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20993            } else if ("changes".equals(cmd)) {
20994                dumpState.setDump(DumpState.DUMP_CHANGES);
20995            } else if ("write".equals(cmd)) {
20996                synchronized (mPackages) {
20997                    mSettings.writeLPr();
20998                    pw.println("Settings written.");
20999                    return;
21000                }
21001            }
21002        }
21003
21004        if (checkin) {
21005            pw.println("vers,1");
21006        }
21007
21008        // reader
21009        synchronized (mPackages) {
21010            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21011                if (!checkin) {
21012                    if (dumpState.onTitlePrinted())
21013                        pw.println();
21014                    pw.println("Database versions:");
21015                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21016                }
21017            }
21018
21019            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21020                if (!checkin) {
21021                    if (dumpState.onTitlePrinted())
21022                        pw.println();
21023                    pw.println("Verifiers:");
21024                    pw.print("  Required: ");
21025                    pw.print(mRequiredVerifierPackage);
21026                    pw.print(" (uid=");
21027                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21028                            UserHandle.USER_SYSTEM));
21029                    pw.println(")");
21030                } else if (mRequiredVerifierPackage != null) {
21031                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21032                    pw.print(",");
21033                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21034                            UserHandle.USER_SYSTEM));
21035                }
21036            }
21037
21038            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21039                    packageName == null) {
21040                if (mIntentFilterVerifierComponent != null) {
21041                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21042                    if (!checkin) {
21043                        if (dumpState.onTitlePrinted())
21044                            pw.println();
21045                        pw.println("Intent Filter Verifier:");
21046                        pw.print("  Using: ");
21047                        pw.print(verifierPackageName);
21048                        pw.print(" (uid=");
21049                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21050                                UserHandle.USER_SYSTEM));
21051                        pw.println(")");
21052                    } else if (verifierPackageName != null) {
21053                        pw.print("ifv,"); pw.print(verifierPackageName);
21054                        pw.print(",");
21055                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21056                                UserHandle.USER_SYSTEM));
21057                    }
21058                } else {
21059                    pw.println();
21060                    pw.println("No Intent Filter Verifier available!");
21061                }
21062            }
21063
21064            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21065                boolean printedHeader = false;
21066                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21067                while (it.hasNext()) {
21068                    String libName = it.next();
21069                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21070                    if (versionedLib == null) {
21071                        continue;
21072                    }
21073                    final int versionCount = versionedLib.size();
21074                    for (int i = 0; i < versionCount; i++) {
21075                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21076                        if (!checkin) {
21077                            if (!printedHeader) {
21078                                if (dumpState.onTitlePrinted())
21079                                    pw.println();
21080                                pw.println("Libraries:");
21081                                printedHeader = true;
21082                            }
21083                            pw.print("  ");
21084                        } else {
21085                            pw.print("lib,");
21086                        }
21087                        pw.print(libEntry.info.getName());
21088                        if (libEntry.info.isStatic()) {
21089                            pw.print(" version=" + libEntry.info.getVersion());
21090                        }
21091                        if (!checkin) {
21092                            pw.print(" -> ");
21093                        }
21094                        if (libEntry.path != null) {
21095                            pw.print(" (jar) ");
21096                            pw.print(libEntry.path);
21097                        } else {
21098                            pw.print(" (apk) ");
21099                            pw.print(libEntry.apk);
21100                        }
21101                        pw.println();
21102                    }
21103                }
21104            }
21105
21106            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21107                if (dumpState.onTitlePrinted())
21108                    pw.println();
21109                if (!checkin) {
21110                    pw.println("Features:");
21111                }
21112
21113                synchronized (mAvailableFeatures) {
21114                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21115                        if (checkin) {
21116                            pw.print("feat,");
21117                            pw.print(feat.name);
21118                            pw.print(",");
21119                            pw.println(feat.version);
21120                        } else {
21121                            pw.print("  ");
21122                            pw.print(feat.name);
21123                            if (feat.version > 0) {
21124                                pw.print(" version=");
21125                                pw.print(feat.version);
21126                            }
21127                            pw.println();
21128                        }
21129                    }
21130                }
21131            }
21132
21133            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21134                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21135                        : "Activity Resolver Table:", "  ", packageName,
21136                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21137                    dumpState.setTitlePrinted(true);
21138                }
21139            }
21140            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21141                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21142                        : "Receiver Resolver Table:", "  ", packageName,
21143                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21144                    dumpState.setTitlePrinted(true);
21145                }
21146            }
21147            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21148                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21149                        : "Service Resolver Table:", "  ", packageName,
21150                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21151                    dumpState.setTitlePrinted(true);
21152                }
21153            }
21154            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21155                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21156                        : "Provider Resolver Table:", "  ", packageName,
21157                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21158                    dumpState.setTitlePrinted(true);
21159                }
21160            }
21161
21162            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21163                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21164                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21165                    int user = mSettings.mPreferredActivities.keyAt(i);
21166                    if (pir.dump(pw,
21167                            dumpState.getTitlePrinted()
21168                                ? "\nPreferred Activities User " + user + ":"
21169                                : "Preferred Activities User " + user + ":", "  ",
21170                            packageName, true, false)) {
21171                        dumpState.setTitlePrinted(true);
21172                    }
21173                }
21174            }
21175
21176            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21177                pw.flush();
21178                FileOutputStream fout = new FileOutputStream(fd);
21179                BufferedOutputStream str = new BufferedOutputStream(fout);
21180                XmlSerializer serializer = new FastXmlSerializer();
21181                try {
21182                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21183                    serializer.startDocument(null, true);
21184                    serializer.setFeature(
21185                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21186                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21187                    serializer.endDocument();
21188                    serializer.flush();
21189                } catch (IllegalArgumentException e) {
21190                    pw.println("Failed writing: " + e);
21191                } catch (IllegalStateException e) {
21192                    pw.println("Failed writing: " + e);
21193                } catch (IOException e) {
21194                    pw.println("Failed writing: " + e);
21195                }
21196            }
21197
21198            if (!checkin
21199                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21200                    && packageName == null) {
21201                pw.println();
21202                int count = mSettings.mPackages.size();
21203                if (count == 0) {
21204                    pw.println("No applications!");
21205                    pw.println();
21206                } else {
21207                    final String prefix = "  ";
21208                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21209                    if (allPackageSettings.size() == 0) {
21210                        pw.println("No domain preferred apps!");
21211                        pw.println();
21212                    } else {
21213                        pw.println("App verification status:");
21214                        pw.println();
21215                        count = 0;
21216                        for (PackageSetting ps : allPackageSettings) {
21217                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21218                            if (ivi == null || ivi.getPackageName() == null) continue;
21219                            pw.println(prefix + "Package: " + ivi.getPackageName());
21220                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21221                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21222                            pw.println();
21223                            count++;
21224                        }
21225                        if (count == 0) {
21226                            pw.println(prefix + "No app verification established.");
21227                            pw.println();
21228                        }
21229                        for (int userId : sUserManager.getUserIds()) {
21230                            pw.println("App linkages for user " + userId + ":");
21231                            pw.println();
21232                            count = 0;
21233                            for (PackageSetting ps : allPackageSettings) {
21234                                final long status = ps.getDomainVerificationStatusForUser(userId);
21235                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21236                                        && !DEBUG_DOMAIN_VERIFICATION) {
21237                                    continue;
21238                                }
21239                                pw.println(prefix + "Package: " + ps.name);
21240                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21241                                String statusStr = IntentFilterVerificationInfo.
21242                                        getStatusStringFromValue(status);
21243                                pw.println(prefix + "Status:  " + statusStr);
21244                                pw.println();
21245                                count++;
21246                            }
21247                            if (count == 0) {
21248                                pw.println(prefix + "No configured app linkages.");
21249                                pw.println();
21250                            }
21251                        }
21252                    }
21253                }
21254            }
21255
21256            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21257                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21258                if (packageName == null && permissionNames == null) {
21259                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21260                        if (iperm == 0) {
21261                            if (dumpState.onTitlePrinted())
21262                                pw.println();
21263                            pw.println("AppOp Permissions:");
21264                        }
21265                        pw.print("  AppOp Permission ");
21266                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21267                        pw.println(":");
21268                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21269                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21270                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21271                        }
21272                    }
21273                }
21274            }
21275
21276            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21277                boolean printedSomething = false;
21278                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21279                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21280                        continue;
21281                    }
21282                    if (!printedSomething) {
21283                        if (dumpState.onTitlePrinted())
21284                            pw.println();
21285                        pw.println("Registered ContentProviders:");
21286                        printedSomething = true;
21287                    }
21288                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21289                    pw.print("    "); pw.println(p.toString());
21290                }
21291                printedSomething = false;
21292                for (Map.Entry<String, PackageParser.Provider> entry :
21293                        mProvidersByAuthority.entrySet()) {
21294                    PackageParser.Provider p = entry.getValue();
21295                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21296                        continue;
21297                    }
21298                    if (!printedSomething) {
21299                        if (dumpState.onTitlePrinted())
21300                            pw.println();
21301                        pw.println("ContentProvider Authorities:");
21302                        printedSomething = true;
21303                    }
21304                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21305                    pw.print("    "); pw.println(p.toString());
21306                    if (p.info != null && p.info.applicationInfo != null) {
21307                        final String appInfo = p.info.applicationInfo.toString();
21308                        pw.print("      applicationInfo="); pw.println(appInfo);
21309                    }
21310                }
21311            }
21312
21313            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21314                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21315            }
21316
21317            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21318                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21319            }
21320
21321            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21322                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21323            }
21324
21325            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21326                if (dumpState.onTitlePrinted()) pw.println();
21327                pw.println("Package Changes:");
21328                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21329                final int K = mChangedPackages.size();
21330                for (int i = 0; i < K; i++) {
21331                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21332                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21333                    final int N = changes.size();
21334                    if (N == 0) {
21335                        pw.print("    "); pw.println("No packages changed");
21336                    } else {
21337                        for (int j = 0; j < N; j++) {
21338                            final String pkgName = changes.valueAt(j);
21339                            final int sequenceNumber = changes.keyAt(j);
21340                            pw.print("    ");
21341                            pw.print("seq=");
21342                            pw.print(sequenceNumber);
21343                            pw.print(", package=");
21344                            pw.println(pkgName);
21345                        }
21346                    }
21347                }
21348            }
21349
21350            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21351                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21352            }
21353
21354            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21355                // XXX should handle packageName != null by dumping only install data that
21356                // the given package is involved with.
21357                if (dumpState.onTitlePrinted()) pw.println();
21358
21359                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21360                ipw.println();
21361                ipw.println("Frozen packages:");
21362                ipw.increaseIndent();
21363                if (mFrozenPackages.size() == 0) {
21364                    ipw.println("(none)");
21365                } else {
21366                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21367                        ipw.println(mFrozenPackages.valueAt(i));
21368                    }
21369                }
21370                ipw.decreaseIndent();
21371            }
21372
21373            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21374                if (dumpState.onTitlePrinted()) pw.println();
21375                dumpDexoptStateLPr(pw, packageName);
21376            }
21377
21378            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21379                if (dumpState.onTitlePrinted()) pw.println();
21380                dumpCompilerStatsLPr(pw, packageName);
21381            }
21382
21383            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21384                if (dumpState.onTitlePrinted()) pw.println();
21385                dumpEnabledOverlaysLPr(pw);
21386            }
21387
21388            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21389                if (dumpState.onTitlePrinted()) pw.println();
21390                mSettings.dumpReadMessagesLPr(pw, dumpState);
21391
21392                pw.println();
21393                pw.println("Package warning messages:");
21394                BufferedReader in = null;
21395                String line = null;
21396                try {
21397                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21398                    while ((line = in.readLine()) != null) {
21399                        if (line.contains("ignored: updated version")) continue;
21400                        pw.println(line);
21401                    }
21402                } catch (IOException ignored) {
21403                } finally {
21404                    IoUtils.closeQuietly(in);
21405                }
21406            }
21407
21408            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21409                BufferedReader in = null;
21410                String line = null;
21411                try {
21412                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21413                    while ((line = in.readLine()) != null) {
21414                        if (line.contains("ignored: updated version")) continue;
21415                        pw.print("msg,");
21416                        pw.println(line);
21417                    }
21418                } catch (IOException ignored) {
21419                } finally {
21420                    IoUtils.closeQuietly(in);
21421                }
21422            }
21423        }
21424
21425        // PackageInstaller should be called outside of mPackages lock
21426        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21427            // XXX should handle packageName != null by dumping only install data that
21428            // the given package is involved with.
21429            if (dumpState.onTitlePrinted()) pw.println();
21430            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21431        }
21432    }
21433
21434    private void dumpProto(FileDescriptor fd) {
21435        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21436
21437        synchronized (mPackages) {
21438            final long requiredVerifierPackageToken =
21439                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21440            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21441            proto.write(
21442                    PackageServiceDumpProto.PackageShortProto.UID,
21443                    getPackageUid(
21444                            mRequiredVerifierPackage,
21445                            MATCH_DEBUG_TRIAGED_MISSING,
21446                            UserHandle.USER_SYSTEM));
21447            proto.end(requiredVerifierPackageToken);
21448
21449            if (mIntentFilterVerifierComponent != null) {
21450                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21451                final long verifierPackageToken =
21452                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21453                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21454                proto.write(
21455                        PackageServiceDumpProto.PackageShortProto.UID,
21456                        getPackageUid(
21457                                verifierPackageName,
21458                                MATCH_DEBUG_TRIAGED_MISSING,
21459                                UserHandle.USER_SYSTEM));
21460                proto.end(verifierPackageToken);
21461            }
21462
21463            dumpSharedLibrariesProto(proto);
21464            dumpFeaturesProto(proto);
21465            mSettings.dumpPackagesProto(proto);
21466            mSettings.dumpSharedUsersProto(proto);
21467            dumpMessagesProto(proto);
21468        }
21469        proto.flush();
21470    }
21471
21472    private void dumpMessagesProto(ProtoOutputStream proto) {
21473        BufferedReader in = null;
21474        String line = null;
21475        try {
21476            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21477            while ((line = in.readLine()) != null) {
21478                if (line.contains("ignored: updated version")) continue;
21479                proto.write(PackageServiceDumpProto.MESSAGES, line);
21480            }
21481        } catch (IOException ignored) {
21482        } finally {
21483            IoUtils.closeQuietly(in);
21484        }
21485    }
21486
21487    private void dumpFeaturesProto(ProtoOutputStream proto) {
21488        synchronized (mAvailableFeatures) {
21489            final int count = mAvailableFeatures.size();
21490            for (int i = 0; i < count; i++) {
21491                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21492                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21493                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21494                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21495                proto.end(featureToken);
21496            }
21497        }
21498    }
21499
21500    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21501        final int count = mSharedLibraries.size();
21502        for (int i = 0; i < count; i++) {
21503            final String libName = mSharedLibraries.keyAt(i);
21504            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21505            if (versionedLib == null) {
21506                continue;
21507            }
21508            final int versionCount = versionedLib.size();
21509            for (int j = 0; j < versionCount; j++) {
21510                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21511                final long sharedLibraryToken =
21512                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21513                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21514                final boolean isJar = (libEntry.path != null);
21515                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21516                if (isJar) {
21517                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21518                } else {
21519                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21520                }
21521                proto.end(sharedLibraryToken);
21522            }
21523        }
21524    }
21525
21526    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21527        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21528        ipw.println();
21529        ipw.println("Dexopt state:");
21530        ipw.increaseIndent();
21531        Collection<PackageParser.Package> packages = null;
21532        if (packageName != null) {
21533            PackageParser.Package targetPackage = mPackages.get(packageName);
21534            if (targetPackage != null) {
21535                packages = Collections.singletonList(targetPackage);
21536            } else {
21537                ipw.println("Unable to find package: " + packageName);
21538                return;
21539            }
21540        } else {
21541            packages = mPackages.values();
21542        }
21543
21544        for (PackageParser.Package pkg : packages) {
21545            ipw.println("[" + pkg.packageName + "]");
21546            ipw.increaseIndent();
21547            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21548            ipw.decreaseIndent();
21549        }
21550    }
21551
21552    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21553        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21554        ipw.println();
21555        ipw.println("Compiler stats:");
21556        ipw.increaseIndent();
21557        Collection<PackageParser.Package> packages = null;
21558        if (packageName != null) {
21559            PackageParser.Package targetPackage = mPackages.get(packageName);
21560            if (targetPackage != null) {
21561                packages = Collections.singletonList(targetPackage);
21562            } else {
21563                ipw.println("Unable to find package: " + packageName);
21564                return;
21565            }
21566        } else {
21567            packages = mPackages.values();
21568        }
21569
21570        for (PackageParser.Package pkg : packages) {
21571            ipw.println("[" + pkg.packageName + "]");
21572            ipw.increaseIndent();
21573
21574            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21575            if (stats == null) {
21576                ipw.println("(No recorded stats)");
21577            } else {
21578                stats.dump(ipw);
21579            }
21580            ipw.decreaseIndent();
21581        }
21582    }
21583
21584    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21585        pw.println("Enabled overlay paths:");
21586        final int N = mEnabledOverlayPaths.size();
21587        for (int i = 0; i < N; i++) {
21588            final int userId = mEnabledOverlayPaths.keyAt(i);
21589            pw.println(String.format("    User %d:", userId));
21590            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21591                mEnabledOverlayPaths.valueAt(i);
21592            final int M = userSpecificOverlays.size();
21593            for (int j = 0; j < M; j++) {
21594                final String targetPackageName = userSpecificOverlays.keyAt(j);
21595                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21596                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21597            }
21598        }
21599    }
21600
21601    private String dumpDomainString(String packageName) {
21602        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21603                .getList();
21604        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21605
21606        ArraySet<String> result = new ArraySet<>();
21607        if (iviList.size() > 0) {
21608            for (IntentFilterVerificationInfo ivi : iviList) {
21609                for (String host : ivi.getDomains()) {
21610                    result.add(host);
21611                }
21612            }
21613        }
21614        if (filters != null && filters.size() > 0) {
21615            for (IntentFilter filter : filters) {
21616                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21617                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21618                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21619                    result.addAll(filter.getHostsList());
21620                }
21621            }
21622        }
21623
21624        StringBuilder sb = new StringBuilder(result.size() * 16);
21625        for (String domain : result) {
21626            if (sb.length() > 0) sb.append(" ");
21627            sb.append(domain);
21628        }
21629        return sb.toString();
21630    }
21631
21632    // ------- apps on sdcard specific code -------
21633    static final boolean DEBUG_SD_INSTALL = false;
21634
21635    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21636
21637    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21638
21639    private boolean mMediaMounted = false;
21640
21641    static String getEncryptKey() {
21642        try {
21643            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21644                    SD_ENCRYPTION_KEYSTORE_NAME);
21645            if (sdEncKey == null) {
21646                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21647                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21648                if (sdEncKey == null) {
21649                    Slog.e(TAG, "Failed to create encryption keys");
21650                    return null;
21651                }
21652            }
21653            return sdEncKey;
21654        } catch (NoSuchAlgorithmException nsae) {
21655            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21656            return null;
21657        } catch (IOException ioe) {
21658            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21659            return null;
21660        }
21661    }
21662
21663    /*
21664     * Update media status on PackageManager.
21665     */
21666    @Override
21667    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21668        int callingUid = Binder.getCallingUid();
21669        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21670            throw new SecurityException("Media status can only be updated by the system");
21671        }
21672        // reader; this apparently protects mMediaMounted, but should probably
21673        // be a different lock in that case.
21674        synchronized (mPackages) {
21675            Log.i(TAG, "Updating external media status from "
21676                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21677                    + (mediaStatus ? "mounted" : "unmounted"));
21678            if (DEBUG_SD_INSTALL)
21679                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21680                        + ", mMediaMounted=" + mMediaMounted);
21681            if (mediaStatus == mMediaMounted) {
21682                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21683                        : 0, -1);
21684                mHandler.sendMessage(msg);
21685                return;
21686            }
21687            mMediaMounted = mediaStatus;
21688        }
21689        // Queue up an async operation since the package installation may take a
21690        // little while.
21691        mHandler.post(new Runnable() {
21692            public void run() {
21693                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21694            }
21695        });
21696    }
21697
21698    /**
21699     * Called by StorageManagerService when the initial ASECs to scan are available.
21700     * Should block until all the ASEC containers are finished being scanned.
21701     */
21702    public void scanAvailableAsecs() {
21703        updateExternalMediaStatusInner(true, false, false);
21704    }
21705
21706    /*
21707     * Collect information of applications on external media, map them against
21708     * existing containers and update information based on current mount status.
21709     * Please note that we always have to report status if reportStatus has been
21710     * set to true especially when unloading packages.
21711     */
21712    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21713            boolean externalStorage) {
21714        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21715        int[] uidArr = EmptyArray.INT;
21716
21717        final String[] list = PackageHelper.getSecureContainerList();
21718        if (ArrayUtils.isEmpty(list)) {
21719            Log.i(TAG, "No secure containers found");
21720        } else {
21721            // Process list of secure containers and categorize them
21722            // as active or stale based on their package internal state.
21723
21724            // reader
21725            synchronized (mPackages) {
21726                for (String cid : list) {
21727                    // Leave stages untouched for now; installer service owns them
21728                    if (PackageInstallerService.isStageName(cid)) continue;
21729
21730                    if (DEBUG_SD_INSTALL)
21731                        Log.i(TAG, "Processing container " + cid);
21732                    String pkgName = getAsecPackageName(cid);
21733                    if (pkgName == null) {
21734                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21735                        continue;
21736                    }
21737                    if (DEBUG_SD_INSTALL)
21738                        Log.i(TAG, "Looking for pkg : " + pkgName);
21739
21740                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21741                    if (ps == null) {
21742                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21743                        continue;
21744                    }
21745
21746                    /*
21747                     * Skip packages that are not external if we're unmounting
21748                     * external storage.
21749                     */
21750                    if (externalStorage && !isMounted && !isExternal(ps)) {
21751                        continue;
21752                    }
21753
21754                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21755                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21756                    // The package status is changed only if the code path
21757                    // matches between settings and the container id.
21758                    if (ps.codePathString != null
21759                            && ps.codePathString.startsWith(args.getCodePath())) {
21760                        if (DEBUG_SD_INSTALL) {
21761                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21762                                    + " at code path: " + ps.codePathString);
21763                        }
21764
21765                        // We do have a valid package installed on sdcard
21766                        processCids.put(args, ps.codePathString);
21767                        final int uid = ps.appId;
21768                        if (uid != -1) {
21769                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21770                        }
21771                    } else {
21772                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21773                                + ps.codePathString);
21774                    }
21775                }
21776            }
21777
21778            Arrays.sort(uidArr);
21779        }
21780
21781        // Process packages with valid entries.
21782        if (isMounted) {
21783            if (DEBUG_SD_INSTALL)
21784                Log.i(TAG, "Loading packages");
21785            loadMediaPackages(processCids, uidArr, externalStorage);
21786            startCleaningPackages();
21787            mInstallerService.onSecureContainersAvailable();
21788        } else {
21789            if (DEBUG_SD_INSTALL)
21790                Log.i(TAG, "Unloading packages");
21791            unloadMediaPackages(processCids, uidArr, reportStatus);
21792        }
21793    }
21794
21795    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21796            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21797        final int size = infos.size();
21798        final String[] packageNames = new String[size];
21799        final int[] packageUids = new int[size];
21800        for (int i = 0; i < size; i++) {
21801            final ApplicationInfo info = infos.get(i);
21802            packageNames[i] = info.packageName;
21803            packageUids[i] = info.uid;
21804        }
21805        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21806                finishedReceiver);
21807    }
21808
21809    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21810            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21811        sendResourcesChangedBroadcast(mediaStatus, replacing,
21812                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21813    }
21814
21815    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21816            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21817        int size = pkgList.length;
21818        if (size > 0) {
21819            // Send broadcasts here
21820            Bundle extras = new Bundle();
21821            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21822            if (uidArr != null) {
21823                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21824            }
21825            if (replacing) {
21826                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21827            }
21828            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21829                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21830            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21831        }
21832    }
21833
21834   /*
21835     * Look at potentially valid container ids from processCids If package
21836     * information doesn't match the one on record or package scanning fails,
21837     * the cid is added to list of removeCids. We currently don't delete stale
21838     * containers.
21839     */
21840    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21841            boolean externalStorage) {
21842        ArrayList<String> pkgList = new ArrayList<String>();
21843        Set<AsecInstallArgs> keys = processCids.keySet();
21844
21845        for (AsecInstallArgs args : keys) {
21846            String codePath = processCids.get(args);
21847            if (DEBUG_SD_INSTALL)
21848                Log.i(TAG, "Loading container : " + args.cid);
21849            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21850            try {
21851                // Make sure there are no container errors first.
21852                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21853                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21854                            + " when installing from sdcard");
21855                    continue;
21856                }
21857                // Check code path here.
21858                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21859                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21860                            + " does not match one in settings " + codePath);
21861                    continue;
21862                }
21863                // Parse package
21864                int parseFlags = mDefParseFlags;
21865                if (args.isExternalAsec()) {
21866                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21867                }
21868                if (args.isFwdLocked()) {
21869                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21870                }
21871
21872                synchronized (mInstallLock) {
21873                    PackageParser.Package pkg = null;
21874                    try {
21875                        // Sadly we don't know the package name yet to freeze it
21876                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21877                                SCAN_IGNORE_FROZEN, 0, null);
21878                    } catch (PackageManagerException e) {
21879                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21880                    }
21881                    // Scan the package
21882                    if (pkg != null) {
21883                        /*
21884                         * TODO why is the lock being held? doPostInstall is
21885                         * called in other places without the lock. This needs
21886                         * to be straightened out.
21887                         */
21888                        // writer
21889                        synchronized (mPackages) {
21890                            retCode = PackageManager.INSTALL_SUCCEEDED;
21891                            pkgList.add(pkg.packageName);
21892                            // Post process args
21893                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21894                                    pkg.applicationInfo.uid);
21895                        }
21896                    } else {
21897                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21898                    }
21899                }
21900
21901            } finally {
21902                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21903                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21904                }
21905            }
21906        }
21907        // writer
21908        synchronized (mPackages) {
21909            // If the platform SDK has changed since the last time we booted,
21910            // we need to re-grant app permission to catch any new ones that
21911            // appear. This is really a hack, and means that apps can in some
21912            // cases get permissions that the user didn't initially explicitly
21913            // allow... it would be nice to have some better way to handle
21914            // this situation.
21915            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21916                    : mSettings.getInternalVersion();
21917            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21918                    : StorageManager.UUID_PRIVATE_INTERNAL;
21919
21920            int updateFlags = UPDATE_PERMISSIONS_ALL;
21921            if (ver.sdkVersion != mSdkVersion) {
21922                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21923                        + mSdkVersion + "; regranting permissions for external");
21924                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21925            }
21926            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21927
21928            // Yay, everything is now upgraded
21929            ver.forceCurrent();
21930
21931            // can downgrade to reader
21932            // Persist settings
21933            mSettings.writeLPr();
21934        }
21935        // Send a broadcast to let everyone know we are done processing
21936        if (pkgList.size() > 0) {
21937            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21938        }
21939    }
21940
21941   /*
21942     * Utility method to unload a list of specified containers
21943     */
21944    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21945        // Just unmount all valid containers.
21946        for (AsecInstallArgs arg : cidArgs) {
21947            synchronized (mInstallLock) {
21948                arg.doPostDeleteLI(false);
21949           }
21950       }
21951   }
21952
21953    /*
21954     * Unload packages mounted on external media. This involves deleting package
21955     * data from internal structures, sending broadcasts about disabled packages,
21956     * gc'ing to free up references, unmounting all secure containers
21957     * corresponding to packages on external media, and posting a
21958     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21959     * that we always have to post this message if status has been requested no
21960     * matter what.
21961     */
21962    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21963            final boolean reportStatus) {
21964        if (DEBUG_SD_INSTALL)
21965            Log.i(TAG, "unloading media packages");
21966        ArrayList<String> pkgList = new ArrayList<String>();
21967        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21968        final Set<AsecInstallArgs> keys = processCids.keySet();
21969        for (AsecInstallArgs args : keys) {
21970            String pkgName = args.getPackageName();
21971            if (DEBUG_SD_INSTALL)
21972                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21973            // Delete package internally
21974            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21975            synchronized (mInstallLock) {
21976                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21977                final boolean res;
21978                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21979                        "unloadMediaPackages")) {
21980                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21981                            null);
21982                }
21983                if (res) {
21984                    pkgList.add(pkgName);
21985                } else {
21986                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21987                    failedList.add(args);
21988                }
21989            }
21990        }
21991
21992        // reader
21993        synchronized (mPackages) {
21994            // We didn't update the settings after removing each package;
21995            // write them now for all packages.
21996            mSettings.writeLPr();
21997        }
21998
21999        // We have to absolutely send UPDATED_MEDIA_STATUS only
22000        // after confirming that all the receivers processed the ordered
22001        // broadcast when packages get disabled, force a gc to clean things up.
22002        // and unload all the containers.
22003        if (pkgList.size() > 0) {
22004            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22005                    new IIntentReceiver.Stub() {
22006                public void performReceive(Intent intent, int resultCode, String data,
22007                        Bundle extras, boolean ordered, boolean sticky,
22008                        int sendingUser) throws RemoteException {
22009                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22010                            reportStatus ? 1 : 0, 1, keys);
22011                    mHandler.sendMessage(msg);
22012                }
22013            });
22014        } else {
22015            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22016                    keys);
22017            mHandler.sendMessage(msg);
22018        }
22019    }
22020
22021    private void loadPrivatePackages(final VolumeInfo vol) {
22022        mHandler.post(new Runnable() {
22023            @Override
22024            public void run() {
22025                loadPrivatePackagesInner(vol);
22026            }
22027        });
22028    }
22029
22030    private void loadPrivatePackagesInner(VolumeInfo vol) {
22031        final String volumeUuid = vol.fsUuid;
22032        if (TextUtils.isEmpty(volumeUuid)) {
22033            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22034            return;
22035        }
22036
22037        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22038        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22039        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22040
22041        final VersionInfo ver;
22042        final List<PackageSetting> packages;
22043        synchronized (mPackages) {
22044            ver = mSettings.findOrCreateVersion(volumeUuid);
22045            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22046        }
22047
22048        for (PackageSetting ps : packages) {
22049            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22050            synchronized (mInstallLock) {
22051                final PackageParser.Package pkg;
22052                try {
22053                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22054                    loaded.add(pkg.applicationInfo);
22055
22056                } catch (PackageManagerException e) {
22057                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22058                }
22059
22060                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22061                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22062                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22063                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22064                }
22065            }
22066        }
22067
22068        // Reconcile app data for all started/unlocked users
22069        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22070        final UserManager um = mContext.getSystemService(UserManager.class);
22071        UserManagerInternal umInternal = getUserManagerInternal();
22072        for (UserInfo user : um.getUsers()) {
22073            final int flags;
22074            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22075                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22076            } else if (umInternal.isUserRunning(user.id)) {
22077                flags = StorageManager.FLAG_STORAGE_DE;
22078            } else {
22079                continue;
22080            }
22081
22082            try {
22083                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22084                synchronized (mInstallLock) {
22085                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22086                }
22087            } catch (IllegalStateException e) {
22088                // Device was probably ejected, and we'll process that event momentarily
22089                Slog.w(TAG, "Failed to prepare storage: " + e);
22090            }
22091        }
22092
22093        synchronized (mPackages) {
22094            int updateFlags = UPDATE_PERMISSIONS_ALL;
22095            if (ver.sdkVersion != mSdkVersion) {
22096                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22097                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22098                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22099            }
22100            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22101
22102            // Yay, everything is now upgraded
22103            ver.forceCurrent();
22104
22105            mSettings.writeLPr();
22106        }
22107
22108        for (PackageFreezer freezer : freezers) {
22109            freezer.close();
22110        }
22111
22112        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22113        sendResourcesChangedBroadcast(true, false, loaded, null);
22114    }
22115
22116    private void unloadPrivatePackages(final VolumeInfo vol) {
22117        mHandler.post(new Runnable() {
22118            @Override
22119            public void run() {
22120                unloadPrivatePackagesInner(vol);
22121            }
22122        });
22123    }
22124
22125    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22126        final String volumeUuid = vol.fsUuid;
22127        if (TextUtils.isEmpty(volumeUuid)) {
22128            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22129            return;
22130        }
22131
22132        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22133        synchronized (mInstallLock) {
22134        synchronized (mPackages) {
22135            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22136            for (PackageSetting ps : packages) {
22137                if (ps.pkg == null) continue;
22138
22139                final ApplicationInfo info = ps.pkg.applicationInfo;
22140                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22141                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22142
22143                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22144                        "unloadPrivatePackagesInner")) {
22145                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22146                            false, null)) {
22147                        unloaded.add(info);
22148                    } else {
22149                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22150                    }
22151                }
22152
22153                // Try very hard to release any references to this package
22154                // so we don't risk the system server being killed due to
22155                // open FDs
22156                AttributeCache.instance().removePackage(ps.name);
22157            }
22158
22159            mSettings.writeLPr();
22160        }
22161        }
22162
22163        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22164        sendResourcesChangedBroadcast(false, false, unloaded, null);
22165
22166        // Try very hard to release any references to this path so we don't risk
22167        // the system server being killed due to open FDs
22168        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22169
22170        for (int i = 0; i < 3; i++) {
22171            System.gc();
22172            System.runFinalization();
22173        }
22174    }
22175
22176    private void assertPackageKnown(String volumeUuid, String packageName)
22177            throws PackageManagerException {
22178        synchronized (mPackages) {
22179            // Normalize package name to handle renamed packages
22180            packageName = normalizePackageNameLPr(packageName);
22181
22182            final PackageSetting ps = mSettings.mPackages.get(packageName);
22183            if (ps == null) {
22184                throw new PackageManagerException("Package " + packageName + " is unknown");
22185            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22186                throw new PackageManagerException(
22187                        "Package " + packageName + " found on unknown volume " + volumeUuid
22188                                + "; expected volume " + ps.volumeUuid);
22189            }
22190        }
22191    }
22192
22193    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22194            throws PackageManagerException {
22195        synchronized (mPackages) {
22196            // Normalize package name to handle renamed packages
22197            packageName = normalizePackageNameLPr(packageName);
22198
22199            final PackageSetting ps = mSettings.mPackages.get(packageName);
22200            if (ps == null) {
22201                throw new PackageManagerException("Package " + packageName + " is unknown");
22202            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22203                throw new PackageManagerException(
22204                        "Package " + packageName + " found on unknown volume " + volumeUuid
22205                                + "; expected volume " + ps.volumeUuid);
22206            } else if (!ps.getInstalled(userId)) {
22207                throw new PackageManagerException(
22208                        "Package " + packageName + " not installed for user " + userId);
22209            }
22210        }
22211    }
22212
22213    private List<String> collectAbsoluteCodePaths() {
22214        synchronized (mPackages) {
22215            List<String> codePaths = new ArrayList<>();
22216            final int packageCount = mSettings.mPackages.size();
22217            for (int i = 0; i < packageCount; i++) {
22218                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22219                codePaths.add(ps.codePath.getAbsolutePath());
22220            }
22221            return codePaths;
22222        }
22223    }
22224
22225    /**
22226     * Examine all apps present on given mounted volume, and destroy apps that
22227     * aren't expected, either due to uninstallation or reinstallation on
22228     * another volume.
22229     */
22230    private void reconcileApps(String volumeUuid) {
22231        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22232        List<File> filesToDelete = null;
22233
22234        final File[] files = FileUtils.listFilesOrEmpty(
22235                Environment.getDataAppDirectory(volumeUuid));
22236        for (File file : files) {
22237            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22238                    && !PackageInstallerService.isStageName(file.getName());
22239            if (!isPackage) {
22240                // Ignore entries which are not packages
22241                continue;
22242            }
22243
22244            String absolutePath = file.getAbsolutePath();
22245
22246            boolean pathValid = false;
22247            final int absoluteCodePathCount = absoluteCodePaths.size();
22248            for (int i = 0; i < absoluteCodePathCount; i++) {
22249                String absoluteCodePath = absoluteCodePaths.get(i);
22250                if (absolutePath.startsWith(absoluteCodePath)) {
22251                    pathValid = true;
22252                    break;
22253                }
22254            }
22255
22256            if (!pathValid) {
22257                if (filesToDelete == null) {
22258                    filesToDelete = new ArrayList<>();
22259                }
22260                filesToDelete.add(file);
22261            }
22262        }
22263
22264        if (filesToDelete != null) {
22265            final int fileToDeleteCount = filesToDelete.size();
22266            for (int i = 0; i < fileToDeleteCount; i++) {
22267                File fileToDelete = filesToDelete.get(i);
22268                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22269                synchronized (mInstallLock) {
22270                    removeCodePathLI(fileToDelete);
22271                }
22272            }
22273        }
22274    }
22275
22276    /**
22277     * Reconcile all app data for the given user.
22278     * <p>
22279     * Verifies that directories exist and that ownership and labeling is
22280     * correct for all installed apps on all mounted volumes.
22281     */
22282    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22283        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22284        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22285            final String volumeUuid = vol.getFsUuid();
22286            synchronized (mInstallLock) {
22287                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22288            }
22289        }
22290    }
22291
22292    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22293            boolean migrateAppData) {
22294        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22295    }
22296
22297    /**
22298     * Reconcile all app data on given mounted volume.
22299     * <p>
22300     * Destroys app data that isn't expected, either due to uninstallation or
22301     * reinstallation on another volume.
22302     * <p>
22303     * Verifies that directories exist and that ownership and labeling is
22304     * correct for all installed apps.
22305     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22306     */
22307    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22308            boolean migrateAppData, boolean onlyCoreApps) {
22309        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22310                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22311        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22312
22313        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22314        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22315
22316        // First look for stale data that doesn't belong, and check if things
22317        // have changed since we did our last restorecon
22318        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22319            if (StorageManager.isFileEncryptedNativeOrEmulated()
22320                    && !StorageManager.isUserKeyUnlocked(userId)) {
22321                throw new RuntimeException(
22322                        "Yikes, someone asked us to reconcile CE storage while " + userId
22323                                + " was still locked; this would have caused massive data loss!");
22324            }
22325
22326            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22327            for (File file : files) {
22328                final String packageName = file.getName();
22329                try {
22330                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22331                } catch (PackageManagerException e) {
22332                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22333                    try {
22334                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22335                                StorageManager.FLAG_STORAGE_CE, 0);
22336                    } catch (InstallerException e2) {
22337                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22338                    }
22339                }
22340            }
22341        }
22342        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22343            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22344            for (File file : files) {
22345                final String packageName = file.getName();
22346                try {
22347                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22348                } catch (PackageManagerException e) {
22349                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22350                    try {
22351                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22352                                StorageManager.FLAG_STORAGE_DE, 0);
22353                    } catch (InstallerException e2) {
22354                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22355                    }
22356                }
22357            }
22358        }
22359
22360        // Ensure that data directories are ready to roll for all packages
22361        // installed for this volume and user
22362        final List<PackageSetting> packages;
22363        synchronized (mPackages) {
22364            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22365        }
22366        int preparedCount = 0;
22367        for (PackageSetting ps : packages) {
22368            final String packageName = ps.name;
22369            if (ps.pkg == null) {
22370                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22371                // TODO: might be due to legacy ASEC apps; we should circle back
22372                // and reconcile again once they're scanned
22373                continue;
22374            }
22375            // Skip non-core apps if requested
22376            if (onlyCoreApps && !ps.pkg.coreApp) {
22377                result.add(packageName);
22378                continue;
22379            }
22380
22381            if (ps.getInstalled(userId)) {
22382                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22383                preparedCount++;
22384            }
22385        }
22386
22387        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22388        return result;
22389    }
22390
22391    /**
22392     * Prepare app data for the given app just after it was installed or
22393     * upgraded. This method carefully only touches users that it's installed
22394     * for, and it forces a restorecon to handle any seinfo changes.
22395     * <p>
22396     * Verifies that directories exist and that ownership and labeling is
22397     * correct for all installed apps. If there is an ownership mismatch, it
22398     * will try recovering system apps by wiping data; third-party app data is
22399     * left intact.
22400     * <p>
22401     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22402     */
22403    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22404        final PackageSetting ps;
22405        synchronized (mPackages) {
22406            ps = mSettings.mPackages.get(pkg.packageName);
22407            mSettings.writeKernelMappingLPr(ps);
22408        }
22409
22410        final UserManager um = mContext.getSystemService(UserManager.class);
22411        UserManagerInternal umInternal = getUserManagerInternal();
22412        for (UserInfo user : um.getUsers()) {
22413            final int flags;
22414            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22415                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22416            } else if (umInternal.isUserRunning(user.id)) {
22417                flags = StorageManager.FLAG_STORAGE_DE;
22418            } else {
22419                continue;
22420            }
22421
22422            if (ps.getInstalled(user.id)) {
22423                // TODO: when user data is locked, mark that we're still dirty
22424                prepareAppDataLIF(pkg, user.id, flags);
22425            }
22426        }
22427    }
22428
22429    /**
22430     * Prepare app data for the given app.
22431     * <p>
22432     * Verifies that directories exist and that ownership and labeling is
22433     * correct for all installed apps. If there is an ownership mismatch, this
22434     * will try recovering system apps by wiping data; third-party app data is
22435     * left intact.
22436     */
22437    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22438        if (pkg == null) {
22439            Slog.wtf(TAG, "Package was null!", new Throwable());
22440            return;
22441        }
22442        prepareAppDataLeafLIF(pkg, userId, flags);
22443        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22444        for (int i = 0; i < childCount; i++) {
22445            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22446        }
22447    }
22448
22449    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22450            boolean maybeMigrateAppData) {
22451        prepareAppDataLIF(pkg, userId, flags);
22452
22453        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22454            // We may have just shuffled around app data directories, so
22455            // prepare them one more time
22456            prepareAppDataLIF(pkg, userId, flags);
22457        }
22458    }
22459
22460    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22461        if (DEBUG_APP_DATA) {
22462            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22463                    + Integer.toHexString(flags));
22464        }
22465
22466        final String volumeUuid = pkg.volumeUuid;
22467        final String packageName = pkg.packageName;
22468        final ApplicationInfo app = pkg.applicationInfo;
22469        final int appId = UserHandle.getAppId(app.uid);
22470
22471        Preconditions.checkNotNull(app.seInfo);
22472
22473        long ceDataInode = -1;
22474        try {
22475            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22476                    appId, app.seInfo, app.targetSdkVersion);
22477        } catch (InstallerException e) {
22478            if (app.isSystemApp()) {
22479                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22480                        + ", but trying to recover: " + e);
22481                destroyAppDataLeafLIF(pkg, userId, flags);
22482                try {
22483                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22484                            appId, app.seInfo, app.targetSdkVersion);
22485                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22486                } catch (InstallerException e2) {
22487                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22488                }
22489            } else {
22490                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22491            }
22492        }
22493
22494        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22495            // TODO: mark this structure as dirty so we persist it!
22496            synchronized (mPackages) {
22497                final PackageSetting ps = mSettings.mPackages.get(packageName);
22498                if (ps != null) {
22499                    ps.setCeDataInode(ceDataInode, userId);
22500                }
22501            }
22502        }
22503
22504        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22505    }
22506
22507    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22508        if (pkg == null) {
22509            Slog.wtf(TAG, "Package was null!", new Throwable());
22510            return;
22511        }
22512        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22513        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22514        for (int i = 0; i < childCount; i++) {
22515            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22516        }
22517    }
22518
22519    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22520        final String volumeUuid = pkg.volumeUuid;
22521        final String packageName = pkg.packageName;
22522        final ApplicationInfo app = pkg.applicationInfo;
22523
22524        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22525            // Create a native library symlink only if we have native libraries
22526            // and if the native libraries are 32 bit libraries. We do not provide
22527            // this symlink for 64 bit libraries.
22528            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22529                final String nativeLibPath = app.nativeLibraryDir;
22530                try {
22531                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22532                            nativeLibPath, userId);
22533                } catch (InstallerException e) {
22534                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22535                }
22536            }
22537        }
22538    }
22539
22540    /**
22541     * For system apps on non-FBE devices, this method migrates any existing
22542     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22543     * requested by the app.
22544     */
22545    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22546        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22547                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22548            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22549                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22550            try {
22551                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22552                        storageTarget);
22553            } catch (InstallerException e) {
22554                logCriticalInfo(Log.WARN,
22555                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22556            }
22557            return true;
22558        } else {
22559            return false;
22560        }
22561    }
22562
22563    public PackageFreezer freezePackage(String packageName, String killReason) {
22564        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22565    }
22566
22567    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22568        return new PackageFreezer(packageName, userId, killReason);
22569    }
22570
22571    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22572            String killReason) {
22573        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22574    }
22575
22576    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22577            String killReason) {
22578        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22579            return new PackageFreezer();
22580        } else {
22581            return freezePackage(packageName, userId, killReason);
22582        }
22583    }
22584
22585    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22586            String killReason) {
22587        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22588    }
22589
22590    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22591            String killReason) {
22592        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22593            return new PackageFreezer();
22594        } else {
22595            return freezePackage(packageName, userId, killReason);
22596        }
22597    }
22598
22599    /**
22600     * Class that freezes and kills the given package upon creation, and
22601     * unfreezes it upon closing. This is typically used when doing surgery on
22602     * app code/data to prevent the app from running while you're working.
22603     */
22604    private class PackageFreezer implements AutoCloseable {
22605        private final String mPackageName;
22606        private final PackageFreezer[] mChildren;
22607
22608        private final boolean mWeFroze;
22609
22610        private final AtomicBoolean mClosed = new AtomicBoolean();
22611        private final CloseGuard mCloseGuard = CloseGuard.get();
22612
22613        /**
22614         * Create and return a stub freezer that doesn't actually do anything,
22615         * typically used when someone requested
22616         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22617         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22618         */
22619        public PackageFreezer() {
22620            mPackageName = null;
22621            mChildren = null;
22622            mWeFroze = false;
22623            mCloseGuard.open("close");
22624        }
22625
22626        public PackageFreezer(String packageName, int userId, String killReason) {
22627            synchronized (mPackages) {
22628                mPackageName = packageName;
22629                mWeFroze = mFrozenPackages.add(mPackageName);
22630
22631                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22632                if (ps != null) {
22633                    killApplication(ps.name, ps.appId, userId, killReason);
22634                }
22635
22636                final PackageParser.Package p = mPackages.get(packageName);
22637                if (p != null && p.childPackages != null) {
22638                    final int N = p.childPackages.size();
22639                    mChildren = new PackageFreezer[N];
22640                    for (int i = 0; i < N; i++) {
22641                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22642                                userId, killReason);
22643                    }
22644                } else {
22645                    mChildren = null;
22646                }
22647            }
22648            mCloseGuard.open("close");
22649        }
22650
22651        @Override
22652        protected void finalize() throws Throwable {
22653            try {
22654                mCloseGuard.warnIfOpen();
22655                close();
22656            } finally {
22657                super.finalize();
22658            }
22659        }
22660
22661        @Override
22662        public void close() {
22663            mCloseGuard.close();
22664            if (mClosed.compareAndSet(false, true)) {
22665                synchronized (mPackages) {
22666                    if (mWeFroze) {
22667                        mFrozenPackages.remove(mPackageName);
22668                    }
22669
22670                    if (mChildren != null) {
22671                        for (PackageFreezer freezer : mChildren) {
22672                            freezer.close();
22673                        }
22674                    }
22675                }
22676            }
22677        }
22678    }
22679
22680    /**
22681     * Verify that given package is currently frozen.
22682     */
22683    private void checkPackageFrozen(String packageName) {
22684        synchronized (mPackages) {
22685            if (!mFrozenPackages.contains(packageName)) {
22686                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22687            }
22688        }
22689    }
22690
22691    @Override
22692    public int movePackage(final String packageName, final String volumeUuid) {
22693        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22694
22695        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22696        final int moveId = mNextMoveId.getAndIncrement();
22697        mHandler.post(new Runnable() {
22698            @Override
22699            public void run() {
22700                try {
22701                    movePackageInternal(packageName, volumeUuid, moveId, user);
22702                } catch (PackageManagerException e) {
22703                    Slog.w(TAG, "Failed to move " + packageName, e);
22704                    mMoveCallbacks.notifyStatusChanged(moveId,
22705                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22706                }
22707            }
22708        });
22709        return moveId;
22710    }
22711
22712    private void movePackageInternal(final String packageName, final String volumeUuid,
22713            final int moveId, UserHandle user) throws PackageManagerException {
22714        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22715        final PackageManager pm = mContext.getPackageManager();
22716
22717        final boolean currentAsec;
22718        final String currentVolumeUuid;
22719        final File codeFile;
22720        final String installerPackageName;
22721        final String packageAbiOverride;
22722        final int appId;
22723        final String seinfo;
22724        final String label;
22725        final int targetSdkVersion;
22726        final PackageFreezer freezer;
22727        final int[] installedUserIds;
22728
22729        // reader
22730        synchronized (mPackages) {
22731            final PackageParser.Package pkg = mPackages.get(packageName);
22732            final PackageSetting ps = mSettings.mPackages.get(packageName);
22733            if (pkg == null || ps == null) {
22734                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22735            }
22736
22737            if (pkg.applicationInfo.isSystemApp()) {
22738                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22739                        "Cannot move system application");
22740            }
22741
22742            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22743            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22744                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22745            if (isInternalStorage && !allow3rdPartyOnInternal) {
22746                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22747                        "3rd party apps are not allowed on internal storage");
22748            }
22749
22750            if (pkg.applicationInfo.isExternalAsec()) {
22751                currentAsec = true;
22752                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22753            } else if (pkg.applicationInfo.isForwardLocked()) {
22754                currentAsec = true;
22755                currentVolumeUuid = "forward_locked";
22756            } else {
22757                currentAsec = false;
22758                currentVolumeUuid = ps.volumeUuid;
22759
22760                final File probe = new File(pkg.codePath);
22761                final File probeOat = new File(probe, "oat");
22762                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22763                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22764                            "Move only supported for modern cluster style installs");
22765                }
22766            }
22767
22768            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22769                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22770                        "Package already moved to " + volumeUuid);
22771            }
22772            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22773                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22774                        "Device admin cannot be moved");
22775            }
22776
22777            if (mFrozenPackages.contains(packageName)) {
22778                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22779                        "Failed to move already frozen package");
22780            }
22781
22782            codeFile = new File(pkg.codePath);
22783            installerPackageName = ps.installerPackageName;
22784            packageAbiOverride = ps.cpuAbiOverrideString;
22785            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22786            seinfo = pkg.applicationInfo.seInfo;
22787            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22788            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22789            freezer = freezePackage(packageName, "movePackageInternal");
22790            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22791        }
22792
22793        final Bundle extras = new Bundle();
22794        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22795        extras.putString(Intent.EXTRA_TITLE, label);
22796        mMoveCallbacks.notifyCreated(moveId, extras);
22797
22798        int installFlags;
22799        final boolean moveCompleteApp;
22800        final File measurePath;
22801
22802        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22803            installFlags = INSTALL_INTERNAL;
22804            moveCompleteApp = !currentAsec;
22805            measurePath = Environment.getDataAppDirectory(volumeUuid);
22806        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22807            installFlags = INSTALL_EXTERNAL;
22808            moveCompleteApp = false;
22809            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22810        } else {
22811            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22812            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22813                    || !volume.isMountedWritable()) {
22814                freezer.close();
22815                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22816                        "Move location not mounted private volume");
22817            }
22818
22819            Preconditions.checkState(!currentAsec);
22820
22821            installFlags = INSTALL_INTERNAL;
22822            moveCompleteApp = true;
22823            measurePath = Environment.getDataAppDirectory(volumeUuid);
22824        }
22825
22826        final PackageStats stats = new PackageStats(null, -1);
22827        synchronized (mInstaller) {
22828            for (int userId : installedUserIds) {
22829                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22830                    freezer.close();
22831                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22832                            "Failed to measure package size");
22833                }
22834            }
22835        }
22836
22837        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22838                + stats.dataSize);
22839
22840        final long startFreeBytes = measurePath.getUsableSpace();
22841        final long sizeBytes;
22842        if (moveCompleteApp) {
22843            sizeBytes = stats.codeSize + stats.dataSize;
22844        } else {
22845            sizeBytes = stats.codeSize;
22846        }
22847
22848        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22849            freezer.close();
22850            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22851                    "Not enough free space to move");
22852        }
22853
22854        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22855
22856        final CountDownLatch installedLatch = new CountDownLatch(1);
22857        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22858            @Override
22859            public void onUserActionRequired(Intent intent) throws RemoteException {
22860                throw new IllegalStateException();
22861            }
22862
22863            @Override
22864            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22865                    Bundle extras) throws RemoteException {
22866                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22867                        + PackageManager.installStatusToString(returnCode, msg));
22868
22869                installedLatch.countDown();
22870                freezer.close();
22871
22872                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22873                switch (status) {
22874                    case PackageInstaller.STATUS_SUCCESS:
22875                        mMoveCallbacks.notifyStatusChanged(moveId,
22876                                PackageManager.MOVE_SUCCEEDED);
22877                        break;
22878                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22879                        mMoveCallbacks.notifyStatusChanged(moveId,
22880                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22881                        break;
22882                    default:
22883                        mMoveCallbacks.notifyStatusChanged(moveId,
22884                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22885                        break;
22886                }
22887            }
22888        };
22889
22890        final MoveInfo move;
22891        if (moveCompleteApp) {
22892            // Kick off a thread to report progress estimates
22893            new Thread() {
22894                @Override
22895                public void run() {
22896                    while (true) {
22897                        try {
22898                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22899                                break;
22900                            }
22901                        } catch (InterruptedException ignored) {
22902                        }
22903
22904                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22905                        final int progress = 10 + (int) MathUtils.constrain(
22906                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22907                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22908                    }
22909                }
22910            }.start();
22911
22912            final String dataAppName = codeFile.getName();
22913            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22914                    dataAppName, appId, seinfo, targetSdkVersion);
22915        } else {
22916            move = null;
22917        }
22918
22919        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22920
22921        final Message msg = mHandler.obtainMessage(INIT_COPY);
22922        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22923        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22924                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22925                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22926                PackageManager.INSTALL_REASON_UNKNOWN);
22927        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22928        msg.obj = params;
22929
22930        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22931                System.identityHashCode(msg.obj));
22932        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22933                System.identityHashCode(msg.obj));
22934
22935        mHandler.sendMessage(msg);
22936    }
22937
22938    @Override
22939    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22940        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22941
22942        final int realMoveId = mNextMoveId.getAndIncrement();
22943        final Bundle extras = new Bundle();
22944        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22945        mMoveCallbacks.notifyCreated(realMoveId, extras);
22946
22947        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22948            @Override
22949            public void onCreated(int moveId, Bundle extras) {
22950                // Ignored
22951            }
22952
22953            @Override
22954            public void onStatusChanged(int moveId, int status, long estMillis) {
22955                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22956            }
22957        };
22958
22959        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22960        storage.setPrimaryStorageUuid(volumeUuid, callback);
22961        return realMoveId;
22962    }
22963
22964    @Override
22965    public int getMoveStatus(int moveId) {
22966        mContext.enforceCallingOrSelfPermission(
22967                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22968        return mMoveCallbacks.mLastStatus.get(moveId);
22969    }
22970
22971    @Override
22972    public void registerMoveCallback(IPackageMoveObserver callback) {
22973        mContext.enforceCallingOrSelfPermission(
22974                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22975        mMoveCallbacks.register(callback);
22976    }
22977
22978    @Override
22979    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22980        mContext.enforceCallingOrSelfPermission(
22981                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22982        mMoveCallbacks.unregister(callback);
22983    }
22984
22985    @Override
22986    public boolean setInstallLocation(int loc) {
22987        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22988                null);
22989        if (getInstallLocation() == loc) {
22990            return true;
22991        }
22992        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22993                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22994            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22995                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22996            return true;
22997        }
22998        return false;
22999   }
23000
23001    @Override
23002    public int getInstallLocation() {
23003        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23004                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23005                PackageHelper.APP_INSTALL_AUTO);
23006    }
23007
23008    /** Called by UserManagerService */
23009    void cleanUpUser(UserManagerService userManager, int userHandle) {
23010        synchronized (mPackages) {
23011            mDirtyUsers.remove(userHandle);
23012            mUserNeedsBadging.delete(userHandle);
23013            mSettings.removeUserLPw(userHandle);
23014            mPendingBroadcasts.remove(userHandle);
23015            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23016            removeUnusedPackagesLPw(userManager, userHandle);
23017        }
23018    }
23019
23020    /**
23021     * We're removing userHandle and would like to remove any downloaded packages
23022     * that are no longer in use by any other user.
23023     * @param userHandle the user being removed
23024     */
23025    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23026        final boolean DEBUG_CLEAN_APKS = false;
23027        int [] users = userManager.getUserIds();
23028        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23029        while (psit.hasNext()) {
23030            PackageSetting ps = psit.next();
23031            if (ps.pkg == null) {
23032                continue;
23033            }
23034            final String packageName = ps.pkg.packageName;
23035            // Skip over if system app
23036            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23037                continue;
23038            }
23039            if (DEBUG_CLEAN_APKS) {
23040                Slog.i(TAG, "Checking package " + packageName);
23041            }
23042            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23043            if (keep) {
23044                if (DEBUG_CLEAN_APKS) {
23045                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23046                }
23047            } else {
23048                for (int i = 0; i < users.length; i++) {
23049                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23050                        keep = true;
23051                        if (DEBUG_CLEAN_APKS) {
23052                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23053                                    + users[i]);
23054                        }
23055                        break;
23056                    }
23057                }
23058            }
23059            if (!keep) {
23060                if (DEBUG_CLEAN_APKS) {
23061                    Slog.i(TAG, "  Removing package " + packageName);
23062                }
23063                mHandler.post(new Runnable() {
23064                    public void run() {
23065                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23066                                userHandle, 0);
23067                    } //end run
23068                });
23069            }
23070        }
23071    }
23072
23073    /** Called by UserManagerService */
23074    void createNewUser(int userId, String[] disallowedPackages) {
23075        synchronized (mInstallLock) {
23076            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23077        }
23078        synchronized (mPackages) {
23079            scheduleWritePackageRestrictionsLocked(userId);
23080            scheduleWritePackageListLocked(userId);
23081            applyFactoryDefaultBrowserLPw(userId);
23082            primeDomainVerificationsLPw(userId);
23083        }
23084    }
23085
23086    void onNewUserCreated(final int userId) {
23087        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23088        // If permission review for legacy apps is required, we represent
23089        // dagerous permissions for such apps as always granted runtime
23090        // permissions to keep per user flag state whether review is needed.
23091        // Hence, if a new user is added we have to propagate dangerous
23092        // permission grants for these legacy apps.
23093        if (mPermissionReviewRequired) {
23094            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23095                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23096        }
23097    }
23098
23099    @Override
23100    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23101        mContext.enforceCallingOrSelfPermission(
23102                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23103                "Only package verification agents can read the verifier device identity");
23104
23105        synchronized (mPackages) {
23106            return mSettings.getVerifierDeviceIdentityLPw();
23107        }
23108    }
23109
23110    @Override
23111    public void setPermissionEnforced(String permission, boolean enforced) {
23112        // TODO: Now that we no longer change GID for storage, this should to away.
23113        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23114                "setPermissionEnforced");
23115        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23116            synchronized (mPackages) {
23117                if (mSettings.mReadExternalStorageEnforced == null
23118                        || mSettings.mReadExternalStorageEnforced != enforced) {
23119                    mSettings.mReadExternalStorageEnforced = enforced;
23120                    mSettings.writeLPr();
23121                }
23122            }
23123            // kill any non-foreground processes so we restart them and
23124            // grant/revoke the GID.
23125            final IActivityManager am = ActivityManager.getService();
23126            if (am != null) {
23127                final long token = Binder.clearCallingIdentity();
23128                try {
23129                    am.killProcessesBelowForeground("setPermissionEnforcement");
23130                } catch (RemoteException e) {
23131                } finally {
23132                    Binder.restoreCallingIdentity(token);
23133                }
23134            }
23135        } else {
23136            throw new IllegalArgumentException("No selective enforcement for " + permission);
23137        }
23138    }
23139
23140    @Override
23141    @Deprecated
23142    public boolean isPermissionEnforced(String permission) {
23143        return true;
23144    }
23145
23146    @Override
23147    public boolean isStorageLow() {
23148        final long token = Binder.clearCallingIdentity();
23149        try {
23150            final DeviceStorageMonitorInternal
23151                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23152            if (dsm != null) {
23153                return dsm.isMemoryLow();
23154            } else {
23155                return false;
23156            }
23157        } finally {
23158            Binder.restoreCallingIdentity(token);
23159        }
23160    }
23161
23162    @Override
23163    public IPackageInstaller getPackageInstaller() {
23164        return mInstallerService;
23165    }
23166
23167    private boolean userNeedsBadging(int userId) {
23168        int index = mUserNeedsBadging.indexOfKey(userId);
23169        if (index < 0) {
23170            final UserInfo userInfo;
23171            final long token = Binder.clearCallingIdentity();
23172            try {
23173                userInfo = sUserManager.getUserInfo(userId);
23174            } finally {
23175                Binder.restoreCallingIdentity(token);
23176            }
23177            final boolean b;
23178            if (userInfo != null && userInfo.isManagedProfile()) {
23179                b = true;
23180            } else {
23181                b = false;
23182            }
23183            mUserNeedsBadging.put(userId, b);
23184            return b;
23185        }
23186        return mUserNeedsBadging.valueAt(index);
23187    }
23188
23189    @Override
23190    public KeySet getKeySetByAlias(String packageName, String alias) {
23191        if (packageName == null || alias == null) {
23192            return null;
23193        }
23194        synchronized(mPackages) {
23195            final PackageParser.Package pkg = mPackages.get(packageName);
23196            if (pkg == null) {
23197                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23198                throw new IllegalArgumentException("Unknown package: " + packageName);
23199            }
23200            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23201            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23202        }
23203    }
23204
23205    @Override
23206    public KeySet getSigningKeySet(String packageName) {
23207        if (packageName == null) {
23208            return null;
23209        }
23210        synchronized(mPackages) {
23211            final PackageParser.Package pkg = mPackages.get(packageName);
23212            if (pkg == null) {
23213                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23214                throw new IllegalArgumentException("Unknown package: " + packageName);
23215            }
23216            if (pkg.applicationInfo.uid != Binder.getCallingUid()
23217                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
23218                throw new SecurityException("May not access signing KeySet of other apps.");
23219            }
23220            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23221            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23222        }
23223    }
23224
23225    @Override
23226    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23227        if (packageName == null || ks == null) {
23228            return false;
23229        }
23230        synchronized(mPackages) {
23231            final PackageParser.Package pkg = mPackages.get(packageName);
23232            if (pkg == null) {
23233                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23234                throw new IllegalArgumentException("Unknown package: " + packageName);
23235            }
23236            IBinder ksh = ks.getToken();
23237            if (ksh instanceof KeySetHandle) {
23238                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23239                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23240            }
23241            return false;
23242        }
23243    }
23244
23245    @Override
23246    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23247        if (packageName == null || ks == null) {
23248            return false;
23249        }
23250        synchronized(mPackages) {
23251            final PackageParser.Package pkg = mPackages.get(packageName);
23252            if (pkg == null) {
23253                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23254                throw new IllegalArgumentException("Unknown package: " + packageName);
23255            }
23256            IBinder ksh = ks.getToken();
23257            if (ksh instanceof KeySetHandle) {
23258                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23259                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23260            }
23261            return false;
23262        }
23263    }
23264
23265    private void deletePackageIfUnusedLPr(final String packageName) {
23266        PackageSetting ps = mSettings.mPackages.get(packageName);
23267        if (ps == null) {
23268            return;
23269        }
23270        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23271            // TODO Implement atomic delete if package is unused
23272            // It is currently possible that the package will be deleted even if it is installed
23273            // after this method returns.
23274            mHandler.post(new Runnable() {
23275                public void run() {
23276                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23277                            0, PackageManager.DELETE_ALL_USERS);
23278                }
23279            });
23280        }
23281    }
23282
23283    /**
23284     * Check and throw if the given before/after packages would be considered a
23285     * downgrade.
23286     */
23287    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23288            throws PackageManagerException {
23289        if (after.versionCode < before.mVersionCode) {
23290            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23291                    "Update version code " + after.versionCode + " is older than current "
23292                    + before.mVersionCode);
23293        } else if (after.versionCode == before.mVersionCode) {
23294            if (after.baseRevisionCode < before.baseRevisionCode) {
23295                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23296                        "Update base revision code " + after.baseRevisionCode
23297                        + " is older than current " + before.baseRevisionCode);
23298            }
23299
23300            if (!ArrayUtils.isEmpty(after.splitNames)) {
23301                for (int i = 0; i < after.splitNames.length; i++) {
23302                    final String splitName = after.splitNames[i];
23303                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23304                    if (j != -1) {
23305                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23306                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23307                                    "Update split " + splitName + " revision code "
23308                                    + after.splitRevisionCodes[i] + " is older than current "
23309                                    + before.splitRevisionCodes[j]);
23310                        }
23311                    }
23312                }
23313            }
23314        }
23315    }
23316
23317    private static class MoveCallbacks extends Handler {
23318        private static final int MSG_CREATED = 1;
23319        private static final int MSG_STATUS_CHANGED = 2;
23320
23321        private final RemoteCallbackList<IPackageMoveObserver>
23322                mCallbacks = new RemoteCallbackList<>();
23323
23324        private final SparseIntArray mLastStatus = new SparseIntArray();
23325
23326        public MoveCallbacks(Looper looper) {
23327            super(looper);
23328        }
23329
23330        public void register(IPackageMoveObserver callback) {
23331            mCallbacks.register(callback);
23332        }
23333
23334        public void unregister(IPackageMoveObserver callback) {
23335            mCallbacks.unregister(callback);
23336        }
23337
23338        @Override
23339        public void handleMessage(Message msg) {
23340            final SomeArgs args = (SomeArgs) msg.obj;
23341            final int n = mCallbacks.beginBroadcast();
23342            for (int i = 0; i < n; i++) {
23343                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23344                try {
23345                    invokeCallback(callback, msg.what, args);
23346                } catch (RemoteException ignored) {
23347                }
23348            }
23349            mCallbacks.finishBroadcast();
23350            args.recycle();
23351        }
23352
23353        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23354                throws RemoteException {
23355            switch (what) {
23356                case MSG_CREATED: {
23357                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23358                    break;
23359                }
23360                case MSG_STATUS_CHANGED: {
23361                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23362                    break;
23363                }
23364            }
23365        }
23366
23367        private void notifyCreated(int moveId, Bundle extras) {
23368            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23369
23370            final SomeArgs args = SomeArgs.obtain();
23371            args.argi1 = moveId;
23372            args.arg2 = extras;
23373            obtainMessage(MSG_CREATED, args).sendToTarget();
23374        }
23375
23376        private void notifyStatusChanged(int moveId, int status) {
23377            notifyStatusChanged(moveId, status, -1);
23378        }
23379
23380        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23381            Slog.v(TAG, "Move " + moveId + " status " + status);
23382
23383            final SomeArgs args = SomeArgs.obtain();
23384            args.argi1 = moveId;
23385            args.argi2 = status;
23386            args.arg3 = estMillis;
23387            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23388
23389            synchronized (mLastStatus) {
23390                mLastStatus.put(moveId, status);
23391            }
23392        }
23393    }
23394
23395    private final static class OnPermissionChangeListeners extends Handler {
23396        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23397
23398        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23399                new RemoteCallbackList<>();
23400
23401        public OnPermissionChangeListeners(Looper looper) {
23402            super(looper);
23403        }
23404
23405        @Override
23406        public void handleMessage(Message msg) {
23407            switch (msg.what) {
23408                case MSG_ON_PERMISSIONS_CHANGED: {
23409                    final int uid = msg.arg1;
23410                    handleOnPermissionsChanged(uid);
23411                } break;
23412            }
23413        }
23414
23415        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23416            mPermissionListeners.register(listener);
23417
23418        }
23419
23420        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23421            mPermissionListeners.unregister(listener);
23422        }
23423
23424        public void onPermissionsChanged(int uid) {
23425            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23426                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23427            }
23428        }
23429
23430        private void handleOnPermissionsChanged(int uid) {
23431            final int count = mPermissionListeners.beginBroadcast();
23432            try {
23433                for (int i = 0; i < count; i++) {
23434                    IOnPermissionsChangeListener callback = mPermissionListeners
23435                            .getBroadcastItem(i);
23436                    try {
23437                        callback.onPermissionsChanged(uid);
23438                    } catch (RemoteException e) {
23439                        Log.e(TAG, "Permission listener is dead", e);
23440                    }
23441                }
23442            } finally {
23443                mPermissionListeners.finishBroadcast();
23444            }
23445        }
23446    }
23447
23448    private class PackageManagerInternalImpl extends PackageManagerInternal {
23449        @Override
23450        public void setLocationPackagesProvider(PackagesProvider provider) {
23451            synchronized (mPackages) {
23452                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23453            }
23454        }
23455
23456        @Override
23457        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23458            synchronized (mPackages) {
23459                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23460            }
23461        }
23462
23463        @Override
23464        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23465            synchronized (mPackages) {
23466                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23467            }
23468        }
23469
23470        @Override
23471        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23472            synchronized (mPackages) {
23473                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23474            }
23475        }
23476
23477        @Override
23478        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23479            synchronized (mPackages) {
23480                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23481            }
23482        }
23483
23484        @Override
23485        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23486            synchronized (mPackages) {
23487                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23488            }
23489        }
23490
23491        @Override
23492        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23493            synchronized (mPackages) {
23494                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23495                        packageName, userId);
23496            }
23497        }
23498
23499        @Override
23500        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23501            synchronized (mPackages) {
23502                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23503                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23504                        packageName, userId);
23505            }
23506        }
23507
23508        @Override
23509        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23510            synchronized (mPackages) {
23511                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23512                        packageName, userId);
23513            }
23514        }
23515
23516        @Override
23517        public void setKeepUninstalledPackages(final List<String> packageList) {
23518            Preconditions.checkNotNull(packageList);
23519            List<String> removedFromList = null;
23520            synchronized (mPackages) {
23521                if (mKeepUninstalledPackages != null) {
23522                    final int packagesCount = mKeepUninstalledPackages.size();
23523                    for (int i = 0; i < packagesCount; i++) {
23524                        String oldPackage = mKeepUninstalledPackages.get(i);
23525                        if (packageList != null && packageList.contains(oldPackage)) {
23526                            continue;
23527                        }
23528                        if (removedFromList == null) {
23529                            removedFromList = new ArrayList<>();
23530                        }
23531                        removedFromList.add(oldPackage);
23532                    }
23533                }
23534                mKeepUninstalledPackages = new ArrayList<>(packageList);
23535                if (removedFromList != null) {
23536                    final int removedCount = removedFromList.size();
23537                    for (int i = 0; i < removedCount; i++) {
23538                        deletePackageIfUnusedLPr(removedFromList.get(i));
23539                    }
23540                }
23541            }
23542        }
23543
23544        @Override
23545        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23546            synchronized (mPackages) {
23547                // If we do not support permission review, done.
23548                if (!mPermissionReviewRequired) {
23549                    return false;
23550                }
23551
23552                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23553                if (packageSetting == null) {
23554                    return false;
23555                }
23556
23557                // Permission review applies only to apps not supporting the new permission model.
23558                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23559                    return false;
23560                }
23561
23562                // Legacy apps have the permission and get user consent on launch.
23563                PermissionsState permissionsState = packageSetting.getPermissionsState();
23564                return permissionsState.isPermissionReviewRequired(userId);
23565            }
23566        }
23567
23568        @Override
23569        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23570            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23571        }
23572
23573        @Override
23574        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23575                int userId) {
23576            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23577        }
23578
23579        @Override
23580        public void setDeviceAndProfileOwnerPackages(
23581                int deviceOwnerUserId, String deviceOwnerPackage,
23582                SparseArray<String> profileOwnerPackages) {
23583            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23584                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23585        }
23586
23587        @Override
23588        public boolean isPackageDataProtected(int userId, String packageName) {
23589            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23590        }
23591
23592        @Override
23593        public boolean isPackageEphemeral(int userId, String packageName) {
23594            synchronized (mPackages) {
23595                final PackageSetting ps = mSettings.mPackages.get(packageName);
23596                return ps != null ? ps.getInstantApp(userId) : false;
23597            }
23598        }
23599
23600        @Override
23601        public boolean wasPackageEverLaunched(String packageName, int userId) {
23602            synchronized (mPackages) {
23603                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23604            }
23605        }
23606
23607        @Override
23608        public void grantRuntimePermission(String packageName, String name, int userId,
23609                boolean overridePolicy) {
23610            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23611                    overridePolicy);
23612        }
23613
23614        @Override
23615        public void revokeRuntimePermission(String packageName, String name, int userId,
23616                boolean overridePolicy) {
23617            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23618                    overridePolicy);
23619        }
23620
23621        @Override
23622        public String getNameForUid(int uid) {
23623            return PackageManagerService.this.getNameForUid(uid);
23624        }
23625
23626        @Override
23627        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23628                Intent origIntent, String resolvedType, String callingPackage,
23629                Bundle verificationBundle, int userId) {
23630            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23631                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23632                    userId);
23633        }
23634
23635        @Override
23636        public void grantEphemeralAccess(int userId, Intent intent,
23637                int targetAppId, int ephemeralAppId) {
23638            synchronized (mPackages) {
23639                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23640                        targetAppId, ephemeralAppId);
23641            }
23642        }
23643
23644        @Override
23645        public boolean isInstantAppInstallerComponent(ComponentName component) {
23646            synchronized (mPackages) {
23647                return mInstantAppInstallerActivity != null
23648                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23649            }
23650        }
23651
23652        @Override
23653        public void pruneInstantApps() {
23654            synchronized (mPackages) {
23655                mInstantAppRegistry.pruneInstantAppsLPw();
23656            }
23657        }
23658
23659        @Override
23660        public String getSetupWizardPackageName() {
23661            return mSetupWizardPackage;
23662        }
23663
23664        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23665            if (policy != null) {
23666                mExternalSourcesPolicy = policy;
23667            }
23668        }
23669
23670        @Override
23671        public boolean isPackagePersistent(String packageName) {
23672            synchronized (mPackages) {
23673                PackageParser.Package pkg = mPackages.get(packageName);
23674                return pkg != null
23675                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23676                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23677                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23678                        : false;
23679            }
23680        }
23681
23682        @Override
23683        public List<PackageInfo> getOverlayPackages(int userId) {
23684            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23685            synchronized (mPackages) {
23686                for (PackageParser.Package p : mPackages.values()) {
23687                    if (p.mOverlayTarget != null) {
23688                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23689                        if (pkg != null) {
23690                            overlayPackages.add(pkg);
23691                        }
23692                    }
23693                }
23694            }
23695            return overlayPackages;
23696        }
23697
23698        @Override
23699        public List<String> getTargetPackageNames(int userId) {
23700            List<String> targetPackages = new ArrayList<>();
23701            synchronized (mPackages) {
23702                for (PackageParser.Package p : mPackages.values()) {
23703                    if (p.mOverlayTarget == null) {
23704                        targetPackages.add(p.packageName);
23705                    }
23706                }
23707            }
23708            return targetPackages;
23709        }
23710
23711        @Override
23712        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23713                @Nullable List<String> overlayPackageNames) {
23714            synchronized (mPackages) {
23715                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23716                    Slog.e(TAG, "failed to find package " + targetPackageName);
23717                    return false;
23718                }
23719
23720                ArrayList<String> paths = null;
23721                if (overlayPackageNames != null) {
23722                    final int N = overlayPackageNames.size();
23723                    paths = new ArrayList<>(N);
23724                    for (int i = 0; i < N; i++) {
23725                        final String packageName = overlayPackageNames.get(i);
23726                        final PackageParser.Package pkg = mPackages.get(packageName);
23727                        if (pkg == null) {
23728                            Slog.e(TAG, "failed to find package " + packageName);
23729                            return false;
23730                        }
23731                        paths.add(pkg.baseCodePath);
23732                    }
23733                }
23734
23735                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23736                    mEnabledOverlayPaths.get(userId);
23737                if (userSpecificOverlays == null) {
23738                    userSpecificOverlays = new ArrayMap<>();
23739                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23740                }
23741
23742                if (paths != null && paths.size() > 0) {
23743                    userSpecificOverlays.put(targetPackageName, paths);
23744                } else {
23745                    userSpecificOverlays.remove(targetPackageName);
23746                }
23747                return true;
23748            }
23749        }
23750
23751        @Override
23752        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23753                int flags, int userId) {
23754            return resolveIntentInternal(
23755                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
23756        }
23757
23758        @Override
23759        public ResolveInfo resolveService(Intent intent, String resolvedType,
23760                int flags, int userId, int callingUid) {
23761            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23762        }
23763
23764        @Override
23765        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23766            synchronized (mPackages) {
23767                mIsolatedOwners.put(isolatedUid, ownerUid);
23768            }
23769        }
23770
23771        @Override
23772        public void removeIsolatedUid(int isolatedUid) {
23773            synchronized (mPackages) {
23774                mIsolatedOwners.delete(isolatedUid);
23775            }
23776        }
23777
23778        @Override
23779        public int getUidTargetSdkVersion(int uid) {
23780            synchronized (mPackages) {
23781                return getUidTargetSdkVersionLockedLPr(uid);
23782            }
23783        }
23784    }
23785
23786    @Override
23787    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23788        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23789        synchronized (mPackages) {
23790            final long identity = Binder.clearCallingIdentity();
23791            try {
23792                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23793                        packageNames, userId);
23794            } finally {
23795                Binder.restoreCallingIdentity(identity);
23796            }
23797        }
23798    }
23799
23800    @Override
23801    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23802        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23803        synchronized (mPackages) {
23804            final long identity = Binder.clearCallingIdentity();
23805            try {
23806                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23807                        packageNames, userId);
23808            } finally {
23809                Binder.restoreCallingIdentity(identity);
23810            }
23811        }
23812    }
23813
23814    private static void enforceSystemOrPhoneCaller(String tag) {
23815        int callingUid = Binder.getCallingUid();
23816        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23817            throw new SecurityException(
23818                    "Cannot call " + tag + " from UID " + callingUid);
23819        }
23820    }
23821
23822    boolean isHistoricalPackageUsageAvailable() {
23823        return mPackageUsage.isHistoricalPackageUsageAvailable();
23824    }
23825
23826    /**
23827     * Return a <b>copy</b> of the collection of packages known to the package manager.
23828     * @return A copy of the values of mPackages.
23829     */
23830    Collection<PackageParser.Package> getPackages() {
23831        synchronized (mPackages) {
23832            return new ArrayList<>(mPackages.values());
23833        }
23834    }
23835
23836    /**
23837     * Logs process start information (including base APK hash) to the security log.
23838     * @hide
23839     */
23840    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23841            String apkFile, int pid) {
23842        if (!SecurityLog.isLoggingEnabled()) {
23843            return;
23844        }
23845        Bundle data = new Bundle();
23846        data.putLong("startTimestamp", System.currentTimeMillis());
23847        data.putString("processName", processName);
23848        data.putInt("uid", uid);
23849        data.putString("seinfo", seinfo);
23850        data.putString("apkFile", apkFile);
23851        data.putInt("pid", pid);
23852        Message msg = mProcessLoggingHandler.obtainMessage(
23853                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23854        msg.setData(data);
23855        mProcessLoggingHandler.sendMessage(msg);
23856    }
23857
23858    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23859        return mCompilerStats.getPackageStats(pkgName);
23860    }
23861
23862    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23863        return getOrCreateCompilerPackageStats(pkg.packageName);
23864    }
23865
23866    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23867        return mCompilerStats.getOrCreatePackageStats(pkgName);
23868    }
23869
23870    public void deleteCompilerPackageStats(String pkgName) {
23871        mCompilerStats.deletePackageStats(pkgName);
23872    }
23873
23874    @Override
23875    public int getInstallReason(String packageName, int userId) {
23876        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23877                true /* requireFullPermission */, false /* checkShell */,
23878                "get install reason");
23879        synchronized (mPackages) {
23880            final PackageSetting ps = mSettings.mPackages.get(packageName);
23881            if (ps != null) {
23882                return ps.getInstallReason(userId);
23883            }
23884        }
23885        return PackageManager.INSTALL_REASON_UNKNOWN;
23886    }
23887
23888    @Override
23889    public boolean canRequestPackageInstalls(String packageName, int userId) {
23890        int callingUid = Binder.getCallingUid();
23891        int uid = getPackageUid(packageName, 0, userId);
23892        if (callingUid != uid && callingUid != Process.ROOT_UID
23893                && callingUid != Process.SYSTEM_UID) {
23894            throw new SecurityException(
23895                    "Caller uid " + callingUid + " does not own package " + packageName);
23896        }
23897        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23898        if (info == null) {
23899            return false;
23900        }
23901        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23902            throw new UnsupportedOperationException(
23903                    "Operation only supported on apps targeting Android O or higher");
23904        }
23905        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23906        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23907        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23908            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23909        }
23910        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23911            return false;
23912        }
23913        if (mExternalSourcesPolicy != null) {
23914            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23915            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23916                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23917            }
23918        }
23919        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23920    }
23921
23922    @Override
23923    public ComponentName getInstantAppResolverSettingsComponent() {
23924        return mInstantAppResolverSettingsComponent;
23925    }
23926
23927    @Override
23928    public ComponentName getInstantAppInstallerComponent() {
23929        return mInstantAppInstallerActivity == null
23930                ? null : mInstantAppInstallerActivity.getComponentName();
23931    }
23932
23933    @Override
23934    public String getInstantAppAndroidId(String packageName, int userId) {
23935        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23936                "getInstantAppAndroidId");
23937        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23938                true /* requireFullPermission */, false /* checkShell */,
23939                "getInstantAppAndroidId");
23940        // Make sure the target is an Instant App.
23941        if (!isInstantApp(packageName, userId)) {
23942            return null;
23943        }
23944        synchronized (mPackages) {
23945            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23946        }
23947    }
23948}
23949
23950interface PackageSender {
23951    void sendPackageBroadcast(final String action, final String pkg,
23952        final Bundle extras, final int flags, final String targetPkg,
23953        final IIntentReceiver finishedReceiver, final int[] userIds);
23954    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
23955        int appId, int... userIds);
23956}
23957