PackageManagerService.java revision 4b0aa4db3a0d8101293832dd554b53cb8a0114b9
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.DeviceIdleController;
264import com.android.server.EventLogTags;
265import com.android.server.FgThread;
266import com.android.server.IntentResolver;
267import com.android.server.LocalServices;
268import com.android.server.LockGuard;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.BackgroundDexOptService;
275import com.android.server.pm.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
300import java.io.FileNotFoundException;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
398    private static final boolean DISABLE_EPHEMERAL_APPS = false;
399    private static final boolean HIDE_EPHEMERAL_APIS = false;
400
401    private static final boolean ENABLE_FREE_CACHE_V2 =
402            SystemProperties.getBoolean("fw.free_cache_v2", true);
403
404    private static final int RADIO_UID = Process.PHONE_UID;
405    private static final int LOG_UID = Process.LOG_UID;
406    private static final int NFC_UID = Process.NFC_UID;
407    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
408    private static final int SHELL_UID = Process.SHELL_UID;
409
410    // Cap the size of permission trees that 3rd party apps can define
411    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
412
413    // Suffix used during package installation when copying/moving
414    // package apks to install directory.
415    private static final String INSTALL_PACKAGE_SUFFIX = "-";
416
417    static final int SCAN_NO_DEX = 1<<1;
418    static final int SCAN_FORCE_DEX = 1<<2;
419    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
420    static final int SCAN_NEW_INSTALL = 1<<4;
421    static final int SCAN_UPDATE_TIME = 1<<5;
422    static final int SCAN_BOOTING = 1<<6;
423    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
424    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
425    static final int SCAN_REPLACING = 1<<9;
426    static final int SCAN_REQUIRE_KNOWN = 1<<10;
427    static final int SCAN_MOVE = 1<<11;
428    static final int SCAN_INITIAL = 1<<12;
429    static final int SCAN_CHECK_ONLY = 1<<13;
430    static final int SCAN_DONT_KILL_APP = 1<<14;
431    static final int SCAN_IGNORE_FROZEN = 1<<15;
432    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
433    static final int SCAN_AS_INSTANT_APP = 1<<17;
434    static final int SCAN_AS_FULL_APP = 1<<18;
435    /** Should not be with the scan flags */
436    static final int FLAGS_REMOVE_CHATTY = 1<<31;
437
438    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
439
440    private static final int[] EMPTY_INT_ARRAY = new int[0];
441
442    /**
443     * Timeout (in milliseconds) after which the watchdog should declare that
444     * our handler thread is wedged.  The usual default for such things is one
445     * minute but we sometimes do very lengthy I/O operations on this thread,
446     * such as installing multi-gigabyte applications, so ours needs to be longer.
447     */
448    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
449
450    /**
451     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
452     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
453     * settings entry if available, otherwise we use the hardcoded default.  If it's been
454     * more than this long since the last fstrim, we force one during the boot sequence.
455     *
456     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
457     * one gets run at the next available charging+idle time.  This final mandatory
458     * no-fstrim check kicks in only of the other scheduling criteria is never met.
459     */
460    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
461
462    /**
463     * Whether verification is enabled by default.
464     */
465    private static final boolean DEFAULT_VERIFY_ENABLE = true;
466
467    /**
468     * The default maximum time to wait for the verification agent to return in
469     * milliseconds.
470     */
471    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
472
473    /**
474     * The default response for package verification timeout.
475     *
476     * This can be either PackageManager.VERIFICATION_ALLOW or
477     * PackageManager.VERIFICATION_REJECT.
478     */
479    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
480
481    static final String PLATFORM_PACKAGE_NAME = "android";
482
483    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
484
485    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
486            DEFAULT_CONTAINER_PACKAGE,
487            "com.android.defcontainer.DefaultContainerService");
488
489    private static final String KILL_APP_REASON_GIDS_CHANGED =
490            "permission grant or revoke changed gids";
491
492    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
493            "permissions revoked";
494
495    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
496
497    private static final String PACKAGE_SCHEME = "package";
498
499    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
500
501    /** Permission grant: not grant the permission. */
502    private static final int GRANT_DENIED = 1;
503
504    /** Permission grant: grant the permission as an install permission. */
505    private static final int GRANT_INSTALL = 2;
506
507    /** Permission grant: grant the permission as a runtime one. */
508    private static final int GRANT_RUNTIME = 3;
509
510    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
511    private static final int GRANT_UPGRADE = 4;
512
513    /** Canonical intent used to identify what counts as a "web browser" app */
514    private static final Intent sBrowserIntent;
515    static {
516        sBrowserIntent = new Intent();
517        sBrowserIntent.setAction(Intent.ACTION_VIEW);
518        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
519        sBrowserIntent.setData(Uri.parse("http:"));
520    }
521
522    /**
523     * The set of all protected actions [i.e. those actions for which a high priority
524     * intent filter is disallowed].
525     */
526    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
527    static {
528        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
531        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
532    }
533
534    // Compilation reasons.
535    public static final int REASON_FIRST_BOOT = 0;
536    public static final int REASON_BOOT = 1;
537    public static final int REASON_INSTALL = 2;
538    public static final int REASON_BACKGROUND_DEXOPT = 3;
539    public static final int REASON_AB_OTA = 4;
540    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
541    public static final int REASON_SHARED_APK = 6;
542    public static final int REASON_FORCED_DEXOPT = 7;
543    public static final int REASON_CORE_APP = 8;
544
545    public static final int REASON_LAST = REASON_CORE_APP;
546
547    /** All dangerous permission names in the same order as the events in MetricsEvent */
548    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
549            Manifest.permission.READ_CALENDAR,
550            Manifest.permission.WRITE_CALENDAR,
551            Manifest.permission.CAMERA,
552            Manifest.permission.READ_CONTACTS,
553            Manifest.permission.WRITE_CONTACTS,
554            Manifest.permission.GET_ACCOUNTS,
555            Manifest.permission.ACCESS_FINE_LOCATION,
556            Manifest.permission.ACCESS_COARSE_LOCATION,
557            Manifest.permission.RECORD_AUDIO,
558            Manifest.permission.READ_PHONE_STATE,
559            Manifest.permission.CALL_PHONE,
560            Manifest.permission.READ_CALL_LOG,
561            Manifest.permission.WRITE_CALL_LOG,
562            Manifest.permission.ADD_VOICEMAIL,
563            Manifest.permission.USE_SIP,
564            Manifest.permission.PROCESS_OUTGOING_CALLS,
565            Manifest.permission.READ_CELL_BROADCASTS,
566            Manifest.permission.BODY_SENSORS,
567            Manifest.permission.SEND_SMS,
568            Manifest.permission.RECEIVE_SMS,
569            Manifest.permission.READ_SMS,
570            Manifest.permission.RECEIVE_WAP_PUSH,
571            Manifest.permission.RECEIVE_MMS,
572            Manifest.permission.READ_EXTERNAL_STORAGE,
573            Manifest.permission.WRITE_EXTERNAL_STORAGE,
574            Manifest.permission.READ_PHONE_NUMBER,
575            Manifest.permission.ANSWER_PHONE_CALLS);
576
577
578    /**
579     * Version number for the package parser cache. Increment this whenever the format or
580     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
581     */
582    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
583
584    /**
585     * Whether the package parser cache is enabled.
586     */
587    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
588
589    final ServiceThread mHandlerThread;
590
591    final PackageHandler mHandler;
592
593    private final ProcessLoggingHandler mProcessLoggingHandler;
594
595    /**
596     * Messages for {@link #mHandler} that need to wait for system ready before
597     * being dispatched.
598     */
599    private ArrayList<Message> mPostSystemReadyMessages;
600
601    final int mSdkVersion = Build.VERSION.SDK_INT;
602
603    final Context mContext;
604    final boolean mFactoryTest;
605    final boolean mOnlyCore;
606    final DisplayMetrics mMetrics;
607    final int mDefParseFlags;
608    final String[] mSeparateProcesses;
609    final boolean mIsUpgrade;
610    final boolean mIsPreNUpgrade;
611    final boolean mIsPreNMR1Upgrade;
612
613    @GuardedBy("mPackages")
614    private boolean mDexOptDialogShown;
615
616    /** The location for ASEC container files on internal storage. */
617    final String mAsecInternalPath;
618
619    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
620    // LOCK HELD.  Can be called with mInstallLock held.
621    @GuardedBy("mInstallLock")
622    final Installer mInstaller;
623
624    /** Directory where installed third-party apps stored */
625    final File mAppInstallDir;
626
627    /**
628     * Directory to which applications installed internally have their
629     * 32 bit native libraries copied.
630     */
631    private File mAppLib32InstallDir;
632
633    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
634    // apps.
635    final File mDrmAppPrivateInstallDir;
636
637    // ----------------------------------------------------------------
638
639    // Lock for state used when installing and doing other long running
640    // operations.  Methods that must be called with this lock held have
641    // the suffix "LI".
642    final Object mInstallLock = new Object();
643
644    // ----------------------------------------------------------------
645
646    // Keys are String (package name), values are Package.  This also serves
647    // as the lock for the global state.  Methods that must be called with
648    // this lock held have the prefix "LP".
649    @GuardedBy("mPackages")
650    final ArrayMap<String, PackageParser.Package> mPackages =
651            new ArrayMap<String, PackageParser.Package>();
652
653    final ArrayMap<String, Set<String>> mKnownCodebase =
654            new ArrayMap<String, Set<String>>();
655
656    // List of APK paths to load for each user and package. This data is never
657    // persisted by the package manager. Instead, the overlay manager will
658    // ensure the data is up-to-date in runtime.
659    @GuardedBy("mPackages")
660    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
661        new SparseArray<ArrayMap<String, ArrayList<String>>>();
662
663    /**
664     * Tracks new system packages [received in an OTA] that we expect to
665     * find updated user-installed versions. Keys are package name, values
666     * are package location.
667     */
668    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
669    /**
670     * Tracks high priority intent filters for protected actions. During boot, certain
671     * filter actions are protected and should never be allowed to have a high priority
672     * intent filter for them. However, there is one, and only one exception -- the
673     * setup wizard. It must be able to define a high priority intent filter for these
674     * actions to ensure there are no escapes from the wizard. We need to delay processing
675     * of these during boot as we need to look at all of the system packages in order
676     * to know which component is the setup wizard.
677     */
678    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
679    /**
680     * Whether or not processing protected filters should be deferred.
681     */
682    private boolean mDeferProtectedFilters = true;
683
684    /**
685     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
686     */
687    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
688    /**
689     * Whether or not system app permissions should be promoted from install to runtime.
690     */
691    boolean mPromoteSystemApps;
692
693    @GuardedBy("mPackages")
694    final Settings mSettings;
695
696    /**
697     * Set of package names that are currently "frozen", which means active
698     * surgery is being done on the code/data for that package. The platform
699     * will refuse to launch frozen packages to avoid race conditions.
700     *
701     * @see PackageFreezer
702     */
703    @GuardedBy("mPackages")
704    final ArraySet<String> mFrozenPackages = new ArraySet<>();
705
706    final ProtectedPackages mProtectedPackages;
707
708    boolean mFirstBoot;
709
710    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
711
712    // System configuration read by SystemConfig.
713    final int[] mGlobalGids;
714    final SparseArray<ArraySet<String>> mSystemPermissions;
715    @GuardedBy("mAvailableFeatures")
716    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
717
718    // If mac_permissions.xml was found for seinfo labeling.
719    boolean mFoundPolicyFile;
720
721    private final InstantAppRegistry mInstantAppRegistry;
722
723    @GuardedBy("mPackages")
724    int mChangedPackagesSequenceNumber;
725    /**
726     * List of changed [installed, removed or updated] packages.
727     * mapping from user id -> sequence number -> package name
728     */
729    @GuardedBy("mPackages")
730    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
731    /**
732     * The sequence number of the last change to a package.
733     * mapping from user id -> package name -> sequence number
734     */
735    @GuardedBy("mPackages")
736    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
737
738    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
739        @Override public boolean hasFeature(String feature) {
740            return PackageManagerService.this.hasSystemFeature(feature, 0);
741        }
742    };
743
744    public static final class SharedLibraryEntry {
745        public final String path;
746        public final String apk;
747        public final SharedLibraryInfo info;
748
749        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
750                String declaringPackageName, int declaringPackageVersionCode) {
751            path = _path;
752            apk = _apk;
753            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
754                    declaringPackageName, declaringPackageVersionCode), null);
755        }
756    }
757
758    // Currently known shared libraries.
759    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
760    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
761            new ArrayMap<>();
762
763    // All available activities, for your resolving pleasure.
764    final ActivityIntentResolver mActivities =
765            new ActivityIntentResolver();
766
767    // All available receivers, for your resolving pleasure.
768    final ActivityIntentResolver mReceivers =
769            new ActivityIntentResolver();
770
771    // All available services, for your resolving pleasure.
772    final ServiceIntentResolver mServices = new ServiceIntentResolver();
773
774    // All available providers, for your resolving pleasure.
775    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
776
777    // Mapping from provider base names (first directory in content URI codePath)
778    // to the provider information.
779    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
780            new ArrayMap<String, PackageParser.Provider>();
781
782    // Mapping from instrumentation class names to info about them.
783    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
784            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
785
786    // Mapping from permission names to info about them.
787    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
788            new ArrayMap<String, PackageParser.PermissionGroup>();
789
790    // Packages whose data we have transfered into another package, thus
791    // should no longer exist.
792    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
793
794    // Broadcast actions that are only available to the system.
795    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
796
797    /** List of packages waiting for verification. */
798    final SparseArray<PackageVerificationState> mPendingVerification
799            = new SparseArray<PackageVerificationState>();
800
801    /** Set of packages associated with each app op permission. */
802    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
803
804    final PackageInstallerService mInstallerService;
805
806    private final PackageDexOptimizer mPackageDexOptimizer;
807    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
808    // is used by other apps).
809    private final DexManager mDexManager;
810
811    private AtomicInteger mNextMoveId = new AtomicInteger();
812    private final MoveCallbacks mMoveCallbacks;
813
814    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
815
816    // Cache of users who need badging.
817    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
818
819    /** Token for keys in mPendingVerification. */
820    private int mPendingVerificationToken = 0;
821
822    volatile boolean mSystemReady;
823    volatile boolean mSafeMode;
824    volatile boolean mHasSystemUidErrors;
825
826    ApplicationInfo mAndroidApplication;
827    final ActivityInfo mResolveActivity = new ActivityInfo();
828    final ResolveInfo mResolveInfo = new ResolveInfo();
829    ComponentName mResolveComponentName;
830    PackageParser.Package mPlatformPackage;
831    ComponentName mCustomResolverComponentName;
832
833    boolean mResolverReplaced = false;
834
835    private final @Nullable ComponentName mIntentFilterVerifierComponent;
836    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
837
838    private int mIntentFilterVerificationToken = 0;
839
840    /** The service connection to the ephemeral resolver */
841    final EphemeralResolverConnection mInstantAppResolverConnection;
842
843    /** Component used to install ephemeral applications */
844    ComponentName mInstantAppInstallerComponent;
845    ActivityInfo mInstantAppInstallerActivity;
846    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
847
848    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
849            = new SparseArray<IntentFilterVerificationState>();
850
851    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
852
853    // List of packages names to keep cached, even if they are uninstalled for all users
854    private List<String> mKeepUninstalledPackages;
855
856    private UserManagerInternal mUserManagerInternal;
857
858    private DeviceIdleController.LocalService mDeviceIdleController;
859
860    private File mCacheDir;
861
862    private ArraySet<String> mPrivappPermissionsViolations;
863
864    private Future<?> mPrepareAppDataFuture;
865
866    private static class IFVerificationParams {
867        PackageParser.Package pkg;
868        boolean replacing;
869        int userId;
870        int verifierUid;
871
872        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
873                int _userId, int _verifierUid) {
874            pkg = _pkg;
875            replacing = _replacing;
876            userId = _userId;
877            replacing = _replacing;
878            verifierUid = _verifierUid;
879        }
880    }
881
882    private interface IntentFilterVerifier<T extends IntentFilter> {
883        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
884                                               T filter, String packageName);
885        void startVerifications(int userId);
886        void receiveVerificationResponse(int verificationId);
887    }
888
889    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
890        private Context mContext;
891        private ComponentName mIntentFilterVerifierComponent;
892        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
893
894        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
895            mContext = context;
896            mIntentFilterVerifierComponent = verifierComponent;
897        }
898
899        private String getDefaultScheme() {
900            return IntentFilter.SCHEME_HTTPS;
901        }
902
903        @Override
904        public void startVerifications(int userId) {
905            // Launch verifications requests
906            int count = mCurrentIntentFilterVerifications.size();
907            for (int n=0; n<count; n++) {
908                int verificationId = mCurrentIntentFilterVerifications.get(n);
909                final IntentFilterVerificationState ivs =
910                        mIntentFilterVerificationStates.get(verificationId);
911
912                String packageName = ivs.getPackageName();
913
914                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
915                final int filterCount = filters.size();
916                ArraySet<String> domainsSet = new ArraySet<>();
917                for (int m=0; m<filterCount; m++) {
918                    PackageParser.ActivityIntentInfo filter = filters.get(m);
919                    domainsSet.addAll(filter.getHostsList());
920                }
921                synchronized (mPackages) {
922                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
923                            packageName, domainsSet) != null) {
924                        scheduleWriteSettingsLocked();
925                    }
926                }
927                sendVerificationRequest(userId, verificationId, ivs);
928            }
929            mCurrentIntentFilterVerifications.clear();
930        }
931
932        private void sendVerificationRequest(int userId, int verificationId,
933                IntentFilterVerificationState ivs) {
934
935            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
936            verificationIntent.putExtra(
937                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
938                    verificationId);
939            verificationIntent.putExtra(
940                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
941                    getDefaultScheme());
942            verificationIntent.putExtra(
943                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
944                    ivs.getHostsString());
945            verificationIntent.putExtra(
946                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
947                    ivs.getPackageName());
948            verificationIntent.setComponent(mIntentFilterVerifierComponent);
949            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
950
951            UserHandle user = new UserHandle(userId);
952            mContext.sendBroadcastAsUser(verificationIntent, user);
953            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
954                    "Sending IntentFilter verification broadcast");
955        }
956
957        public void receiveVerificationResponse(int verificationId) {
958            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
959
960            final boolean verified = ivs.isVerified();
961
962            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
963            final int count = filters.size();
964            if (DEBUG_DOMAIN_VERIFICATION) {
965                Slog.i(TAG, "Received verification response " + verificationId
966                        + " for " + count + " filters, verified=" + verified);
967            }
968            for (int n=0; n<count; n++) {
969                PackageParser.ActivityIntentInfo filter = filters.get(n);
970                filter.setVerified(verified);
971
972                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
973                        + " verified with result:" + verified + " and hosts:"
974                        + ivs.getHostsString());
975            }
976
977            mIntentFilterVerificationStates.remove(verificationId);
978
979            final String packageName = ivs.getPackageName();
980            IntentFilterVerificationInfo ivi = null;
981
982            synchronized (mPackages) {
983                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
984            }
985            if (ivi == null) {
986                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
987                        + verificationId + " packageName:" + packageName);
988                return;
989            }
990            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
991                    "Updating IntentFilterVerificationInfo for package " + packageName
992                            +" verificationId:" + verificationId);
993
994            synchronized (mPackages) {
995                if (verified) {
996                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
997                } else {
998                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
999                }
1000                scheduleWriteSettingsLocked();
1001
1002                final int userId = ivs.getUserId();
1003                if (userId != UserHandle.USER_ALL) {
1004                    final int userStatus =
1005                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1006
1007                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1008                    boolean needUpdate = false;
1009
1010                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1011                    // already been set by the User thru the Disambiguation dialog
1012                    switch (userStatus) {
1013                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1014                            if (verified) {
1015                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1016                            } else {
1017                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1018                            }
1019                            needUpdate = true;
1020                            break;
1021
1022                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1023                            if (verified) {
1024                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1025                                needUpdate = true;
1026                            }
1027                            break;
1028
1029                        default:
1030                            // Nothing to do
1031                    }
1032
1033                    if (needUpdate) {
1034                        mSettings.updateIntentFilterVerificationStatusLPw(
1035                                packageName, updatedStatus, userId);
1036                        scheduleWritePackageRestrictionsLocked(userId);
1037                    }
1038                }
1039            }
1040        }
1041
1042        @Override
1043        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1044                    ActivityIntentInfo filter, String packageName) {
1045            if (!hasValidDomains(filter)) {
1046                return false;
1047            }
1048            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1049            if (ivs == null) {
1050                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1051                        packageName);
1052            }
1053            if (DEBUG_DOMAIN_VERIFICATION) {
1054                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1055            }
1056            ivs.addFilter(filter);
1057            return true;
1058        }
1059
1060        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1061                int userId, int verificationId, String packageName) {
1062            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1063                    verifierUid, userId, packageName);
1064            ivs.setPendingState();
1065            synchronized (mPackages) {
1066                mIntentFilterVerificationStates.append(verificationId, ivs);
1067                mCurrentIntentFilterVerifications.add(verificationId);
1068            }
1069            return ivs;
1070        }
1071    }
1072
1073    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1074        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1075                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1076                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1077    }
1078
1079    // Set of pending broadcasts for aggregating enable/disable of components.
1080    static class PendingPackageBroadcasts {
1081        // for each user id, a map of <package name -> components within that package>
1082        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1083
1084        public PendingPackageBroadcasts() {
1085            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1086        }
1087
1088        public ArrayList<String> get(int userId, String packageName) {
1089            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1090            return packages.get(packageName);
1091        }
1092
1093        public void put(int userId, String packageName, ArrayList<String> components) {
1094            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1095            packages.put(packageName, components);
1096        }
1097
1098        public void remove(int userId, String packageName) {
1099            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1100            if (packages != null) {
1101                packages.remove(packageName);
1102            }
1103        }
1104
1105        public void remove(int userId) {
1106            mUidMap.remove(userId);
1107        }
1108
1109        public int userIdCount() {
1110            return mUidMap.size();
1111        }
1112
1113        public int userIdAt(int n) {
1114            return mUidMap.keyAt(n);
1115        }
1116
1117        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1118            return mUidMap.get(userId);
1119        }
1120
1121        public int size() {
1122            // total number of pending broadcast entries across all userIds
1123            int num = 0;
1124            for (int i = 0; i< mUidMap.size(); i++) {
1125                num += mUidMap.valueAt(i).size();
1126            }
1127            return num;
1128        }
1129
1130        public void clear() {
1131            mUidMap.clear();
1132        }
1133
1134        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1135            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1136            if (map == null) {
1137                map = new ArrayMap<String, ArrayList<String>>();
1138                mUidMap.put(userId, map);
1139            }
1140            return map;
1141        }
1142    }
1143    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1144
1145    // Service Connection to remote media container service to copy
1146    // package uri's from external media onto secure containers
1147    // or internal storage.
1148    private IMediaContainerService mContainerService = null;
1149
1150    static final int SEND_PENDING_BROADCAST = 1;
1151    static final int MCS_BOUND = 3;
1152    static final int END_COPY = 4;
1153    static final int INIT_COPY = 5;
1154    static final int MCS_UNBIND = 6;
1155    static final int START_CLEANING_PACKAGE = 7;
1156    static final int FIND_INSTALL_LOC = 8;
1157    static final int POST_INSTALL = 9;
1158    static final int MCS_RECONNECT = 10;
1159    static final int MCS_GIVE_UP = 11;
1160    static final int UPDATED_MEDIA_STATUS = 12;
1161    static final int WRITE_SETTINGS = 13;
1162    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1163    static final int PACKAGE_VERIFIED = 15;
1164    static final int CHECK_PENDING_VERIFICATION = 16;
1165    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1166    static final int INTENT_FILTER_VERIFIED = 18;
1167    static final int WRITE_PACKAGE_LIST = 19;
1168    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1169
1170    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1171
1172    // Delay time in millisecs
1173    static final int BROADCAST_DELAY = 10 * 1000;
1174
1175    static UserManagerService sUserManager;
1176
1177    // Stores a list of users whose package restrictions file needs to be updated
1178    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1179
1180    final private DefaultContainerConnection mDefContainerConn =
1181            new DefaultContainerConnection();
1182    class DefaultContainerConnection implements ServiceConnection {
1183        public void onServiceConnected(ComponentName name, IBinder service) {
1184            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1185            final IMediaContainerService imcs = IMediaContainerService.Stub
1186                    .asInterface(Binder.allowBlocking(service));
1187            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1188        }
1189
1190        public void onServiceDisconnected(ComponentName name) {
1191            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1192        }
1193    }
1194
1195    // Recordkeeping of restore-after-install operations that are currently in flight
1196    // between the Package Manager and the Backup Manager
1197    static class PostInstallData {
1198        public InstallArgs args;
1199        public PackageInstalledInfo res;
1200
1201        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1202            args = _a;
1203            res = _r;
1204        }
1205    }
1206
1207    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1208    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1209
1210    // XML tags for backup/restore of various bits of state
1211    private static final String TAG_PREFERRED_BACKUP = "pa";
1212    private static final String TAG_DEFAULT_APPS = "da";
1213    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1214
1215    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1216    private static final String TAG_ALL_GRANTS = "rt-grants";
1217    private static final String TAG_GRANT = "grant";
1218    private static final String ATTR_PACKAGE_NAME = "pkg";
1219
1220    private static final String TAG_PERMISSION = "perm";
1221    private static final String ATTR_PERMISSION_NAME = "name";
1222    private static final String ATTR_IS_GRANTED = "g";
1223    private static final String ATTR_USER_SET = "set";
1224    private static final String ATTR_USER_FIXED = "fixed";
1225    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1226
1227    // System/policy permission grants are not backed up
1228    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1229            FLAG_PERMISSION_POLICY_FIXED
1230            | FLAG_PERMISSION_SYSTEM_FIXED
1231            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1232
1233    // And we back up these user-adjusted states
1234    private static final int USER_RUNTIME_GRANT_MASK =
1235            FLAG_PERMISSION_USER_SET
1236            | FLAG_PERMISSION_USER_FIXED
1237            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1238
1239    final @Nullable String mRequiredVerifierPackage;
1240    final @NonNull String mRequiredInstallerPackage;
1241    final @NonNull String mRequiredUninstallerPackage;
1242    final @Nullable String mSetupWizardPackage;
1243    final @Nullable String mStorageManagerPackage;
1244    final @NonNull String mServicesSystemSharedLibraryPackageName;
1245    final @NonNull String mSharedSystemSharedLibraryPackageName;
1246
1247    final boolean mPermissionReviewRequired;
1248
1249    private final PackageUsage mPackageUsage = new PackageUsage();
1250    private final CompilerStats mCompilerStats = new CompilerStats();
1251
1252    class PackageHandler extends Handler {
1253        private boolean mBound = false;
1254        final ArrayList<HandlerParams> mPendingInstalls =
1255            new ArrayList<HandlerParams>();
1256
1257        private boolean connectToService() {
1258            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1259                    " DefaultContainerService");
1260            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1261            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1263                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1264                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1265                mBound = true;
1266                return true;
1267            }
1268            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1269            return false;
1270        }
1271
1272        private void disconnectService() {
1273            mContainerService = null;
1274            mBound = false;
1275            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1276            mContext.unbindService(mDefContainerConn);
1277            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1278        }
1279
1280        PackageHandler(Looper looper) {
1281            super(looper);
1282        }
1283
1284        public void handleMessage(Message msg) {
1285            try {
1286                doHandleMessage(msg);
1287            } finally {
1288                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1289            }
1290        }
1291
1292        void doHandleMessage(Message msg) {
1293            switch (msg.what) {
1294                case INIT_COPY: {
1295                    HandlerParams params = (HandlerParams) msg.obj;
1296                    int idx = mPendingInstalls.size();
1297                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1298                    // If a bind was already initiated we dont really
1299                    // need to do anything. The pending install
1300                    // will be processed later on.
1301                    if (!mBound) {
1302                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1303                                System.identityHashCode(mHandler));
1304                        // If this is the only one pending we might
1305                        // have to bind to the service again.
1306                        if (!connectToService()) {
1307                            Slog.e(TAG, "Failed to bind to media container service");
1308                            params.serviceError();
1309                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1310                                    System.identityHashCode(mHandler));
1311                            if (params.traceMethod != null) {
1312                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1313                                        params.traceCookie);
1314                            }
1315                            return;
1316                        } else {
1317                            // Once we bind to the service, the first
1318                            // pending request will be processed.
1319                            mPendingInstalls.add(idx, params);
1320                        }
1321                    } else {
1322                        mPendingInstalls.add(idx, params);
1323                        // Already bound to the service. Just make
1324                        // sure we trigger off processing the first request.
1325                        if (idx == 0) {
1326                            mHandler.sendEmptyMessage(MCS_BOUND);
1327                        }
1328                    }
1329                    break;
1330                }
1331                case MCS_BOUND: {
1332                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1333                    if (msg.obj != null) {
1334                        mContainerService = (IMediaContainerService) msg.obj;
1335                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1336                                System.identityHashCode(mHandler));
1337                    }
1338                    if (mContainerService == null) {
1339                        if (!mBound) {
1340                            // Something seriously wrong since we are not bound and we are not
1341                            // waiting for connection. Bail out.
1342                            Slog.e(TAG, "Cannot bind to media container service");
1343                            for (HandlerParams params : mPendingInstalls) {
1344                                // Indicate service bind error
1345                                params.serviceError();
1346                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1347                                        System.identityHashCode(params));
1348                                if (params.traceMethod != null) {
1349                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1350                                            params.traceMethod, params.traceCookie);
1351                                }
1352                                return;
1353                            }
1354                            mPendingInstalls.clear();
1355                        } else {
1356                            Slog.w(TAG, "Waiting to connect to media container service");
1357                        }
1358                    } else if (mPendingInstalls.size() > 0) {
1359                        HandlerParams params = mPendingInstalls.get(0);
1360                        if (params != null) {
1361                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1362                                    System.identityHashCode(params));
1363                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1364                            if (params.startCopy()) {
1365                                // We are done...  look for more work or to
1366                                // go idle.
1367                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1368                                        "Checking for more work or unbind...");
1369                                // Delete pending install
1370                                if (mPendingInstalls.size() > 0) {
1371                                    mPendingInstalls.remove(0);
1372                                }
1373                                if (mPendingInstalls.size() == 0) {
1374                                    if (mBound) {
1375                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1376                                                "Posting delayed MCS_UNBIND");
1377                                        removeMessages(MCS_UNBIND);
1378                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1379                                        // Unbind after a little delay, to avoid
1380                                        // continual thrashing.
1381                                        sendMessageDelayed(ubmsg, 10000);
1382                                    }
1383                                } else {
1384                                    // There are more pending requests in queue.
1385                                    // Just post MCS_BOUND message to trigger processing
1386                                    // of next pending install.
1387                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1388                                            "Posting MCS_BOUND for next work");
1389                                    mHandler.sendEmptyMessage(MCS_BOUND);
1390                                }
1391                            }
1392                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1393                        }
1394                    } else {
1395                        // Should never happen ideally.
1396                        Slog.w(TAG, "Empty queue");
1397                    }
1398                    break;
1399                }
1400                case MCS_RECONNECT: {
1401                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1402                    if (mPendingInstalls.size() > 0) {
1403                        if (mBound) {
1404                            disconnectService();
1405                        }
1406                        if (!connectToService()) {
1407                            Slog.e(TAG, "Failed to bind to media container service");
1408                            for (HandlerParams params : mPendingInstalls) {
1409                                // Indicate service bind error
1410                                params.serviceError();
1411                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1412                                        System.identityHashCode(params));
1413                            }
1414                            mPendingInstalls.clear();
1415                        }
1416                    }
1417                    break;
1418                }
1419                case MCS_UNBIND: {
1420                    // If there is no actual work left, then time to unbind.
1421                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1422
1423                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1424                        if (mBound) {
1425                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1426
1427                            disconnectService();
1428                        }
1429                    } else if (mPendingInstalls.size() > 0) {
1430                        // There are more pending requests in queue.
1431                        // Just post MCS_BOUND message to trigger processing
1432                        // of next pending install.
1433                        mHandler.sendEmptyMessage(MCS_BOUND);
1434                    }
1435
1436                    break;
1437                }
1438                case MCS_GIVE_UP: {
1439                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1440                    HandlerParams params = mPendingInstalls.remove(0);
1441                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1442                            System.identityHashCode(params));
1443                    break;
1444                }
1445                case SEND_PENDING_BROADCAST: {
1446                    String packages[];
1447                    ArrayList<String> components[];
1448                    int size = 0;
1449                    int uids[];
1450                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1451                    synchronized (mPackages) {
1452                        if (mPendingBroadcasts == null) {
1453                            return;
1454                        }
1455                        size = mPendingBroadcasts.size();
1456                        if (size <= 0) {
1457                            // Nothing to be done. Just return
1458                            return;
1459                        }
1460                        packages = new String[size];
1461                        components = new ArrayList[size];
1462                        uids = new int[size];
1463                        int i = 0;  // filling out the above arrays
1464
1465                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1466                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1467                            Iterator<Map.Entry<String, ArrayList<String>>> it
1468                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1469                                            .entrySet().iterator();
1470                            while (it.hasNext() && i < size) {
1471                                Map.Entry<String, ArrayList<String>> ent = it.next();
1472                                packages[i] = ent.getKey();
1473                                components[i] = ent.getValue();
1474                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1475                                uids[i] = (ps != null)
1476                                        ? UserHandle.getUid(packageUserId, ps.appId)
1477                                        : -1;
1478                                i++;
1479                            }
1480                        }
1481                        size = i;
1482                        mPendingBroadcasts.clear();
1483                    }
1484                    // Send broadcasts
1485                    for (int i = 0; i < size; i++) {
1486                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                    break;
1490                }
1491                case START_CLEANING_PACKAGE: {
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1493                    final String packageName = (String)msg.obj;
1494                    final int userId = msg.arg1;
1495                    final boolean andCode = msg.arg2 != 0;
1496                    synchronized (mPackages) {
1497                        if (userId == UserHandle.USER_ALL) {
1498                            int[] users = sUserManager.getUserIds();
1499                            for (int user : users) {
1500                                mSettings.addPackageToCleanLPw(
1501                                        new PackageCleanItem(user, packageName, andCode));
1502                            }
1503                        } else {
1504                            mSettings.addPackageToCleanLPw(
1505                                    new PackageCleanItem(userId, packageName, andCode));
1506                        }
1507                    }
1508                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1509                    startCleaningPackages();
1510                } break;
1511                case POST_INSTALL: {
1512                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1513
1514                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1515                    final boolean didRestore = (msg.arg2 != 0);
1516                    mRunningInstalls.delete(msg.arg1);
1517
1518                    if (data != null) {
1519                        InstallArgs args = data.args;
1520                        PackageInstalledInfo parentRes = data.res;
1521
1522                        final boolean grantPermissions = (args.installFlags
1523                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1524                        final boolean killApp = (args.installFlags
1525                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1526                        final String[] grantedPermissions = args.installGrantPermissions;
1527
1528                        // Handle the parent package
1529                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1530                                grantedPermissions, didRestore, args.installerPackageName,
1531                                args.observer);
1532
1533                        // Handle the child packages
1534                        final int childCount = (parentRes.addedChildPackages != null)
1535                                ? parentRes.addedChildPackages.size() : 0;
1536                        for (int i = 0; i < childCount; i++) {
1537                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1538                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1539                                    grantedPermissions, false, args.installerPackageName,
1540                                    args.observer);
1541                        }
1542
1543                        // Log tracing if needed
1544                        if (args.traceMethod != null) {
1545                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1546                                    args.traceCookie);
1547                        }
1548                    } else {
1549                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1550                    }
1551
1552                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1553                } break;
1554                case UPDATED_MEDIA_STATUS: {
1555                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1556                    boolean reportStatus = msg.arg1 == 1;
1557                    boolean doGc = msg.arg2 == 1;
1558                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1559                    if (doGc) {
1560                        // Force a gc to clear up stale containers.
1561                        Runtime.getRuntime().gc();
1562                    }
1563                    if (msg.obj != null) {
1564                        @SuppressWarnings("unchecked")
1565                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1566                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1567                        // Unload containers
1568                        unloadAllContainers(args);
1569                    }
1570                    if (reportStatus) {
1571                        try {
1572                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1573                                    "Invoking StorageManagerService call back");
1574                            PackageHelper.getStorageManager().finishMediaUpdate();
1575                        } catch (RemoteException e) {
1576                            Log.e(TAG, "StorageManagerService not running?");
1577                        }
1578                    }
1579                } break;
1580                case WRITE_SETTINGS: {
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1582                    synchronized (mPackages) {
1583                        removeMessages(WRITE_SETTINGS);
1584                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1585                        mSettings.writeLPr();
1586                        mDirtyUsers.clear();
1587                    }
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1589                } break;
1590                case WRITE_PACKAGE_RESTRICTIONS: {
1591                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1592                    synchronized (mPackages) {
1593                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1594                        for (int userId : mDirtyUsers) {
1595                            mSettings.writePackageRestrictionsLPr(userId);
1596                        }
1597                        mDirtyUsers.clear();
1598                    }
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1600                } break;
1601                case WRITE_PACKAGE_LIST: {
1602                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603                    synchronized (mPackages) {
1604                        removeMessages(WRITE_PACKAGE_LIST);
1605                        mSettings.writePackageListLPr(msg.arg1);
1606                    }
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1608                } break;
1609                case CHECK_PENDING_VERIFICATION: {
1610                    final int verificationId = msg.arg1;
1611                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1612
1613                    if ((state != null) && !state.timeoutExtended()) {
1614                        final InstallArgs args = state.getInstallArgs();
1615                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1616
1617                        Slog.i(TAG, "Verification timed out for " + originUri);
1618                        mPendingVerification.remove(verificationId);
1619
1620                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1621
1622                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1623                            Slog.i(TAG, "Continuing with installation of " + originUri);
1624                            state.setVerifierResponse(Binder.getCallingUid(),
1625                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1626                            broadcastPackageVerified(verificationId, originUri,
1627                                    PackageManager.VERIFICATION_ALLOW,
1628                                    state.getInstallArgs().getUser());
1629                            try {
1630                                ret = args.copyApk(mContainerService, true);
1631                            } catch (RemoteException e) {
1632                                Slog.e(TAG, "Could not contact the ContainerService");
1633                            }
1634                        } else {
1635                            broadcastPackageVerified(verificationId, originUri,
1636                                    PackageManager.VERIFICATION_REJECT,
1637                                    state.getInstallArgs().getUser());
1638                        }
1639
1640                        Trace.asyncTraceEnd(
1641                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1642
1643                        processPendingInstall(args, ret);
1644                        mHandler.sendEmptyMessage(MCS_UNBIND);
1645                    }
1646                    break;
1647                }
1648                case PACKAGE_VERIFIED: {
1649                    final int verificationId = msg.arg1;
1650
1651                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1652                    if (state == null) {
1653                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1654                        break;
1655                    }
1656
1657                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1658
1659                    state.setVerifierResponse(response.callerUid, response.code);
1660
1661                    if (state.isVerificationComplete()) {
1662                        mPendingVerification.remove(verificationId);
1663
1664                        final InstallArgs args = state.getInstallArgs();
1665                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1666
1667                        int ret;
1668                        if (state.isInstallAllowed()) {
1669                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1670                            broadcastPackageVerified(verificationId, originUri,
1671                                    response.code, state.getInstallArgs().getUser());
1672                            try {
1673                                ret = args.copyApk(mContainerService, true);
1674                            } catch (RemoteException e) {
1675                                Slog.e(TAG, "Could not contact the ContainerService");
1676                            }
1677                        } else {
1678                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1679                        }
1680
1681                        Trace.asyncTraceEnd(
1682                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1683
1684                        processPendingInstall(args, ret);
1685                        mHandler.sendEmptyMessage(MCS_UNBIND);
1686                    }
1687
1688                    break;
1689                }
1690                case START_INTENT_FILTER_VERIFICATIONS: {
1691                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1692                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1693                            params.replacing, params.pkg);
1694                    break;
1695                }
1696                case INTENT_FILTER_VERIFIED: {
1697                    final int verificationId = msg.arg1;
1698
1699                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1700                            verificationId);
1701                    if (state == null) {
1702                        Slog.w(TAG, "Invalid IntentFilter verification token "
1703                                + verificationId + " received");
1704                        break;
1705                    }
1706
1707                    final int userId = state.getUserId();
1708
1709                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1710                            "Processing IntentFilter verification with token:"
1711                            + verificationId + " and userId:" + userId);
1712
1713                    final IntentFilterVerificationResponse response =
1714                            (IntentFilterVerificationResponse) msg.obj;
1715
1716                    state.setVerifierResponse(response.callerUid, response.code);
1717
1718                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1719                            "IntentFilter verification with token:" + verificationId
1720                            + " and userId:" + userId
1721                            + " is settings verifier response with response code:"
1722                            + response.code);
1723
1724                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1725                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1726                                + response.getFailedDomainsString());
1727                    }
1728
1729                    if (state.isVerificationComplete()) {
1730                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1731                    } else {
1732                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1733                                "IntentFilter verification with token:" + verificationId
1734                                + " was not said to be complete");
1735                    }
1736
1737                    break;
1738                }
1739                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1740                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1741                            mInstantAppResolverConnection,
1742                            (InstantAppRequest) msg.obj,
1743                            mInstantAppInstallerActivity,
1744                            mHandler);
1745                }
1746            }
1747        }
1748    }
1749
1750    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1751            boolean killApp, String[] grantedPermissions,
1752            boolean launchedForRestore, String installerPackage,
1753            IPackageInstallObserver2 installObserver) {
1754        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1755            // Send the removed broadcasts
1756            if (res.removedInfo != null) {
1757                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1758            }
1759
1760            // Now that we successfully installed the package, grant runtime
1761            // permissions if requested before broadcasting the install. Also
1762            // for legacy apps in permission review mode we clear the permission
1763            // review flag which is used to emulate runtime permissions for
1764            // legacy apps.
1765            if (grantPermissions) {
1766                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1767            }
1768
1769            final boolean update = res.removedInfo != null
1770                    && res.removedInfo.removedPackage != null;
1771
1772            // If this is the first time we have child packages for a disabled privileged
1773            // app that had no children, we grant requested runtime permissions to the new
1774            // children if the parent on the system image had them already granted.
1775            if (res.pkg.parentPackage != null) {
1776                synchronized (mPackages) {
1777                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1778                }
1779            }
1780
1781            synchronized (mPackages) {
1782                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1783            }
1784
1785            final String packageName = res.pkg.applicationInfo.packageName;
1786
1787            // Determine the set of users who are adding this package for
1788            // the first time vs. those who are seeing an update.
1789            int[] firstUsers = EMPTY_INT_ARRAY;
1790            int[] updateUsers = EMPTY_INT_ARRAY;
1791            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1792            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1793            for (int newUser : res.newUsers) {
1794                if (ps.getInstantApp(newUser)) {
1795                    continue;
1796                }
1797                if (allNewUsers) {
1798                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1799                    continue;
1800                }
1801                boolean isNew = true;
1802                for (int origUser : res.origUsers) {
1803                    if (origUser == newUser) {
1804                        isNew = false;
1805                        break;
1806                    }
1807                }
1808                if (isNew) {
1809                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1810                } else {
1811                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1812                }
1813            }
1814
1815            // Send installed broadcasts if the package is not a static shared lib.
1816            if (res.pkg.staticSharedLibName == null) {
1817                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1818
1819                // Send added for users that see the package for the first time
1820                // sendPackageAddedForNewUsers also deals with system apps
1821                int appId = UserHandle.getAppId(res.uid);
1822                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1823                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1824
1825                // Send added for users that don't see the package for the first time
1826                Bundle extras = new Bundle(1);
1827                extras.putInt(Intent.EXTRA_UID, res.uid);
1828                if (update) {
1829                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1830                }
1831                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1832                        extras, 0 /*flags*/, null /*targetPackage*/,
1833                        null /*finishedReceiver*/, updateUsers);
1834
1835                // Send replaced for users that don't see the package for the first time
1836                if (update) {
1837                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1838                            packageName, extras, 0 /*flags*/,
1839                            null /*targetPackage*/, null /*finishedReceiver*/,
1840                            updateUsers);
1841                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1842                            null /*package*/, null /*extras*/, 0 /*flags*/,
1843                            packageName /*targetPackage*/,
1844                            null /*finishedReceiver*/, updateUsers);
1845                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1846                    // First-install and we did a restore, so we're responsible for the
1847                    // first-launch broadcast.
1848                    if (DEBUG_BACKUP) {
1849                        Slog.i(TAG, "Post-restore of " + packageName
1850                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1851                    }
1852                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1853                }
1854
1855                // Send broadcast package appeared if forward locked/external for all users
1856                // treat asec-hosted packages like removable media on upgrade
1857                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1858                    if (DEBUG_INSTALL) {
1859                        Slog.i(TAG, "upgrading pkg " + res.pkg
1860                                + " is ASEC-hosted -> AVAILABLE");
1861                    }
1862                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1863                    ArrayList<String> pkgList = new ArrayList<>(1);
1864                    pkgList.add(packageName);
1865                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1866                }
1867            }
1868
1869            // Work that needs to happen on first install within each user
1870            if (firstUsers != null && firstUsers.length > 0) {
1871                synchronized (mPackages) {
1872                    for (int userId : firstUsers) {
1873                        // If this app is a browser and it's newly-installed for some
1874                        // users, clear any default-browser state in those users. The
1875                        // app's nature doesn't depend on the user, so we can just check
1876                        // its browser nature in any user and generalize.
1877                        if (packageIsBrowser(packageName, userId)) {
1878                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1879                        }
1880
1881                        // We may also need to apply pending (restored) runtime
1882                        // permission grants within these users.
1883                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1884                    }
1885                }
1886            }
1887
1888            // Log current value of "unknown sources" setting
1889            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1890                    getUnknownSourcesSettings());
1891
1892            // Force a gc to clear up things
1893            Runtime.getRuntime().gc();
1894
1895            // Remove the replaced package's older resources safely now
1896            // We delete after a gc for applications  on sdcard.
1897            if (res.removedInfo != null && res.removedInfo.args != null) {
1898                synchronized (mInstallLock) {
1899                    res.removedInfo.args.doPostDeleteLI(true);
1900                }
1901            }
1902
1903            // Notify DexManager that the package was installed for new users.
1904            // The updated users should already be indexed and the package code paths
1905            // should not change.
1906            // Don't notify the manager for ephemeral apps as they are not expected to
1907            // survive long enough to benefit of background optimizations.
1908            for (int userId : firstUsers) {
1909                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1910                mDexManager.notifyPackageInstalled(info, userId);
1911            }
1912        }
1913
1914        // If someone is watching installs - notify them
1915        if (installObserver != null) {
1916            try {
1917                Bundle extras = extrasForInstallResult(res);
1918                installObserver.onPackageInstalled(res.name, res.returnCode,
1919                        res.returnMsg, extras);
1920            } catch (RemoteException e) {
1921                Slog.i(TAG, "Observer no longer exists.");
1922            }
1923        }
1924    }
1925
1926    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1927            PackageParser.Package pkg) {
1928        if (pkg.parentPackage == null) {
1929            return;
1930        }
1931        if (pkg.requestedPermissions == null) {
1932            return;
1933        }
1934        final PackageSetting disabledSysParentPs = mSettings
1935                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1936        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1937                || !disabledSysParentPs.isPrivileged()
1938                || (disabledSysParentPs.childPackageNames != null
1939                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1940            return;
1941        }
1942        final int[] allUserIds = sUserManager.getUserIds();
1943        final int permCount = pkg.requestedPermissions.size();
1944        for (int i = 0; i < permCount; i++) {
1945            String permission = pkg.requestedPermissions.get(i);
1946            BasePermission bp = mSettings.mPermissions.get(permission);
1947            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1948                continue;
1949            }
1950            for (int userId : allUserIds) {
1951                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1952                        permission, userId)) {
1953                    grantRuntimePermission(pkg.packageName, permission, userId);
1954                }
1955            }
1956        }
1957    }
1958
1959    private StorageEventListener mStorageListener = new StorageEventListener() {
1960        @Override
1961        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1962            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1963                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1964                    final String volumeUuid = vol.getFsUuid();
1965
1966                    // Clean up any users or apps that were removed or recreated
1967                    // while this volume was missing
1968                    sUserManager.reconcileUsers(volumeUuid);
1969                    reconcileApps(volumeUuid);
1970
1971                    // Clean up any install sessions that expired or were
1972                    // cancelled while this volume was missing
1973                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1974
1975                    loadPrivatePackages(vol);
1976
1977                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1978                    unloadPrivatePackages(vol);
1979                }
1980            }
1981
1982            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1983                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1984                    updateExternalMediaStatus(true, false);
1985                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1986                    updateExternalMediaStatus(false, false);
1987                }
1988            }
1989        }
1990
1991        @Override
1992        public void onVolumeForgotten(String fsUuid) {
1993            if (TextUtils.isEmpty(fsUuid)) {
1994                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1995                return;
1996            }
1997
1998            // Remove any apps installed on the forgotten volume
1999            synchronized (mPackages) {
2000                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2001                for (PackageSetting ps : packages) {
2002                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2003                    deletePackageVersioned(new VersionedPackage(ps.name,
2004                            PackageManager.VERSION_CODE_HIGHEST),
2005                            new LegacyPackageDeleteObserver(null).getBinder(),
2006                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2007                    // Try very hard to release any references to this package
2008                    // so we don't risk the system server being killed due to
2009                    // open FDs
2010                    AttributeCache.instance().removePackage(ps.name);
2011                }
2012
2013                mSettings.onVolumeForgotten(fsUuid);
2014                mSettings.writeLPr();
2015            }
2016        }
2017    };
2018
2019    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2020            String[] grantedPermissions) {
2021        for (int userId : userIds) {
2022            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2023        }
2024    }
2025
2026    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2027            String[] grantedPermissions) {
2028        SettingBase sb = (SettingBase) pkg.mExtras;
2029        if (sb == null) {
2030            return;
2031        }
2032
2033        PermissionsState permissionsState = sb.getPermissionsState();
2034
2035        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2036                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2037
2038        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2039                >= Build.VERSION_CODES.M;
2040
2041        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2042
2043        for (String permission : pkg.requestedPermissions) {
2044            final BasePermission bp;
2045            synchronized (mPackages) {
2046                bp = mSettings.mPermissions.get(permission);
2047            }
2048            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2049                    && (!instantApp || bp.isInstant())
2050                    && (grantedPermissions == null
2051                           || ArrayUtils.contains(grantedPermissions, permission))) {
2052                final int flags = permissionsState.getPermissionFlags(permission, userId);
2053                if (supportsRuntimePermissions) {
2054                    // Installer cannot change immutable permissions.
2055                    if ((flags & immutableFlags) == 0) {
2056                        grantRuntimePermission(pkg.packageName, permission, userId);
2057                    }
2058                } else if (mPermissionReviewRequired) {
2059                    // In permission review mode we clear the review flag when we
2060                    // are asked to install the app with all permissions granted.
2061                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2062                        updatePermissionFlags(permission, pkg.packageName,
2063                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2064                    }
2065                }
2066            }
2067        }
2068    }
2069
2070    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2071        Bundle extras = null;
2072        switch (res.returnCode) {
2073            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2074                extras = new Bundle();
2075                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2076                        res.origPermission);
2077                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2078                        res.origPackage);
2079                break;
2080            }
2081            case PackageManager.INSTALL_SUCCEEDED: {
2082                extras = new Bundle();
2083                extras.putBoolean(Intent.EXTRA_REPLACING,
2084                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2085                break;
2086            }
2087        }
2088        return extras;
2089    }
2090
2091    void scheduleWriteSettingsLocked() {
2092        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2093            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2094        }
2095    }
2096
2097    void scheduleWritePackageListLocked(int userId) {
2098        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2099            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2100            msg.arg1 = userId;
2101            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2102        }
2103    }
2104
2105    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2106        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2107        scheduleWritePackageRestrictionsLocked(userId);
2108    }
2109
2110    void scheduleWritePackageRestrictionsLocked(int userId) {
2111        final int[] userIds = (userId == UserHandle.USER_ALL)
2112                ? sUserManager.getUserIds() : new int[]{userId};
2113        for (int nextUserId : userIds) {
2114            if (!sUserManager.exists(nextUserId)) return;
2115            mDirtyUsers.add(nextUserId);
2116            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2117                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2118            }
2119        }
2120    }
2121
2122    public static PackageManagerService main(Context context, Installer installer,
2123            boolean factoryTest, boolean onlyCore) {
2124        // Self-check for initial settings.
2125        PackageManagerServiceCompilerMapping.checkProperties();
2126
2127        PackageManagerService m = new PackageManagerService(context, installer,
2128                factoryTest, onlyCore);
2129        m.enableSystemUserPackages();
2130        ServiceManager.addService("package", m);
2131        return m;
2132    }
2133
2134    private void enableSystemUserPackages() {
2135        if (!UserManager.isSplitSystemUser()) {
2136            return;
2137        }
2138        // For system user, enable apps based on the following conditions:
2139        // - app is whitelisted or belong to one of these groups:
2140        //   -- system app which has no launcher icons
2141        //   -- system app which has INTERACT_ACROSS_USERS permission
2142        //   -- system IME app
2143        // - app is not in the blacklist
2144        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2145        Set<String> enableApps = new ArraySet<>();
2146        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2147                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2148                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2149        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2150        enableApps.addAll(wlApps);
2151        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2152                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2153        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2154        enableApps.removeAll(blApps);
2155        Log.i(TAG, "Applications installed for system user: " + enableApps);
2156        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2157                UserHandle.SYSTEM);
2158        final int allAppsSize = allAps.size();
2159        synchronized (mPackages) {
2160            for (int i = 0; i < allAppsSize; i++) {
2161                String pName = allAps.get(i);
2162                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2163                // Should not happen, but we shouldn't be failing if it does
2164                if (pkgSetting == null) {
2165                    continue;
2166                }
2167                boolean install = enableApps.contains(pName);
2168                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2169                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2170                            + " for system user");
2171                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2172                }
2173            }
2174            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2175        }
2176    }
2177
2178    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2179        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2180                Context.DISPLAY_SERVICE);
2181        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2182    }
2183
2184    /**
2185     * Requests that files preopted on a secondary system partition be copied to the data partition
2186     * if possible.  Note that the actual copying of the files is accomplished by init for security
2187     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2188     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2189     */
2190    private static void requestCopyPreoptedFiles() {
2191        final int WAIT_TIME_MS = 100;
2192        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2193        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2194            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2195            // We will wait for up to 100 seconds.
2196            final long timeStart = SystemClock.uptimeMillis();
2197            final long timeEnd = timeStart + 100 * 1000;
2198            long timeNow = timeStart;
2199            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2200                try {
2201                    Thread.sleep(WAIT_TIME_MS);
2202                } catch (InterruptedException e) {
2203                    // Do nothing
2204                }
2205                timeNow = SystemClock.uptimeMillis();
2206                if (timeNow > timeEnd) {
2207                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2208                    Slog.wtf(TAG, "cppreopt did not finish!");
2209                    break;
2210                }
2211            }
2212
2213            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2214        }
2215    }
2216
2217    public PackageManagerService(Context context, Installer installer,
2218            boolean factoryTest, boolean onlyCore) {
2219        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2220        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2221        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2222                SystemClock.uptimeMillis());
2223
2224        if (mSdkVersion <= 0) {
2225            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2226        }
2227
2228        mContext = context;
2229
2230        mPermissionReviewRequired = context.getResources().getBoolean(
2231                R.bool.config_permissionReviewRequired);
2232
2233        mFactoryTest = factoryTest;
2234        mOnlyCore = onlyCore;
2235        mMetrics = new DisplayMetrics();
2236        mSettings = new Settings(mPackages);
2237        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2240                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2241        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2242                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2243        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2248                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2249
2250        String separateProcesses = SystemProperties.get("debug.separate_processes");
2251        if (separateProcesses != null && separateProcesses.length() > 0) {
2252            if ("*".equals(separateProcesses)) {
2253                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2254                mSeparateProcesses = null;
2255                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2256            } else {
2257                mDefParseFlags = 0;
2258                mSeparateProcesses = separateProcesses.split(",");
2259                Slog.w(TAG, "Running with debug.separate_processes: "
2260                        + separateProcesses);
2261            }
2262        } else {
2263            mDefParseFlags = 0;
2264            mSeparateProcesses = null;
2265        }
2266
2267        mInstaller = installer;
2268        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2269                "*dexopt*");
2270        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2271        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2272
2273        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2274                FgThread.get().getLooper());
2275
2276        getDefaultDisplayMetrics(context, mMetrics);
2277
2278        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2279        SystemConfig systemConfig = SystemConfig.getInstance();
2280        mGlobalGids = systemConfig.getGlobalGids();
2281        mSystemPermissions = systemConfig.getSystemPermissions();
2282        mAvailableFeatures = systemConfig.getAvailableFeatures();
2283        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2284
2285        mProtectedPackages = new ProtectedPackages(mContext);
2286
2287        synchronized (mInstallLock) {
2288        // writer
2289        synchronized (mPackages) {
2290            mHandlerThread = new ServiceThread(TAG,
2291                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2292            mHandlerThread.start();
2293            mHandler = new PackageHandler(mHandlerThread.getLooper());
2294            mProcessLoggingHandler = new ProcessLoggingHandler();
2295            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2296
2297            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2298            mInstantAppRegistry = new InstantAppRegistry(this);
2299
2300            File dataDir = Environment.getDataDirectory();
2301            mAppInstallDir = new File(dataDir, "app");
2302            mAppLib32InstallDir = new File(dataDir, "app-lib");
2303            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2304            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2305            sUserManager = new UserManagerService(context, this,
2306                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2307
2308            // Propagate permission configuration in to package manager.
2309            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2310                    = systemConfig.getPermissions();
2311            for (int i=0; i<permConfig.size(); i++) {
2312                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2313                BasePermission bp = mSettings.mPermissions.get(perm.name);
2314                if (bp == null) {
2315                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2316                    mSettings.mPermissions.put(perm.name, bp);
2317                }
2318                if (perm.gids != null) {
2319                    bp.setGids(perm.gids, perm.perUser);
2320                }
2321            }
2322
2323            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2324            final int builtInLibCount = libConfig.size();
2325            for (int i = 0; i < builtInLibCount; i++) {
2326                String name = libConfig.keyAt(i);
2327                String path = libConfig.valueAt(i);
2328                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2329                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2330            }
2331
2332            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2333
2334            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2335            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2336            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2337
2338            // Clean up orphaned packages for which the code path doesn't exist
2339            // and they are an update to a system app - caused by bug/32321269
2340            final int packageSettingCount = mSettings.mPackages.size();
2341            for (int i = packageSettingCount - 1; i >= 0; i--) {
2342                PackageSetting ps = mSettings.mPackages.valueAt(i);
2343                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2344                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2345                    mSettings.mPackages.removeAt(i);
2346                    mSettings.enableSystemPackageLPw(ps.name);
2347                }
2348            }
2349
2350            if (mFirstBoot) {
2351                requestCopyPreoptedFiles();
2352            }
2353
2354            String customResolverActivity = Resources.getSystem().getString(
2355                    R.string.config_customResolverActivity);
2356            if (TextUtils.isEmpty(customResolverActivity)) {
2357                customResolverActivity = null;
2358            } else {
2359                mCustomResolverComponentName = ComponentName.unflattenFromString(
2360                        customResolverActivity);
2361            }
2362
2363            long startTime = SystemClock.uptimeMillis();
2364
2365            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2366                    startTime);
2367
2368            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2369            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2370
2371            if (bootClassPath == null) {
2372                Slog.w(TAG, "No BOOTCLASSPATH found!");
2373            }
2374
2375            if (systemServerClassPath == null) {
2376                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2377            }
2378
2379            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2380            final String[] dexCodeInstructionSets =
2381                    getDexCodeInstructionSets(
2382                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2383
2384            /**
2385             * Ensure all external libraries have had dexopt run on them.
2386             */
2387            if (mSharedLibraries.size() > 0) {
2388                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2389                // NOTE: For now, we're compiling these system "shared libraries"
2390                // (and framework jars) into all available architectures. It's possible
2391                // to compile them only when we come across an app that uses them (there's
2392                // already logic for that in scanPackageLI) but that adds some complexity.
2393                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2394                    final int libCount = mSharedLibraries.size();
2395                    for (int i = 0; i < libCount; i++) {
2396                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2397                        final int versionCount = versionedLib.size();
2398                        for (int j = 0; j < versionCount; j++) {
2399                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2400                            final String libPath = libEntry.path != null
2401                                    ? libEntry.path : libEntry.apk;
2402                            if (libPath == null) {
2403                                continue;
2404                            }
2405                            try {
2406                                // Shared libraries do not have profiles so we perform a full
2407                                // AOT compilation (if needed).
2408                                int dexoptNeeded = DexFile.getDexOptNeeded(
2409                                        libPath, dexCodeInstructionSet,
2410                                        getCompilerFilterForReason(REASON_SHARED_APK),
2411                                        false /* newProfile */);
2412                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2413                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2414                                            dexCodeInstructionSet, dexoptNeeded, null,
2415                                            DEXOPT_PUBLIC,
2416                                            getCompilerFilterForReason(REASON_SHARED_APK),
2417                                            StorageManager.UUID_PRIVATE_INTERNAL,
2418                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2419                                }
2420                            } catch (FileNotFoundException e) {
2421                                Slog.w(TAG, "Library not found: " + libPath);
2422                            } catch (IOException | InstallerException e) {
2423                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2424                                        + e.getMessage());
2425                            }
2426                        }
2427                    }
2428                }
2429                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2430            }
2431
2432            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2433
2434            final VersionInfo ver = mSettings.getInternalVersion();
2435            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2436
2437            // when upgrading from pre-M, promote system app permissions from install to runtime
2438            mPromoteSystemApps =
2439                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2440
2441            // When upgrading from pre-N, we need to handle package extraction like first boot,
2442            // as there is no profiling data available.
2443            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2444
2445            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2446
2447            // save off the names of pre-existing system packages prior to scanning; we don't
2448            // want to automatically grant runtime permissions for new system apps
2449            if (mPromoteSystemApps) {
2450                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2451                while (pkgSettingIter.hasNext()) {
2452                    PackageSetting ps = pkgSettingIter.next();
2453                    if (isSystemApp(ps)) {
2454                        mExistingSystemPackages.add(ps.name);
2455                    }
2456                }
2457            }
2458
2459            mCacheDir = preparePackageParserCache(mIsUpgrade);
2460
2461            // Set flag to monitor and not change apk file paths when
2462            // scanning install directories.
2463            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2464
2465            if (mIsUpgrade || mFirstBoot) {
2466                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2467            }
2468
2469            // Collect vendor overlay packages. (Do this before scanning any apps.)
2470            // For security and version matching reason, only consider
2471            // overlay packages if they reside in the right directory.
2472            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2473                    | PackageParser.PARSE_IS_SYSTEM
2474                    | PackageParser.PARSE_IS_SYSTEM_DIR
2475                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2476
2477            // Find base frameworks (resource packages without code).
2478            scanDirTracedLI(frameworkDir, mDefParseFlags
2479                    | PackageParser.PARSE_IS_SYSTEM
2480                    | PackageParser.PARSE_IS_SYSTEM_DIR
2481                    | PackageParser.PARSE_IS_PRIVILEGED,
2482                    scanFlags | SCAN_NO_DEX, 0);
2483
2484            // Collected privileged system packages.
2485            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2486            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR
2489                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2490
2491            // Collect ordinary system packages.
2492            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2493            scanDirTracedLI(systemAppDir, mDefParseFlags
2494                    | PackageParser.PARSE_IS_SYSTEM
2495                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2496
2497            // Collect all vendor packages.
2498            File vendorAppDir = new File("/vendor/app");
2499            try {
2500                vendorAppDir = vendorAppDir.getCanonicalFile();
2501            } catch (IOException e) {
2502                // failed to look up canonical path, continue with original one
2503            }
2504            scanDirTracedLI(vendorAppDir, mDefParseFlags
2505                    | PackageParser.PARSE_IS_SYSTEM
2506                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2507
2508            // Collect all OEM packages.
2509            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2510            scanDirTracedLI(oemAppDir, mDefParseFlags
2511                    | PackageParser.PARSE_IS_SYSTEM
2512                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2513
2514            // Prune any system packages that no longer exist.
2515            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2516            if (!mOnlyCore) {
2517                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2518                while (psit.hasNext()) {
2519                    PackageSetting ps = psit.next();
2520
2521                    /*
2522                     * If this is not a system app, it can't be a
2523                     * disable system app.
2524                     */
2525                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2526                        continue;
2527                    }
2528
2529                    /*
2530                     * If the package is scanned, it's not erased.
2531                     */
2532                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2533                    if (scannedPkg != null) {
2534                        /*
2535                         * If the system app is both scanned and in the
2536                         * disabled packages list, then it must have been
2537                         * added via OTA. Remove it from the currently
2538                         * scanned package so the previously user-installed
2539                         * application can be scanned.
2540                         */
2541                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2542                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2543                                    + ps.name + "; removing system app.  Last known codePath="
2544                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2545                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2546                                    + scannedPkg.mVersionCode);
2547                            removePackageLI(scannedPkg, true);
2548                            mExpectingBetter.put(ps.name, ps.codePath);
2549                        }
2550
2551                        continue;
2552                    }
2553
2554                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2555                        psit.remove();
2556                        logCriticalInfo(Log.WARN, "System package " + ps.name
2557                                + " no longer exists; it's data will be wiped");
2558                        // Actual deletion of code and data will be handled by later
2559                        // reconciliation step
2560                    } else {
2561                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2562                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2563                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2564                        }
2565                    }
2566                }
2567            }
2568
2569            //look for any incomplete package installations
2570            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2571            for (int i = 0; i < deletePkgsList.size(); i++) {
2572                // Actual deletion of code and data will be handled by later
2573                // reconciliation step
2574                final String packageName = deletePkgsList.get(i).name;
2575                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2576                synchronized (mPackages) {
2577                    mSettings.removePackageLPw(packageName);
2578                }
2579            }
2580
2581            //delete tmp files
2582            deleteTempPackageFiles();
2583
2584            // Remove any shared userIDs that have no associated packages
2585            mSettings.pruneSharedUsersLPw();
2586
2587            if (!mOnlyCore) {
2588                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2589                        SystemClock.uptimeMillis());
2590                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2591
2592                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2593                        | PackageParser.PARSE_FORWARD_LOCK,
2594                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2595
2596                /**
2597                 * Remove disable package settings for any updated system
2598                 * apps that were removed via an OTA. If they're not a
2599                 * previously-updated app, remove them completely.
2600                 * Otherwise, just revoke their system-level permissions.
2601                 */
2602                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2603                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2604                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2605
2606                    String msg;
2607                    if (deletedPkg == null) {
2608                        msg = "Updated system package " + deletedAppName
2609                                + " no longer exists; it's data will be wiped";
2610                        // Actual deletion of code and data will be handled by later
2611                        // reconciliation step
2612                    } else {
2613                        msg = "Updated system app + " + deletedAppName
2614                                + " no longer present; removing system privileges for "
2615                                + deletedAppName;
2616
2617                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2618
2619                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2620                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2621                    }
2622                    logCriticalInfo(Log.WARN, msg);
2623                }
2624
2625                /**
2626                 * Make sure all system apps that we expected to appear on
2627                 * the userdata partition actually showed up. If they never
2628                 * appeared, crawl back and revive the system version.
2629                 */
2630                for (int i = 0; i < mExpectingBetter.size(); i++) {
2631                    final String packageName = mExpectingBetter.keyAt(i);
2632                    if (!mPackages.containsKey(packageName)) {
2633                        final File scanFile = mExpectingBetter.valueAt(i);
2634
2635                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2636                                + " but never showed up; reverting to system");
2637
2638                        int reparseFlags = mDefParseFlags;
2639                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2640                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2641                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2642                                    | PackageParser.PARSE_IS_PRIVILEGED;
2643                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2644                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2645                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2646                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2650                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2651                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2652                        } else {
2653                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2654                            continue;
2655                        }
2656
2657                        mSettings.enableSystemPackageLPw(packageName);
2658
2659                        try {
2660                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2661                        } catch (PackageManagerException e) {
2662                            Slog.e(TAG, "Failed to parse original system package: "
2663                                    + e.getMessage());
2664                        }
2665                    }
2666                }
2667            }
2668            mExpectingBetter.clear();
2669
2670            // Resolve the storage manager.
2671            mStorageManagerPackage = getStorageManagerPackageName();
2672
2673            // Resolve protected action filters. Only the setup wizard is allowed to
2674            // have a high priority filter for these actions.
2675            mSetupWizardPackage = getSetupWizardPackageName();
2676            if (mProtectedFilters.size() > 0) {
2677                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2678                    Slog.i(TAG, "No setup wizard;"
2679                        + " All protected intents capped to priority 0");
2680                }
2681                for (ActivityIntentInfo filter : mProtectedFilters) {
2682                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2683                        if (DEBUG_FILTERS) {
2684                            Slog.i(TAG, "Found setup wizard;"
2685                                + " allow priority " + filter.getPriority() + ";"
2686                                + " package: " + filter.activity.info.packageName
2687                                + " activity: " + filter.activity.className
2688                                + " priority: " + filter.getPriority());
2689                        }
2690                        // skip setup wizard; allow it to keep the high priority filter
2691                        continue;
2692                    }
2693                    Slog.w(TAG, "Protected action; cap priority to 0;"
2694                            + " package: " + filter.activity.info.packageName
2695                            + " activity: " + filter.activity.className
2696                            + " origPrio: " + filter.getPriority());
2697                    filter.setPriority(0);
2698                }
2699            }
2700            mDeferProtectedFilters = false;
2701            mProtectedFilters.clear();
2702
2703            // Now that we know all of the shared libraries, update all clients to have
2704            // the correct library paths.
2705            updateAllSharedLibrariesLPw(null);
2706
2707            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2708                // NOTE: We ignore potential failures here during a system scan (like
2709                // the rest of the commands above) because there's precious little we
2710                // can do about it. A settings error is reported, though.
2711                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2712            }
2713
2714            // Now that we know all the packages we are keeping,
2715            // read and update their last usage times.
2716            mPackageUsage.read(mPackages);
2717            mCompilerStats.read();
2718
2719            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2720                    SystemClock.uptimeMillis());
2721            Slog.i(TAG, "Time to scan packages: "
2722                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2723                    + " seconds");
2724
2725            // If the platform SDK has changed since the last time we booted,
2726            // we need to re-grant app permission to catch any new ones that
2727            // appear.  This is really a hack, and means that apps can in some
2728            // cases get permissions that the user didn't initially explicitly
2729            // allow...  it would be nice to have some better way to handle
2730            // this situation.
2731            int updateFlags = UPDATE_PERMISSIONS_ALL;
2732            if (ver.sdkVersion != mSdkVersion) {
2733                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2734                        + mSdkVersion + "; regranting permissions for internal storage");
2735                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2736            }
2737            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2738            ver.sdkVersion = mSdkVersion;
2739
2740            // If this is the first boot or an update from pre-M, and it is a normal
2741            // boot, then we need to initialize the default preferred apps across
2742            // all defined users.
2743            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2744                for (UserInfo user : sUserManager.getUsers(true)) {
2745                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2746                    applyFactoryDefaultBrowserLPw(user.id);
2747                    primeDomainVerificationsLPw(user.id);
2748                }
2749            }
2750
2751            // Prepare storage for system user really early during boot,
2752            // since core system apps like SettingsProvider and SystemUI
2753            // can't wait for user to start
2754            final int storageFlags;
2755            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2756                storageFlags = StorageManager.FLAG_STORAGE_DE;
2757            } else {
2758                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2759            }
2760            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2761                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2762                    true /* onlyCoreApps */);
2763            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2764                if (deferPackages == null || deferPackages.isEmpty()) {
2765                    return;
2766                }
2767                int count = 0;
2768                for (String pkgName : deferPackages) {
2769                    PackageParser.Package pkg = null;
2770                    synchronized (mPackages) {
2771                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2772                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2773                            pkg = ps.pkg;
2774                        }
2775                    }
2776                    if (pkg != null) {
2777                        synchronized (mInstallLock) {
2778                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2779                                    true /* maybeMigrateAppData */);
2780                        }
2781                        count++;
2782                    }
2783                }
2784                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2785            }, "prepareAppData");
2786
2787            // If this is first boot after an OTA, and a normal boot, then
2788            // we need to clear code cache directories.
2789            // Note that we do *not* clear the application profiles. These remain valid
2790            // across OTAs and are used to drive profile verification (post OTA) and
2791            // profile compilation (without waiting to collect a fresh set of profiles).
2792            if (mIsUpgrade && !onlyCore) {
2793                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2794                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2795                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2796                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2797                        // No apps are running this early, so no need to freeze
2798                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2799                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2800                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2801                    }
2802                }
2803                ver.fingerprint = Build.FINGERPRINT;
2804            }
2805
2806            checkDefaultBrowser();
2807
2808            // clear only after permissions and other defaults have been updated
2809            mExistingSystemPackages.clear();
2810            mPromoteSystemApps = false;
2811
2812            // All the changes are done during package scanning.
2813            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2814
2815            // can downgrade to reader
2816            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2817            mSettings.writeLPr();
2818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2819
2820            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2821            // early on (before the package manager declares itself as early) because other
2822            // components in the system server might ask for package contexts for these apps.
2823            //
2824            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2825            // (i.e, that the data partition is unavailable).
2826            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2827                long start = System.nanoTime();
2828                List<PackageParser.Package> coreApps = new ArrayList<>();
2829                for (PackageParser.Package pkg : mPackages.values()) {
2830                    if (pkg.coreApp) {
2831                        coreApps.add(pkg);
2832                    }
2833                }
2834
2835                int[] stats = performDexOptUpgrade(coreApps, false,
2836                        getCompilerFilterForReason(REASON_CORE_APP));
2837
2838                final int elapsedTimeSeconds =
2839                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2840                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2841
2842                if (DEBUG_DEXOPT) {
2843                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2844                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2845                }
2846
2847
2848                // TODO: Should we log these stats to tron too ?
2849                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2850                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2851                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2852                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2853            }
2854
2855            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2856                    SystemClock.uptimeMillis());
2857
2858            if (!mOnlyCore) {
2859                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2860                mRequiredInstallerPackage = getRequiredInstallerLPr();
2861                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2862                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2863                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2864                        mIntentFilterVerifierComponent);
2865                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2866                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2867                        SharedLibraryInfo.VERSION_UNDEFINED);
2868                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2869                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2870                        SharedLibraryInfo.VERSION_UNDEFINED);
2871            } else {
2872                mRequiredVerifierPackage = null;
2873                mRequiredInstallerPackage = null;
2874                mRequiredUninstallerPackage = null;
2875                mIntentFilterVerifierComponent = null;
2876                mIntentFilterVerifier = null;
2877                mServicesSystemSharedLibraryPackageName = null;
2878                mSharedSystemSharedLibraryPackageName = null;
2879            }
2880
2881            mInstallerService = new PackageInstallerService(context, this);
2882            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2883            if (ephemeralResolverComponent != null) {
2884                if (DEBUG_EPHEMERAL) {
2885                    Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent);
2886                }
2887                mInstantAppResolverConnection =
2888                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2889            } else {
2890                mInstantAppResolverConnection = null;
2891            }
2892            updateInstantAppInstallerLocked();
2893
2894            // Read and update the usage of dex files.
2895            // Do this at the end of PM init so that all the packages have their
2896            // data directory reconciled.
2897            // At this point we know the code paths of the packages, so we can validate
2898            // the disk file and build the internal cache.
2899            // The usage file is expected to be small so loading and verifying it
2900            // should take a fairly small time compare to the other activities (e.g. package
2901            // scanning).
2902            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2903            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2904            for (int userId : currentUserIds) {
2905                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2906            }
2907            mDexManager.load(userPackages);
2908        } // synchronized (mPackages)
2909        } // synchronized (mInstallLock)
2910
2911        // Now after opening every single application zip, make sure they
2912        // are all flushed.  Not really needed, but keeps things nice and
2913        // tidy.
2914        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2915        Runtime.getRuntime().gc();
2916        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2917
2918        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2919        FallbackCategoryProvider.loadFallbacks();
2920        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2921
2922        // The initial scanning above does many calls into installd while
2923        // holding the mPackages lock, but we're mostly interested in yelling
2924        // once we have a booted system.
2925        mInstaller.setWarnIfHeld(mPackages);
2926
2927        // Expose private service for system components to use.
2928        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2929        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2930    }
2931
2932    private void updateInstantAppInstallerLocked() {
2933        final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent;
2934        final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr();
2935        ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null
2936                ? null : newInstantAppInstaller.getComponentName();
2937
2938        if (newInstantAppInstallerComponent != null
2939                && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) {
2940            if (DEBUG_EPHEMERAL) {
2941                Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent);
2942            }
2943            setUpInstantAppInstallerActivityLP(newInstantAppInstaller);
2944        } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) {
2945            Slog.d(TAG, "Unset ephemeral installer; none available");
2946        }
2947        mInstantAppInstallerComponent = newInstantAppInstallerComponent;
2948    }
2949
2950    private static File preparePackageParserCache(boolean isUpgrade) {
2951        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2952            return null;
2953        }
2954
2955        // Disable package parsing on eng builds to allow for faster incremental development.
2956        if ("eng".equals(Build.TYPE)) {
2957            return null;
2958        }
2959
2960        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2961            Slog.i(TAG, "Disabling package parser cache due to system property.");
2962            return null;
2963        }
2964
2965        // The base directory for the package parser cache lives under /data/system/.
2966        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2967                "package_cache");
2968        if (cacheBaseDir == null) {
2969            return null;
2970        }
2971
2972        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2973        // This also serves to "GC" unused entries when the package cache version changes (which
2974        // can only happen during upgrades).
2975        if (isUpgrade) {
2976            FileUtils.deleteContents(cacheBaseDir);
2977        }
2978
2979
2980        // Return the versioned package cache directory. This is something like
2981        // "/data/system/package_cache/1"
2982        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2983
2984        // The following is a workaround to aid development on non-numbered userdebug
2985        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2986        // the system partition is newer.
2987        //
2988        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2989        // that starts with "eng." to signify that this is an engineering build and not
2990        // destined for release.
2991        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2992            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2993
2994            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2995            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2996            // in general and should not be used for production changes. In this specific case,
2997            // we know that they will work.
2998            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2999            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3000                FileUtils.deleteContents(cacheBaseDir);
3001                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3002            }
3003        }
3004
3005        return cacheDir;
3006    }
3007
3008    @Override
3009    public boolean isFirstBoot() {
3010        return mFirstBoot;
3011    }
3012
3013    @Override
3014    public boolean isOnlyCoreApps() {
3015        return mOnlyCore;
3016    }
3017
3018    @Override
3019    public boolean isUpgrade() {
3020        return mIsUpgrade;
3021    }
3022
3023    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3024        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3025
3026        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3027                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3028                UserHandle.USER_SYSTEM);
3029        if (matches.size() == 1) {
3030            return matches.get(0).getComponentInfo().packageName;
3031        } else if (matches.size() == 0) {
3032            Log.e(TAG, "There should probably be a verifier, but, none were found");
3033            return null;
3034        }
3035        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3036    }
3037
3038    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3039        synchronized (mPackages) {
3040            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3041            if (libraryEntry == null) {
3042                throw new IllegalStateException("Missing required shared library:" + name);
3043            }
3044            return libraryEntry.apk;
3045        }
3046    }
3047
3048    private @NonNull String getRequiredInstallerLPr() {
3049        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3050        intent.addCategory(Intent.CATEGORY_DEFAULT);
3051        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3052
3053        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3054                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3055                UserHandle.USER_SYSTEM);
3056        if (matches.size() == 1) {
3057            ResolveInfo resolveInfo = matches.get(0);
3058            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3059                throw new RuntimeException("The installer must be a privileged app");
3060            }
3061            return matches.get(0).getComponentInfo().packageName;
3062        } else {
3063            throw new RuntimeException("There must be exactly one installer; found " + matches);
3064        }
3065    }
3066
3067    private @NonNull String getRequiredUninstallerLPr() {
3068        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3069        intent.addCategory(Intent.CATEGORY_DEFAULT);
3070        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3071
3072        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3073                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3074                UserHandle.USER_SYSTEM);
3075        if (resolveInfo == null ||
3076                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3077            throw new RuntimeException("There must be exactly one uninstaller; found "
3078                    + resolveInfo);
3079        }
3080        return resolveInfo.getComponentInfo().packageName;
3081    }
3082
3083    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3084        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3085
3086        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3087                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3088                UserHandle.USER_SYSTEM);
3089        ResolveInfo best = null;
3090        final int N = matches.size();
3091        for (int i = 0; i < N; i++) {
3092            final ResolveInfo cur = matches.get(i);
3093            final String packageName = cur.getComponentInfo().packageName;
3094            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3095                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3096                continue;
3097            }
3098
3099            if (best == null || cur.priority > best.priority) {
3100                best = cur;
3101            }
3102        }
3103
3104        if (best != null) {
3105            return best.getComponentInfo().getComponentName();
3106        } else {
3107            throw new RuntimeException("There must be at least one intent filter verifier");
3108        }
3109    }
3110
3111    private @Nullable ComponentName getEphemeralResolverLPr() {
3112        final String[] packageArray =
3113                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3114        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3115            if (DEBUG_EPHEMERAL) {
3116                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3117            }
3118            return null;
3119        }
3120
3121        final int resolveFlags =
3122                MATCH_DIRECT_BOOT_AWARE
3123                | MATCH_DIRECT_BOOT_UNAWARE
3124                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3125        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3126        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3127                resolveFlags, UserHandle.USER_SYSTEM);
3128
3129        final int N = resolvers.size();
3130        if (N == 0) {
3131            if (DEBUG_EPHEMERAL) {
3132                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3133            }
3134            return null;
3135        }
3136
3137        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3138        for (int i = 0; i < N; i++) {
3139            final ResolveInfo info = resolvers.get(i);
3140
3141            if (info.serviceInfo == null) {
3142                continue;
3143            }
3144
3145            final String packageName = info.serviceInfo.packageName;
3146            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3147                if (DEBUG_EPHEMERAL) {
3148                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3149                            + " pkg: " + packageName + ", info:" + info);
3150                }
3151                continue;
3152            }
3153
3154            if (DEBUG_EPHEMERAL) {
3155                Slog.v(TAG, "Ephemeral resolver found;"
3156                        + " pkg: " + packageName + ", info:" + info);
3157            }
3158            return new ComponentName(packageName, info.serviceInfo.name);
3159        }
3160        if (DEBUG_EPHEMERAL) {
3161            Slog.v(TAG, "Ephemeral resolver NOT found");
3162        }
3163        return null;
3164    }
3165
3166    private @Nullable ActivityInfo getEphemeralInstallerLPr() {
3167        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3168        intent.addCategory(Intent.CATEGORY_DEFAULT);
3169        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3170
3171        final int resolveFlags =
3172                MATCH_DIRECT_BOOT_AWARE
3173                | MATCH_DIRECT_BOOT_UNAWARE
3174                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3175        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3176                resolveFlags, UserHandle.USER_SYSTEM);
3177        Iterator<ResolveInfo> iter = matches.iterator();
3178        while (iter.hasNext()) {
3179            final ResolveInfo rInfo = iter.next();
3180            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3181            if (ps != null) {
3182                final PermissionsState permissionsState = ps.getPermissionsState();
3183                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3184                    continue;
3185                }
3186            }
3187            iter.remove();
3188        }
3189        if (matches.size() == 0) {
3190            return null;
3191        } else if (matches.size() == 1) {
3192            return (ActivityInfo) matches.get(0).getComponentInfo();
3193        } else {
3194            throw new RuntimeException(
3195                    "There must be at most one ephemeral installer; found " + matches);
3196        }
3197    }
3198
3199    private void primeDomainVerificationsLPw(int userId) {
3200        if (DEBUG_DOMAIN_VERIFICATION) {
3201            Slog.d(TAG, "Priming domain verifications in user " + userId);
3202        }
3203
3204        SystemConfig systemConfig = SystemConfig.getInstance();
3205        ArraySet<String> packages = systemConfig.getLinkedApps();
3206
3207        for (String packageName : packages) {
3208            PackageParser.Package pkg = mPackages.get(packageName);
3209            if (pkg != null) {
3210                if (!pkg.isSystemApp()) {
3211                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3212                    continue;
3213                }
3214
3215                ArraySet<String> domains = null;
3216                for (PackageParser.Activity a : pkg.activities) {
3217                    for (ActivityIntentInfo filter : a.intents) {
3218                        if (hasValidDomains(filter)) {
3219                            if (domains == null) {
3220                                domains = new ArraySet<String>();
3221                            }
3222                            domains.addAll(filter.getHostsList());
3223                        }
3224                    }
3225                }
3226
3227                if (domains != null && domains.size() > 0) {
3228                    if (DEBUG_DOMAIN_VERIFICATION) {
3229                        Slog.v(TAG, "      + " + packageName);
3230                    }
3231                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3232                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3233                    // and then 'always' in the per-user state actually used for intent resolution.
3234                    final IntentFilterVerificationInfo ivi;
3235                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3236                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3237                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3238                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3239                } else {
3240                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3241                            + "' does not handle web links");
3242                }
3243            } else {
3244                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3245            }
3246        }
3247
3248        scheduleWritePackageRestrictionsLocked(userId);
3249        scheduleWriteSettingsLocked();
3250    }
3251
3252    private void applyFactoryDefaultBrowserLPw(int userId) {
3253        // The default browser app's package name is stored in a string resource,
3254        // with a product-specific overlay used for vendor customization.
3255        String browserPkg = mContext.getResources().getString(
3256                com.android.internal.R.string.default_browser);
3257        if (!TextUtils.isEmpty(browserPkg)) {
3258            // non-empty string => required to be a known package
3259            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3260            if (ps == null) {
3261                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3262                browserPkg = null;
3263            } else {
3264                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3265            }
3266        }
3267
3268        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3269        // default.  If there's more than one, just leave everything alone.
3270        if (browserPkg == null) {
3271            calculateDefaultBrowserLPw(userId);
3272        }
3273    }
3274
3275    private void calculateDefaultBrowserLPw(int userId) {
3276        List<String> allBrowsers = resolveAllBrowserApps(userId);
3277        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3278        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3279    }
3280
3281    private List<String> resolveAllBrowserApps(int userId) {
3282        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3283        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3284                PackageManager.MATCH_ALL, userId);
3285
3286        final int count = list.size();
3287        List<String> result = new ArrayList<String>(count);
3288        for (int i=0; i<count; i++) {
3289            ResolveInfo info = list.get(i);
3290            if (info.activityInfo == null
3291                    || !info.handleAllWebDataURI
3292                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3293                    || result.contains(info.activityInfo.packageName)) {
3294                continue;
3295            }
3296            result.add(info.activityInfo.packageName);
3297        }
3298
3299        return result;
3300    }
3301
3302    private boolean packageIsBrowser(String packageName, int userId) {
3303        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3304                PackageManager.MATCH_ALL, userId);
3305        final int N = list.size();
3306        for (int i = 0; i < N; i++) {
3307            ResolveInfo info = list.get(i);
3308            if (packageName.equals(info.activityInfo.packageName)) {
3309                return true;
3310            }
3311        }
3312        return false;
3313    }
3314
3315    private void checkDefaultBrowser() {
3316        final int myUserId = UserHandle.myUserId();
3317        final String packageName = getDefaultBrowserPackageName(myUserId);
3318        if (packageName != null) {
3319            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3320            if (info == null) {
3321                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3322                synchronized (mPackages) {
3323                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3324                }
3325            }
3326        }
3327    }
3328
3329    @Override
3330    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3331            throws RemoteException {
3332        try {
3333            return super.onTransact(code, data, reply, flags);
3334        } catch (RuntimeException e) {
3335            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3336                Slog.wtf(TAG, "Package Manager Crash", e);
3337            }
3338            throw e;
3339        }
3340    }
3341
3342    static int[] appendInts(int[] cur, int[] add) {
3343        if (add == null) return cur;
3344        if (cur == null) return add;
3345        final int N = add.length;
3346        for (int i=0; i<N; i++) {
3347            cur = appendInt(cur, add[i]);
3348        }
3349        return cur;
3350    }
3351
3352    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3353        if (!sUserManager.exists(userId)) return null;
3354        if (ps == null) {
3355            return null;
3356        }
3357        final PackageParser.Package p = ps.pkg;
3358        if (p == null) {
3359            return null;
3360        }
3361        // Filter out ephemeral app metadata:
3362        //   * The system/shell/root can see metadata for any app
3363        //   * An installed app can see metadata for 1) other installed apps
3364        //     and 2) ephemeral apps that have explicitly interacted with it
3365        //   * Ephemeral apps can only see their own data and exposed installed apps
3366        //   * Holding a signature permission allows seeing instant apps
3367        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3368        if (callingAppId != Process.SYSTEM_UID
3369                && callingAppId != Process.SHELL_UID
3370                && callingAppId != Process.ROOT_UID
3371                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3372                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3373            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3374            if (instantAppPackageName != null) {
3375                // ephemeral apps can only get information on themselves or
3376                // installed apps that are exposed.
3377                if (!instantAppPackageName.equals(p.packageName)
3378                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3379                    return null;
3380                }
3381            } else {
3382                if (ps.getInstantApp(userId)) {
3383                    // only get access to the ephemeral app if we've been granted access
3384                    if (!mInstantAppRegistry.isInstantAccessGranted(
3385                            userId, callingAppId, ps.appId)) {
3386                        return null;
3387                    }
3388                }
3389            }
3390        }
3391
3392        final PermissionsState permissionsState = ps.getPermissionsState();
3393
3394        // Compute GIDs only if requested
3395        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3396                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3397        // Compute granted permissions only if package has requested permissions
3398        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3399                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3400        final PackageUserState state = ps.readUserState(userId);
3401
3402        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3403                && ps.isSystem()) {
3404            flags |= MATCH_ANY_USER;
3405        }
3406
3407        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3408                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3409
3410        if (packageInfo == null) {
3411            return null;
3412        }
3413
3414        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3415
3416        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3417                resolveExternalPackageNameLPr(p);
3418
3419        return packageInfo;
3420    }
3421
3422    @Override
3423    public void checkPackageStartable(String packageName, int userId) {
3424        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3425
3426        synchronized (mPackages) {
3427            final PackageSetting ps = mSettings.mPackages.get(packageName);
3428            if (ps == null) {
3429                throw new SecurityException("Package " + packageName + " was not found!");
3430            }
3431
3432            if (!ps.getInstalled(userId)) {
3433                throw new SecurityException(
3434                        "Package " + packageName + " was not installed for user " + userId + "!");
3435            }
3436
3437            if (mSafeMode && !ps.isSystem()) {
3438                throw new SecurityException("Package " + packageName + " not a system app!");
3439            }
3440
3441            if (mFrozenPackages.contains(packageName)) {
3442                throw new SecurityException("Package " + packageName + " is currently frozen!");
3443            }
3444
3445            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3446                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3447                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3448            }
3449        }
3450    }
3451
3452    @Override
3453    public boolean isPackageAvailable(String packageName, int userId) {
3454        if (!sUserManager.exists(userId)) return false;
3455        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3456                false /* requireFullPermission */, false /* checkShell */, "is package available");
3457        synchronized (mPackages) {
3458            PackageParser.Package p = mPackages.get(packageName);
3459            if (p != null) {
3460                final PackageSetting ps = (PackageSetting) p.mExtras;
3461                if (ps != null) {
3462                    final PackageUserState state = ps.readUserState(userId);
3463                    if (state != null) {
3464                        return PackageParser.isAvailable(state);
3465                    }
3466                }
3467            }
3468        }
3469        return false;
3470    }
3471
3472    @Override
3473    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3474        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3475                flags, userId);
3476    }
3477
3478    @Override
3479    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3480            int flags, int userId) {
3481        return getPackageInfoInternal(versionedPackage.getPackageName(),
3482                // TODO: We will change version code to long, so in the new API it is long
3483                (int) versionedPackage.getVersionCode(), flags, userId);
3484    }
3485
3486    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3487            int flags, int userId) {
3488        if (!sUserManager.exists(userId)) return null;
3489        flags = updateFlagsForPackage(flags, userId, packageName);
3490        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3491                false /* requireFullPermission */, false /* checkShell */, "get package info");
3492
3493        // reader
3494        synchronized (mPackages) {
3495            // Normalize package name to handle renamed packages and static libs
3496            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3497
3498            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3499            if (matchFactoryOnly) {
3500                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3501                if (ps != null) {
3502                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3503                        return null;
3504                    }
3505                    return generatePackageInfo(ps, flags, userId);
3506                }
3507            }
3508
3509            PackageParser.Package p = mPackages.get(packageName);
3510            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3511                return null;
3512            }
3513            if (DEBUG_PACKAGE_INFO)
3514                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3515            if (p != null) {
3516                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3517                        Binder.getCallingUid(), userId)) {
3518                    return null;
3519                }
3520                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3521            }
3522            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3523                final PackageSetting ps = mSettings.mPackages.get(packageName);
3524                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3525                    return null;
3526                }
3527                return generatePackageInfo(ps, flags, userId);
3528            }
3529        }
3530        return null;
3531    }
3532
3533
3534    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3535        // System/shell/root get to see all static libs
3536        final int appId = UserHandle.getAppId(uid);
3537        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3538                || appId == Process.ROOT_UID) {
3539            return false;
3540        }
3541
3542        // No package means no static lib as it is always on internal storage
3543        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3544            return false;
3545        }
3546
3547        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3548                ps.pkg.staticSharedLibVersion);
3549        if (libEntry == null) {
3550            return false;
3551        }
3552
3553        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3554        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3555        if (uidPackageNames == null) {
3556            return true;
3557        }
3558
3559        for (String uidPackageName : uidPackageNames) {
3560            if (ps.name.equals(uidPackageName)) {
3561                return false;
3562            }
3563            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3564            if (uidPs != null) {
3565                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3566                        libEntry.info.getName());
3567                if (index < 0) {
3568                    continue;
3569                }
3570                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3571                    return false;
3572                }
3573            }
3574        }
3575        return true;
3576    }
3577
3578    @Override
3579    public String[] currentToCanonicalPackageNames(String[] names) {
3580        String[] out = new String[names.length];
3581        // reader
3582        synchronized (mPackages) {
3583            for (int i=names.length-1; i>=0; i--) {
3584                PackageSetting ps = mSettings.mPackages.get(names[i]);
3585                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3586            }
3587        }
3588        return out;
3589    }
3590
3591    @Override
3592    public String[] canonicalToCurrentPackageNames(String[] names) {
3593        String[] out = new String[names.length];
3594        // reader
3595        synchronized (mPackages) {
3596            for (int i=names.length-1; i>=0; i--) {
3597                String cur = mSettings.getRenamedPackageLPr(names[i]);
3598                out[i] = cur != null ? cur : names[i];
3599            }
3600        }
3601        return out;
3602    }
3603
3604    @Override
3605    public int getPackageUid(String packageName, int flags, int userId) {
3606        if (!sUserManager.exists(userId)) return -1;
3607        flags = updateFlagsForPackage(flags, userId, packageName);
3608        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3609                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3610
3611        // reader
3612        synchronized (mPackages) {
3613            final PackageParser.Package p = mPackages.get(packageName);
3614            if (p != null && p.isMatch(flags)) {
3615                return UserHandle.getUid(userId, p.applicationInfo.uid);
3616            }
3617            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3618                final PackageSetting ps = mSettings.mPackages.get(packageName);
3619                if (ps != null && ps.isMatch(flags)) {
3620                    return UserHandle.getUid(userId, ps.appId);
3621                }
3622            }
3623        }
3624
3625        return -1;
3626    }
3627
3628    @Override
3629    public int[] getPackageGids(String packageName, int flags, int userId) {
3630        if (!sUserManager.exists(userId)) return null;
3631        flags = updateFlagsForPackage(flags, userId, packageName);
3632        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3633                false /* requireFullPermission */, false /* checkShell */,
3634                "getPackageGids");
3635
3636        // reader
3637        synchronized (mPackages) {
3638            final PackageParser.Package p = mPackages.get(packageName);
3639            if (p != null && p.isMatch(flags)) {
3640                PackageSetting ps = (PackageSetting) p.mExtras;
3641                // TODO: Shouldn't this be checking for package installed state for userId and
3642                // return null?
3643                return ps.getPermissionsState().computeGids(userId);
3644            }
3645            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3646                final PackageSetting ps = mSettings.mPackages.get(packageName);
3647                if (ps != null && ps.isMatch(flags)) {
3648                    return ps.getPermissionsState().computeGids(userId);
3649                }
3650            }
3651        }
3652
3653        return null;
3654    }
3655
3656    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3657        if (bp.perm != null) {
3658            return PackageParser.generatePermissionInfo(bp.perm, flags);
3659        }
3660        PermissionInfo pi = new PermissionInfo();
3661        pi.name = bp.name;
3662        pi.packageName = bp.sourcePackage;
3663        pi.nonLocalizedLabel = bp.name;
3664        pi.protectionLevel = bp.protectionLevel;
3665        return pi;
3666    }
3667
3668    @Override
3669    public PermissionInfo getPermissionInfo(String name, int flags) {
3670        // reader
3671        synchronized (mPackages) {
3672            final BasePermission p = mSettings.mPermissions.get(name);
3673            if (p != null) {
3674                return generatePermissionInfo(p, flags);
3675            }
3676            return null;
3677        }
3678    }
3679
3680    @Override
3681    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3682            int flags) {
3683        // reader
3684        synchronized (mPackages) {
3685            if (group != null && !mPermissionGroups.containsKey(group)) {
3686                // This is thrown as NameNotFoundException
3687                return null;
3688            }
3689
3690            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3691            for (BasePermission p : mSettings.mPermissions.values()) {
3692                if (group == null) {
3693                    if (p.perm == null || p.perm.info.group == null) {
3694                        out.add(generatePermissionInfo(p, flags));
3695                    }
3696                } else {
3697                    if (p.perm != null && group.equals(p.perm.info.group)) {
3698                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3699                    }
3700                }
3701            }
3702            return new ParceledListSlice<>(out);
3703        }
3704    }
3705
3706    @Override
3707    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3708        // reader
3709        synchronized (mPackages) {
3710            return PackageParser.generatePermissionGroupInfo(
3711                    mPermissionGroups.get(name), flags);
3712        }
3713    }
3714
3715    @Override
3716    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3717        // reader
3718        synchronized (mPackages) {
3719            final int N = mPermissionGroups.size();
3720            ArrayList<PermissionGroupInfo> out
3721                    = new ArrayList<PermissionGroupInfo>(N);
3722            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3723                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3724            }
3725            return new ParceledListSlice<>(out);
3726        }
3727    }
3728
3729    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3730            int uid, int userId) {
3731        if (!sUserManager.exists(userId)) return null;
3732        PackageSetting ps = mSettings.mPackages.get(packageName);
3733        if (ps != null) {
3734            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3735                return null;
3736            }
3737            if (ps.pkg == null) {
3738                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3739                if (pInfo != null) {
3740                    return pInfo.applicationInfo;
3741                }
3742                return null;
3743            }
3744            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3745                    ps.readUserState(userId), userId);
3746            if (ai != null) {
3747                rebaseEnabledOverlays(ai, userId);
3748                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3749            }
3750            return ai;
3751        }
3752        return null;
3753    }
3754
3755    @Override
3756    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3757        if (!sUserManager.exists(userId)) return null;
3758        flags = updateFlagsForApplication(flags, userId, packageName);
3759        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3760                false /* requireFullPermission */, false /* checkShell */, "get application info");
3761
3762        // writer
3763        synchronized (mPackages) {
3764            // Normalize package name to handle renamed packages and static libs
3765            packageName = resolveInternalPackageNameLPr(packageName,
3766                    PackageManager.VERSION_CODE_HIGHEST);
3767
3768            PackageParser.Package p = mPackages.get(packageName);
3769            if (DEBUG_PACKAGE_INFO) Log.v(
3770                    TAG, "getApplicationInfo " + packageName
3771                    + ": " + p);
3772            if (p != null) {
3773                PackageSetting ps = mSettings.mPackages.get(packageName);
3774                if (ps == null) return null;
3775                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3776                    return null;
3777                }
3778                // Note: isEnabledLP() does not apply here - always return info
3779                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3780                        p, flags, ps.readUserState(userId), userId);
3781                if (ai != null) {
3782                    rebaseEnabledOverlays(ai, userId);
3783                    ai.packageName = resolveExternalPackageNameLPr(p);
3784                }
3785                return ai;
3786            }
3787            if ("android".equals(packageName)||"system".equals(packageName)) {
3788                return mAndroidApplication;
3789            }
3790            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3791                // Already generates the external package name
3792                return generateApplicationInfoFromSettingsLPw(packageName,
3793                        Binder.getCallingUid(), flags, userId);
3794            }
3795        }
3796        return null;
3797    }
3798
3799    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3800        List<String> paths = new ArrayList<>();
3801        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3802            mEnabledOverlayPaths.get(userId);
3803        if (userSpecificOverlays != null) {
3804            if (!"android".equals(ai.packageName)) {
3805                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3806                if (frameworkOverlays != null) {
3807                    paths.addAll(frameworkOverlays);
3808                }
3809            }
3810
3811            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3812            if (appOverlays != null) {
3813                paths.addAll(appOverlays);
3814            }
3815        }
3816        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3817    }
3818
3819    private String normalizePackageNameLPr(String packageName) {
3820        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3821        return normalizedPackageName != null ? normalizedPackageName : packageName;
3822    }
3823
3824    @Override
3825    public void deletePreloadsFileCache() {
3826        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3827            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3828        }
3829        File dir = Environment.getDataPreloadsFileCacheDirectory();
3830        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3831        FileUtils.deleteContents(dir);
3832    }
3833
3834    @Override
3835    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3836            final IPackageDataObserver observer) {
3837        mContext.enforceCallingOrSelfPermission(
3838                android.Manifest.permission.CLEAR_APP_CACHE, null);
3839        mHandler.post(() -> {
3840            boolean success = false;
3841            try {
3842                freeStorage(volumeUuid, freeStorageSize, 0);
3843                success = true;
3844            } catch (IOException e) {
3845                Slog.w(TAG, e);
3846            }
3847            if (observer != null) {
3848                try {
3849                    observer.onRemoveCompleted(null, success);
3850                } catch (RemoteException e) {
3851                    Slog.w(TAG, e);
3852                }
3853            }
3854        });
3855    }
3856
3857    @Override
3858    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3859            final IntentSender pi) {
3860        mContext.enforceCallingOrSelfPermission(
3861                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3862        mHandler.post(() -> {
3863            boolean success = false;
3864            try {
3865                freeStorage(volumeUuid, freeStorageSize, 0);
3866                success = true;
3867            } catch (IOException e) {
3868                Slog.w(TAG, e);
3869            }
3870            if (pi != null) {
3871                try {
3872                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3873                } catch (SendIntentException e) {
3874                    Slog.w(TAG, e);
3875                }
3876            }
3877        });
3878    }
3879
3880    /**
3881     * Blocking call to clear various types of cached data across the system
3882     * until the requested bytes are available.
3883     */
3884    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3885        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3886        final File file = storage.findPathForUuid(volumeUuid);
3887        if (file.getUsableSpace() >= bytes) return;
3888
3889        if (ENABLE_FREE_CACHE_V2) {
3890            final boolean aggressive = (storageFlags
3891                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3892            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3893                    volumeUuid);
3894
3895            // 1. Pre-flight to determine if we have any chance to succeed
3896            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3897            if (internalVolume && (aggressive || SystemProperties
3898                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3899                deletePreloadsFileCache();
3900                if (file.getUsableSpace() >= bytes) return;
3901            }
3902
3903            // 3. Consider parsed APK data (aggressive only)
3904            if (internalVolume && aggressive) {
3905                FileUtils.deleteContents(mCacheDir);
3906                if (file.getUsableSpace() >= bytes) return;
3907            }
3908
3909            // 4. Consider cached app data (above quotas)
3910            try {
3911                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3912            } catch (InstallerException ignored) {
3913            }
3914            if (file.getUsableSpace() >= bytes) return;
3915
3916            // 5. Consider shared libraries with refcount=0 and age>2h
3917            // 6. Consider dexopt output (aggressive only)
3918            // 7. Consider ephemeral apps not used in last week
3919
3920            // 8. Consider cached app data (below quotas)
3921            try {
3922                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3923                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3924            } catch (InstallerException ignored) {
3925            }
3926            if (file.getUsableSpace() >= bytes) return;
3927
3928            // 9. Consider DropBox entries
3929            // 10. Consider ephemeral cookies
3930
3931        } else {
3932            try {
3933                mInstaller.freeCache(volumeUuid, bytes, 0);
3934            } catch (InstallerException ignored) {
3935            }
3936            if (file.getUsableSpace() >= bytes) return;
3937        }
3938
3939        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3940    }
3941
3942    /**
3943     * Update given flags based on encryption status of current user.
3944     */
3945    private int updateFlags(int flags, int userId) {
3946        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3947                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3948            // Caller expressed an explicit opinion about what encryption
3949            // aware/unaware components they want to see, so fall through and
3950            // give them what they want
3951        } else {
3952            // Caller expressed no opinion, so match based on user state
3953            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3954                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3955            } else {
3956                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3957            }
3958        }
3959        return flags;
3960    }
3961
3962    private UserManagerInternal getUserManagerInternal() {
3963        if (mUserManagerInternal == null) {
3964            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3965        }
3966        return mUserManagerInternal;
3967    }
3968
3969    private DeviceIdleController.LocalService getDeviceIdleController() {
3970        if (mDeviceIdleController == null) {
3971            mDeviceIdleController =
3972                    LocalServices.getService(DeviceIdleController.LocalService.class);
3973        }
3974        return mDeviceIdleController;
3975    }
3976
3977    /**
3978     * Update given flags when being used to request {@link PackageInfo}.
3979     */
3980    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3981        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3982        boolean triaged = true;
3983        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3984                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3985            // Caller is asking for component details, so they'd better be
3986            // asking for specific encryption matching behavior, or be triaged
3987            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3988                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3989                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3990                triaged = false;
3991            }
3992        }
3993        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3994                | PackageManager.MATCH_SYSTEM_ONLY
3995                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3996            triaged = false;
3997        }
3998        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3999            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4000                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4001                    + Debug.getCallers(5));
4002        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4003                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4004            // If the caller wants all packages and has a restricted profile associated with it,
4005            // then match all users. This is to make sure that launchers that need to access work
4006            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4007            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4008            flags |= PackageManager.MATCH_ANY_USER;
4009        }
4010        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4011            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4012                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4013        }
4014        return updateFlags(flags, userId);
4015    }
4016
4017    /**
4018     * Update given flags when being used to request {@link ApplicationInfo}.
4019     */
4020    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4021        return updateFlagsForPackage(flags, userId, cookie);
4022    }
4023
4024    /**
4025     * Update given flags when being used to request {@link ComponentInfo}.
4026     */
4027    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4028        if (cookie instanceof Intent) {
4029            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4030                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4031            }
4032        }
4033
4034        boolean triaged = true;
4035        // Caller is asking for component details, so they'd better be
4036        // asking for specific encryption matching behavior, or be triaged
4037        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4038                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4039                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4040            triaged = false;
4041        }
4042        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4043            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4044                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4045        }
4046
4047        return updateFlags(flags, userId);
4048    }
4049
4050    /**
4051     * Update given intent when being used to request {@link ResolveInfo}.
4052     */
4053    private Intent updateIntentForResolve(Intent intent) {
4054        if (intent.getSelector() != null) {
4055            intent = intent.getSelector();
4056        }
4057        if (DEBUG_PREFERRED) {
4058            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4059        }
4060        return intent;
4061    }
4062
4063    /**
4064     * Update given flags when being used to request {@link ResolveInfo}.
4065     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4066     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4067     * flag set. However, this flag is only honoured in three circumstances:
4068     * <ul>
4069     * <li>when called from a system process</li>
4070     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4071     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4072     * action and a {@code android.intent.category.BROWSABLE} category</li>
4073     * </ul>
4074     */
4075    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4076        // Safe mode means we shouldn't match any third-party components
4077        if (mSafeMode) {
4078            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4079        }
4080        final int callingUid = Binder.getCallingUid();
4081        if (getInstantAppPackageName(callingUid) != null) {
4082            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4083            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4084            flags |= PackageManager.MATCH_INSTANT;
4085        } else {
4086            // Otherwise, prevent leaking ephemeral components
4087            final boolean isSpecialProcess =
4088                    callingUid == Process.SYSTEM_UID
4089                    || callingUid == Process.SHELL_UID
4090                    || callingUid == 0;
4091            final boolean allowMatchInstant =
4092                    (includeInstantApp
4093                            && Intent.ACTION_VIEW.equals(intent.getAction())
4094                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4095                            && hasWebURI(intent))
4096                    || isSpecialProcess
4097                    || mContext.checkCallingOrSelfPermission(
4098                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4099            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4100            if (!allowMatchInstant) {
4101                flags &= ~PackageManager.MATCH_INSTANT;
4102            }
4103        }
4104        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4105    }
4106
4107    @Override
4108    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4109        if (!sUserManager.exists(userId)) return null;
4110        flags = updateFlagsForComponent(flags, userId, component);
4111        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4112                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4113        synchronized (mPackages) {
4114            PackageParser.Activity a = mActivities.mActivities.get(component);
4115
4116            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4117            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4118                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4119                if (ps == null) return null;
4120                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4121                        userId);
4122            }
4123            if (mResolveComponentName.equals(component)) {
4124                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4125                        new PackageUserState(), userId);
4126            }
4127        }
4128        return null;
4129    }
4130
4131    @Override
4132    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4133            String resolvedType) {
4134        synchronized (mPackages) {
4135            if (component.equals(mResolveComponentName)) {
4136                // The resolver supports EVERYTHING!
4137                return true;
4138            }
4139            PackageParser.Activity a = mActivities.mActivities.get(component);
4140            if (a == null) {
4141                return false;
4142            }
4143            for (int i=0; i<a.intents.size(); i++) {
4144                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4145                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4146                    return true;
4147                }
4148            }
4149            return false;
4150        }
4151    }
4152
4153    @Override
4154    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4155        if (!sUserManager.exists(userId)) return null;
4156        flags = updateFlagsForComponent(flags, userId, component);
4157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4158                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4159        synchronized (mPackages) {
4160            PackageParser.Activity a = mReceivers.mActivities.get(component);
4161            if (DEBUG_PACKAGE_INFO) Log.v(
4162                TAG, "getReceiverInfo " + component + ": " + a);
4163            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4164                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4165                if (ps == null) return null;
4166                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4167                        ps.readUserState(userId), userId);
4168                if (ri != null) {
4169                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4170                }
4171                return ri;
4172            }
4173        }
4174        return null;
4175    }
4176
4177    @Override
4178    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4179        if (!sUserManager.exists(userId)) return null;
4180        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4181
4182        flags = updateFlagsForPackage(flags, userId, null);
4183
4184        final boolean canSeeStaticLibraries =
4185                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4186                        == PERMISSION_GRANTED
4187                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4188                        == PERMISSION_GRANTED
4189                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4190                        == PERMISSION_GRANTED
4191                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4192                        == PERMISSION_GRANTED;
4193
4194        synchronized (mPackages) {
4195            List<SharedLibraryInfo> result = null;
4196
4197            final int libCount = mSharedLibraries.size();
4198            for (int i = 0; i < libCount; i++) {
4199                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4200                if (versionedLib == null) {
4201                    continue;
4202                }
4203
4204                final int versionCount = versionedLib.size();
4205                for (int j = 0; j < versionCount; j++) {
4206                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4207                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4208                        break;
4209                    }
4210                    final long identity = Binder.clearCallingIdentity();
4211                    try {
4212                        // TODO: We will change version code to long, so in the new API it is long
4213                        PackageInfo packageInfo = getPackageInfoVersioned(
4214                                libInfo.getDeclaringPackage(), flags, userId);
4215                        if (packageInfo == null) {
4216                            continue;
4217                        }
4218                    } finally {
4219                        Binder.restoreCallingIdentity(identity);
4220                    }
4221
4222                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4223                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4224                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4225
4226                    if (result == null) {
4227                        result = new ArrayList<>();
4228                    }
4229                    result.add(resLibInfo);
4230                }
4231            }
4232
4233            return result != null ? new ParceledListSlice<>(result) : null;
4234        }
4235    }
4236
4237    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4238            SharedLibraryInfo libInfo, int flags, int userId) {
4239        List<VersionedPackage> versionedPackages = null;
4240        final int packageCount = mSettings.mPackages.size();
4241        for (int i = 0; i < packageCount; i++) {
4242            PackageSetting ps = mSettings.mPackages.valueAt(i);
4243
4244            if (ps == null) {
4245                continue;
4246            }
4247
4248            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4249                continue;
4250            }
4251
4252            final String libName = libInfo.getName();
4253            if (libInfo.isStatic()) {
4254                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4255                if (libIdx < 0) {
4256                    continue;
4257                }
4258                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4259                    continue;
4260                }
4261                if (versionedPackages == null) {
4262                    versionedPackages = new ArrayList<>();
4263                }
4264                // If the dependent is a static shared lib, use the public package name
4265                String dependentPackageName = ps.name;
4266                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4267                    dependentPackageName = ps.pkg.manifestPackageName;
4268                }
4269                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4270            } else if (ps.pkg != null) {
4271                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4272                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4273                    if (versionedPackages == null) {
4274                        versionedPackages = new ArrayList<>();
4275                    }
4276                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4277                }
4278            }
4279        }
4280
4281        return versionedPackages;
4282    }
4283
4284    @Override
4285    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4286        if (!sUserManager.exists(userId)) return null;
4287        flags = updateFlagsForComponent(flags, userId, component);
4288        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4289                false /* requireFullPermission */, false /* checkShell */, "get service info");
4290        synchronized (mPackages) {
4291            PackageParser.Service s = mServices.mServices.get(component);
4292            if (DEBUG_PACKAGE_INFO) Log.v(
4293                TAG, "getServiceInfo " + component + ": " + s);
4294            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4295                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4296                if (ps == null) return null;
4297                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4298                        ps.readUserState(userId), userId);
4299                if (si != null) {
4300                    rebaseEnabledOverlays(si.applicationInfo, userId);
4301                }
4302                return si;
4303            }
4304        }
4305        return null;
4306    }
4307
4308    @Override
4309    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4310        if (!sUserManager.exists(userId)) return null;
4311        flags = updateFlagsForComponent(flags, userId, component);
4312        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4313                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4314        synchronized (mPackages) {
4315            PackageParser.Provider p = mProviders.mProviders.get(component);
4316            if (DEBUG_PACKAGE_INFO) Log.v(
4317                TAG, "getProviderInfo " + component + ": " + p);
4318            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4319                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4320                if (ps == null) return null;
4321                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4322                        ps.readUserState(userId), userId);
4323                if (pi != null) {
4324                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4325                }
4326                return pi;
4327            }
4328        }
4329        return null;
4330    }
4331
4332    @Override
4333    public String[] getSystemSharedLibraryNames() {
4334        synchronized (mPackages) {
4335            Set<String> libs = null;
4336            final int libCount = mSharedLibraries.size();
4337            for (int i = 0; i < libCount; i++) {
4338                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4339                if (versionedLib == null) {
4340                    continue;
4341                }
4342                final int versionCount = versionedLib.size();
4343                for (int j = 0; j < versionCount; j++) {
4344                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4345                    if (!libEntry.info.isStatic()) {
4346                        if (libs == null) {
4347                            libs = new ArraySet<>();
4348                        }
4349                        libs.add(libEntry.info.getName());
4350                        break;
4351                    }
4352                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4353                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4354                            UserHandle.getUserId(Binder.getCallingUid()))) {
4355                        if (libs == null) {
4356                            libs = new ArraySet<>();
4357                        }
4358                        libs.add(libEntry.info.getName());
4359                        break;
4360                    }
4361                }
4362            }
4363
4364            if (libs != null) {
4365                String[] libsArray = new String[libs.size()];
4366                libs.toArray(libsArray);
4367                return libsArray;
4368            }
4369
4370            return null;
4371        }
4372    }
4373
4374    @Override
4375    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4376        synchronized (mPackages) {
4377            return mServicesSystemSharedLibraryPackageName;
4378        }
4379    }
4380
4381    @Override
4382    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4383        synchronized (mPackages) {
4384            return mSharedSystemSharedLibraryPackageName;
4385        }
4386    }
4387
4388    private void updateSequenceNumberLP(String packageName, int[] userList) {
4389        for (int i = userList.length - 1; i >= 0; --i) {
4390            final int userId = userList[i];
4391            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4392            if (changedPackages == null) {
4393                changedPackages = new SparseArray<>();
4394                mChangedPackages.put(userId, changedPackages);
4395            }
4396            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4397            if (sequenceNumbers == null) {
4398                sequenceNumbers = new HashMap<>();
4399                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4400            }
4401            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4402            if (sequenceNumber != null) {
4403                changedPackages.remove(sequenceNumber);
4404            }
4405            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4406            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4407        }
4408        mChangedPackagesSequenceNumber++;
4409    }
4410
4411    @Override
4412    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4413        synchronized (mPackages) {
4414            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4415                return null;
4416            }
4417            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4418            if (changedPackages == null) {
4419                return null;
4420            }
4421            final List<String> packageNames =
4422                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4423            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4424                final String packageName = changedPackages.get(i);
4425                if (packageName != null) {
4426                    packageNames.add(packageName);
4427                }
4428            }
4429            return packageNames.isEmpty()
4430                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4431        }
4432    }
4433
4434    @Override
4435    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4436        ArrayList<FeatureInfo> res;
4437        synchronized (mAvailableFeatures) {
4438            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4439            res.addAll(mAvailableFeatures.values());
4440        }
4441        final FeatureInfo fi = new FeatureInfo();
4442        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4443                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4444        res.add(fi);
4445
4446        return new ParceledListSlice<>(res);
4447    }
4448
4449    @Override
4450    public boolean hasSystemFeature(String name, int version) {
4451        synchronized (mAvailableFeatures) {
4452            final FeatureInfo feat = mAvailableFeatures.get(name);
4453            if (feat == null) {
4454                return false;
4455            } else {
4456                return feat.version >= version;
4457            }
4458        }
4459    }
4460
4461    @Override
4462    public int checkPermission(String permName, String pkgName, int userId) {
4463        if (!sUserManager.exists(userId)) {
4464            return PackageManager.PERMISSION_DENIED;
4465        }
4466
4467        synchronized (mPackages) {
4468            final PackageParser.Package p = mPackages.get(pkgName);
4469            if (p != null && p.mExtras != null) {
4470                final PackageSetting ps = (PackageSetting) p.mExtras;
4471                final PermissionsState permissionsState = ps.getPermissionsState();
4472                if (permissionsState.hasPermission(permName, userId)) {
4473                    return PackageManager.PERMISSION_GRANTED;
4474                }
4475                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4476                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4477                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4478                    return PackageManager.PERMISSION_GRANTED;
4479                }
4480            }
4481        }
4482
4483        return PackageManager.PERMISSION_DENIED;
4484    }
4485
4486    @Override
4487    public int checkUidPermission(String permName, int uid) {
4488        final int userId = UserHandle.getUserId(uid);
4489
4490        if (!sUserManager.exists(userId)) {
4491            return PackageManager.PERMISSION_DENIED;
4492        }
4493
4494        synchronized (mPackages) {
4495            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4496            if (obj != null) {
4497                final SettingBase ps = (SettingBase) obj;
4498                final PermissionsState permissionsState = ps.getPermissionsState();
4499                if (permissionsState.hasPermission(permName, userId)) {
4500                    return PackageManager.PERMISSION_GRANTED;
4501                }
4502                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4503                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4504                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4505                    return PackageManager.PERMISSION_GRANTED;
4506                }
4507            } else {
4508                ArraySet<String> perms = mSystemPermissions.get(uid);
4509                if (perms != null) {
4510                    if (perms.contains(permName)) {
4511                        return PackageManager.PERMISSION_GRANTED;
4512                    }
4513                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4514                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4515                        return PackageManager.PERMISSION_GRANTED;
4516                    }
4517                }
4518            }
4519        }
4520
4521        return PackageManager.PERMISSION_DENIED;
4522    }
4523
4524    @Override
4525    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4526        if (UserHandle.getCallingUserId() != userId) {
4527            mContext.enforceCallingPermission(
4528                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4529                    "isPermissionRevokedByPolicy for user " + userId);
4530        }
4531
4532        if (checkPermission(permission, packageName, userId)
4533                == PackageManager.PERMISSION_GRANTED) {
4534            return false;
4535        }
4536
4537        final long identity = Binder.clearCallingIdentity();
4538        try {
4539            final int flags = getPermissionFlags(permission, packageName, userId);
4540            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4541        } finally {
4542            Binder.restoreCallingIdentity(identity);
4543        }
4544    }
4545
4546    @Override
4547    public String getPermissionControllerPackageName() {
4548        synchronized (mPackages) {
4549            return mRequiredInstallerPackage;
4550        }
4551    }
4552
4553    /**
4554     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4555     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4556     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4557     * @param message the message to log on security exception
4558     */
4559    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4560            boolean checkShell, String message) {
4561        if (userId < 0) {
4562            throw new IllegalArgumentException("Invalid userId " + userId);
4563        }
4564        if (checkShell) {
4565            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4566        }
4567        if (userId == UserHandle.getUserId(callingUid)) return;
4568        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4569            if (requireFullPermission) {
4570                mContext.enforceCallingOrSelfPermission(
4571                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4572            } else {
4573                try {
4574                    mContext.enforceCallingOrSelfPermission(
4575                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4576                } catch (SecurityException se) {
4577                    mContext.enforceCallingOrSelfPermission(
4578                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4579                }
4580            }
4581        }
4582    }
4583
4584    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4585        if (callingUid == Process.SHELL_UID) {
4586            if (userHandle >= 0
4587                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4588                throw new SecurityException("Shell does not have permission to access user "
4589                        + userHandle);
4590            } else if (userHandle < 0) {
4591                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4592                        + Debug.getCallers(3));
4593            }
4594        }
4595    }
4596
4597    private BasePermission findPermissionTreeLP(String permName) {
4598        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4599            if (permName.startsWith(bp.name) &&
4600                    permName.length() > bp.name.length() &&
4601                    permName.charAt(bp.name.length()) == '.') {
4602                return bp;
4603            }
4604        }
4605        return null;
4606    }
4607
4608    private BasePermission checkPermissionTreeLP(String permName) {
4609        if (permName != null) {
4610            BasePermission bp = findPermissionTreeLP(permName);
4611            if (bp != null) {
4612                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4613                    return bp;
4614                }
4615                throw new SecurityException("Calling uid "
4616                        + Binder.getCallingUid()
4617                        + " is not allowed to add to permission tree "
4618                        + bp.name + " owned by uid " + bp.uid);
4619            }
4620        }
4621        throw new SecurityException("No permission tree found for " + permName);
4622    }
4623
4624    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4625        if (s1 == null) {
4626            return s2 == null;
4627        }
4628        if (s2 == null) {
4629            return false;
4630        }
4631        if (s1.getClass() != s2.getClass()) {
4632            return false;
4633        }
4634        return s1.equals(s2);
4635    }
4636
4637    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4638        if (pi1.icon != pi2.icon) return false;
4639        if (pi1.logo != pi2.logo) return false;
4640        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4641        if (!compareStrings(pi1.name, pi2.name)) return false;
4642        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4643        // We'll take care of setting this one.
4644        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4645        // These are not currently stored in settings.
4646        //if (!compareStrings(pi1.group, pi2.group)) return false;
4647        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4648        //if (pi1.labelRes != pi2.labelRes) return false;
4649        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4650        return true;
4651    }
4652
4653    int permissionInfoFootprint(PermissionInfo info) {
4654        int size = info.name.length();
4655        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4656        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4657        return size;
4658    }
4659
4660    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4661        int size = 0;
4662        for (BasePermission perm : mSettings.mPermissions.values()) {
4663            if (perm.uid == tree.uid) {
4664                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4665            }
4666        }
4667        return size;
4668    }
4669
4670    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4671        // We calculate the max size of permissions defined by this uid and throw
4672        // if that plus the size of 'info' would exceed our stated maximum.
4673        if (tree.uid != Process.SYSTEM_UID) {
4674            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4675            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4676                throw new SecurityException("Permission tree size cap exceeded");
4677            }
4678        }
4679    }
4680
4681    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4682        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4683            throw new SecurityException("Label must be specified in permission");
4684        }
4685        BasePermission tree = checkPermissionTreeLP(info.name);
4686        BasePermission bp = mSettings.mPermissions.get(info.name);
4687        boolean added = bp == null;
4688        boolean changed = true;
4689        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4690        if (added) {
4691            enforcePermissionCapLocked(info, tree);
4692            bp = new BasePermission(info.name, tree.sourcePackage,
4693                    BasePermission.TYPE_DYNAMIC);
4694        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4695            throw new SecurityException(
4696                    "Not allowed to modify non-dynamic permission "
4697                    + info.name);
4698        } else {
4699            if (bp.protectionLevel == fixedLevel
4700                    && bp.perm.owner.equals(tree.perm.owner)
4701                    && bp.uid == tree.uid
4702                    && comparePermissionInfos(bp.perm.info, info)) {
4703                changed = false;
4704            }
4705        }
4706        bp.protectionLevel = fixedLevel;
4707        info = new PermissionInfo(info);
4708        info.protectionLevel = fixedLevel;
4709        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4710        bp.perm.info.packageName = tree.perm.info.packageName;
4711        bp.uid = tree.uid;
4712        if (added) {
4713            mSettings.mPermissions.put(info.name, bp);
4714        }
4715        if (changed) {
4716            if (!async) {
4717                mSettings.writeLPr();
4718            } else {
4719                scheduleWriteSettingsLocked();
4720            }
4721        }
4722        return added;
4723    }
4724
4725    @Override
4726    public boolean addPermission(PermissionInfo info) {
4727        synchronized (mPackages) {
4728            return addPermissionLocked(info, false);
4729        }
4730    }
4731
4732    @Override
4733    public boolean addPermissionAsync(PermissionInfo info) {
4734        synchronized (mPackages) {
4735            return addPermissionLocked(info, true);
4736        }
4737    }
4738
4739    @Override
4740    public void removePermission(String name) {
4741        synchronized (mPackages) {
4742            checkPermissionTreeLP(name);
4743            BasePermission bp = mSettings.mPermissions.get(name);
4744            if (bp != null) {
4745                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4746                    throw new SecurityException(
4747                            "Not allowed to modify non-dynamic permission "
4748                            + name);
4749                }
4750                mSettings.mPermissions.remove(name);
4751                mSettings.writeLPr();
4752            }
4753        }
4754    }
4755
4756    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4757            BasePermission bp) {
4758        int index = pkg.requestedPermissions.indexOf(bp.name);
4759        if (index == -1) {
4760            throw new SecurityException("Package " + pkg.packageName
4761                    + " has not requested permission " + bp.name);
4762        }
4763        if (!bp.isRuntime() && !bp.isDevelopment()) {
4764            throw new SecurityException("Permission " + bp.name
4765                    + " is not a changeable permission type");
4766        }
4767    }
4768
4769    @Override
4770    public void grantRuntimePermission(String packageName, String name, final int userId) {
4771        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4772    }
4773
4774    private void grantRuntimePermission(String packageName, String name, final int userId,
4775            boolean overridePolicy) {
4776        if (!sUserManager.exists(userId)) {
4777            Log.e(TAG, "No such user:" + userId);
4778            return;
4779        }
4780
4781        mContext.enforceCallingOrSelfPermission(
4782                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4783                "grantRuntimePermission");
4784
4785        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4786                true /* requireFullPermission */, true /* checkShell */,
4787                "grantRuntimePermission");
4788
4789        final int uid;
4790        final SettingBase sb;
4791
4792        synchronized (mPackages) {
4793            final PackageParser.Package pkg = mPackages.get(packageName);
4794            if (pkg == null) {
4795                throw new IllegalArgumentException("Unknown package: " + packageName);
4796            }
4797
4798            final BasePermission bp = mSettings.mPermissions.get(name);
4799            if (bp == null) {
4800                throw new IllegalArgumentException("Unknown permission: " + name);
4801            }
4802
4803            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4804
4805            // If a permission review is required for legacy apps we represent
4806            // their permissions as always granted runtime ones since we need
4807            // to keep the review required permission flag per user while an
4808            // install permission's state is shared across all users.
4809            if (mPermissionReviewRequired
4810                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4811                    && bp.isRuntime()) {
4812                return;
4813            }
4814
4815            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4816            sb = (SettingBase) pkg.mExtras;
4817            if (sb == null) {
4818                throw new IllegalArgumentException("Unknown package: " + packageName);
4819            }
4820
4821            final PermissionsState permissionsState = sb.getPermissionsState();
4822
4823            final int flags = permissionsState.getPermissionFlags(name, userId);
4824            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4825                throw new SecurityException("Cannot grant system fixed permission "
4826                        + name + " for package " + packageName);
4827            }
4828            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4829                throw new SecurityException("Cannot grant policy fixed permission "
4830                        + name + " for package " + packageName);
4831            }
4832
4833            if (bp.isDevelopment()) {
4834                // Development permissions must be handled specially, since they are not
4835                // normal runtime permissions.  For now they apply to all users.
4836                if (permissionsState.grantInstallPermission(bp) !=
4837                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4838                    scheduleWriteSettingsLocked();
4839                }
4840                return;
4841            }
4842
4843            final PackageSetting ps = mSettings.mPackages.get(packageName);
4844            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4845                throw new SecurityException("Cannot grant non-ephemeral permission"
4846                        + name + " for package " + packageName);
4847            }
4848
4849            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4850                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4851                return;
4852            }
4853
4854            final int result = permissionsState.grantRuntimePermission(bp, userId);
4855            switch (result) {
4856                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4857                    return;
4858                }
4859
4860                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4861                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4862                    mHandler.post(new Runnable() {
4863                        @Override
4864                        public void run() {
4865                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4866                        }
4867                    });
4868                }
4869                break;
4870            }
4871
4872            if (bp.isRuntime()) {
4873                logPermissionGranted(mContext, name, packageName);
4874            }
4875
4876            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4877
4878            // Not critical if that is lost - app has to request again.
4879            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4880        }
4881
4882        // Only need to do this if user is initialized. Otherwise it's a new user
4883        // and there are no processes running as the user yet and there's no need
4884        // to make an expensive call to remount processes for the changed permissions.
4885        if (READ_EXTERNAL_STORAGE.equals(name)
4886                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4887            final long token = Binder.clearCallingIdentity();
4888            try {
4889                if (sUserManager.isInitialized(userId)) {
4890                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4891                            StorageManagerInternal.class);
4892                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4893                }
4894            } finally {
4895                Binder.restoreCallingIdentity(token);
4896            }
4897        }
4898    }
4899
4900    @Override
4901    public void revokeRuntimePermission(String packageName, String name, int userId) {
4902        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4903    }
4904
4905    private void revokeRuntimePermission(String packageName, String name, int userId,
4906            boolean overridePolicy) {
4907        if (!sUserManager.exists(userId)) {
4908            Log.e(TAG, "No such user:" + userId);
4909            return;
4910        }
4911
4912        mContext.enforceCallingOrSelfPermission(
4913                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4914                "revokeRuntimePermission");
4915
4916        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4917                true /* requireFullPermission */, true /* checkShell */,
4918                "revokeRuntimePermission");
4919
4920        final int appId;
4921
4922        synchronized (mPackages) {
4923            final PackageParser.Package pkg = mPackages.get(packageName);
4924            if (pkg == null) {
4925                throw new IllegalArgumentException("Unknown package: " + packageName);
4926            }
4927
4928            final BasePermission bp = mSettings.mPermissions.get(name);
4929            if (bp == null) {
4930                throw new IllegalArgumentException("Unknown permission: " + name);
4931            }
4932
4933            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4934
4935            // If a permission review is required for legacy apps we represent
4936            // their permissions as always granted runtime ones since we need
4937            // to keep the review required permission flag per user while an
4938            // install permission's state is shared across all users.
4939            if (mPermissionReviewRequired
4940                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4941                    && bp.isRuntime()) {
4942                return;
4943            }
4944
4945            SettingBase sb = (SettingBase) pkg.mExtras;
4946            if (sb == null) {
4947                throw new IllegalArgumentException("Unknown package: " + packageName);
4948            }
4949
4950            final PermissionsState permissionsState = sb.getPermissionsState();
4951
4952            final int flags = permissionsState.getPermissionFlags(name, userId);
4953            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4954                throw new SecurityException("Cannot revoke system fixed permission "
4955                        + name + " for package " + packageName);
4956            }
4957            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4958                throw new SecurityException("Cannot revoke policy fixed permission "
4959                        + name + " for package " + packageName);
4960            }
4961
4962            if (bp.isDevelopment()) {
4963                // Development permissions must be handled specially, since they are not
4964                // normal runtime permissions.  For now they apply to all users.
4965                if (permissionsState.revokeInstallPermission(bp) !=
4966                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4967                    scheduleWriteSettingsLocked();
4968                }
4969                return;
4970            }
4971
4972            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4973                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4974                return;
4975            }
4976
4977            if (bp.isRuntime()) {
4978                logPermissionRevoked(mContext, name, packageName);
4979            }
4980
4981            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4982
4983            // Critical, after this call app should never have the permission.
4984            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4985
4986            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4987        }
4988
4989        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4990    }
4991
4992    /**
4993     * Get the first event id for the permission.
4994     *
4995     * <p>There are four events for each permission: <ul>
4996     *     <li>Request permission: first id + 0</li>
4997     *     <li>Grant permission: first id + 1</li>
4998     *     <li>Request for permission denied: first id + 2</li>
4999     *     <li>Revoke permission: first id + 3</li>
5000     * </ul></p>
5001     *
5002     * @param name name of the permission
5003     *
5004     * @return The first event id for the permission
5005     */
5006    private static int getBaseEventId(@NonNull String name) {
5007        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5008
5009        if (eventIdIndex == -1) {
5010            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5011                    || "user".equals(Build.TYPE)) {
5012                Log.i(TAG, "Unknown permission " + name);
5013
5014                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5015            } else {
5016                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5017                //
5018                // Also update
5019                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5020                // - metrics_constants.proto
5021                throw new IllegalStateException("Unknown permission " + name);
5022            }
5023        }
5024
5025        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5026    }
5027
5028    /**
5029     * Log that a permission was revoked.
5030     *
5031     * @param context Context of the caller
5032     * @param name name of the permission
5033     * @param packageName package permission if for
5034     */
5035    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5036            @NonNull String packageName) {
5037        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5038    }
5039
5040    /**
5041     * Log that a permission request was granted.
5042     *
5043     * @param context Context of the caller
5044     * @param name name of the permission
5045     * @param packageName package permission if for
5046     */
5047    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5048            @NonNull String packageName) {
5049        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5050    }
5051
5052    @Override
5053    public void resetRuntimePermissions() {
5054        mContext.enforceCallingOrSelfPermission(
5055                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5056                "revokeRuntimePermission");
5057
5058        int callingUid = Binder.getCallingUid();
5059        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5060            mContext.enforceCallingOrSelfPermission(
5061                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5062                    "resetRuntimePermissions");
5063        }
5064
5065        synchronized (mPackages) {
5066            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5067            for (int userId : UserManagerService.getInstance().getUserIds()) {
5068                final int packageCount = mPackages.size();
5069                for (int i = 0; i < packageCount; i++) {
5070                    PackageParser.Package pkg = mPackages.valueAt(i);
5071                    if (!(pkg.mExtras instanceof PackageSetting)) {
5072                        continue;
5073                    }
5074                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5075                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5076                }
5077            }
5078        }
5079    }
5080
5081    @Override
5082    public int getPermissionFlags(String name, String packageName, int userId) {
5083        if (!sUserManager.exists(userId)) {
5084            return 0;
5085        }
5086
5087        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5088
5089        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5090                true /* requireFullPermission */, false /* checkShell */,
5091                "getPermissionFlags");
5092
5093        synchronized (mPackages) {
5094            final PackageParser.Package pkg = mPackages.get(packageName);
5095            if (pkg == null) {
5096                return 0;
5097            }
5098
5099            final BasePermission bp = mSettings.mPermissions.get(name);
5100            if (bp == null) {
5101                return 0;
5102            }
5103
5104            SettingBase sb = (SettingBase) pkg.mExtras;
5105            if (sb == null) {
5106                return 0;
5107            }
5108
5109            PermissionsState permissionsState = sb.getPermissionsState();
5110            return permissionsState.getPermissionFlags(name, userId);
5111        }
5112    }
5113
5114    @Override
5115    public void updatePermissionFlags(String name, String packageName, int flagMask,
5116            int flagValues, int userId) {
5117        if (!sUserManager.exists(userId)) {
5118            return;
5119        }
5120
5121        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5122
5123        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5124                true /* requireFullPermission */, true /* checkShell */,
5125                "updatePermissionFlags");
5126
5127        // Only the system can change these flags and nothing else.
5128        if (getCallingUid() != Process.SYSTEM_UID) {
5129            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5130            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5131            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5132            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5133            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5134        }
5135
5136        synchronized (mPackages) {
5137            final PackageParser.Package pkg = mPackages.get(packageName);
5138            if (pkg == null) {
5139                throw new IllegalArgumentException("Unknown package: " + packageName);
5140            }
5141
5142            final BasePermission bp = mSettings.mPermissions.get(name);
5143            if (bp == null) {
5144                throw new IllegalArgumentException("Unknown permission: " + name);
5145            }
5146
5147            SettingBase sb = (SettingBase) pkg.mExtras;
5148            if (sb == null) {
5149                throw new IllegalArgumentException("Unknown package: " + packageName);
5150            }
5151
5152            PermissionsState permissionsState = sb.getPermissionsState();
5153
5154            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5155
5156            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5157                // Install and runtime permissions are stored in different places,
5158                // so figure out what permission changed and persist the change.
5159                if (permissionsState.getInstallPermissionState(name) != null) {
5160                    scheduleWriteSettingsLocked();
5161                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5162                        || hadState) {
5163                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5164                }
5165            }
5166        }
5167    }
5168
5169    /**
5170     * Update the permission flags for all packages and runtime permissions of a user in order
5171     * to allow device or profile owner to remove POLICY_FIXED.
5172     */
5173    @Override
5174    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5175        if (!sUserManager.exists(userId)) {
5176            return;
5177        }
5178
5179        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5180
5181        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5182                true /* requireFullPermission */, true /* checkShell */,
5183                "updatePermissionFlagsForAllApps");
5184
5185        // Only the system can change system fixed flags.
5186        if (getCallingUid() != Process.SYSTEM_UID) {
5187            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5188            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5189        }
5190
5191        synchronized (mPackages) {
5192            boolean changed = false;
5193            final int packageCount = mPackages.size();
5194            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5195                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5196                SettingBase sb = (SettingBase) pkg.mExtras;
5197                if (sb == null) {
5198                    continue;
5199                }
5200                PermissionsState permissionsState = sb.getPermissionsState();
5201                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5202                        userId, flagMask, flagValues);
5203            }
5204            if (changed) {
5205                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5206            }
5207        }
5208    }
5209
5210    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5211        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5212                != PackageManager.PERMISSION_GRANTED
5213            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5214                != PackageManager.PERMISSION_GRANTED) {
5215            throw new SecurityException(message + " requires "
5216                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5217                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5218        }
5219    }
5220
5221    @Override
5222    public boolean shouldShowRequestPermissionRationale(String permissionName,
5223            String packageName, int userId) {
5224        if (UserHandle.getCallingUserId() != userId) {
5225            mContext.enforceCallingPermission(
5226                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5227                    "canShowRequestPermissionRationale for user " + userId);
5228        }
5229
5230        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5231        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5232            return false;
5233        }
5234
5235        if (checkPermission(permissionName, packageName, userId)
5236                == PackageManager.PERMISSION_GRANTED) {
5237            return false;
5238        }
5239
5240        final int flags;
5241
5242        final long identity = Binder.clearCallingIdentity();
5243        try {
5244            flags = getPermissionFlags(permissionName,
5245                    packageName, userId);
5246        } finally {
5247            Binder.restoreCallingIdentity(identity);
5248        }
5249
5250        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5251                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5252                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5253
5254        if ((flags & fixedFlags) != 0) {
5255            return false;
5256        }
5257
5258        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5259    }
5260
5261    @Override
5262    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5263        mContext.enforceCallingOrSelfPermission(
5264                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5265                "addOnPermissionsChangeListener");
5266
5267        synchronized (mPackages) {
5268            mOnPermissionChangeListeners.addListenerLocked(listener);
5269        }
5270    }
5271
5272    @Override
5273    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5274        synchronized (mPackages) {
5275            mOnPermissionChangeListeners.removeListenerLocked(listener);
5276        }
5277    }
5278
5279    @Override
5280    public boolean isProtectedBroadcast(String actionName) {
5281        synchronized (mPackages) {
5282            if (mProtectedBroadcasts.contains(actionName)) {
5283                return true;
5284            } else if (actionName != null) {
5285                // TODO: remove these terrible hacks
5286                if (actionName.startsWith("android.net.netmon.lingerExpired")
5287                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5288                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5289                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5290                    return true;
5291                }
5292            }
5293        }
5294        return false;
5295    }
5296
5297    @Override
5298    public int checkSignatures(String pkg1, String pkg2) {
5299        synchronized (mPackages) {
5300            final PackageParser.Package p1 = mPackages.get(pkg1);
5301            final PackageParser.Package p2 = mPackages.get(pkg2);
5302            if (p1 == null || p1.mExtras == null
5303                    || p2 == null || p2.mExtras == null) {
5304                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5305            }
5306            return compareSignatures(p1.mSignatures, p2.mSignatures);
5307        }
5308    }
5309
5310    @Override
5311    public int checkUidSignatures(int uid1, int uid2) {
5312        // Map to base uids.
5313        uid1 = UserHandle.getAppId(uid1);
5314        uid2 = UserHandle.getAppId(uid2);
5315        // reader
5316        synchronized (mPackages) {
5317            Signature[] s1;
5318            Signature[] s2;
5319            Object obj = mSettings.getUserIdLPr(uid1);
5320            if (obj != null) {
5321                if (obj instanceof SharedUserSetting) {
5322                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5323                } else if (obj instanceof PackageSetting) {
5324                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5325                } else {
5326                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5327                }
5328            } else {
5329                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5330            }
5331            obj = mSettings.getUserIdLPr(uid2);
5332            if (obj != null) {
5333                if (obj instanceof SharedUserSetting) {
5334                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5335                } else if (obj instanceof PackageSetting) {
5336                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5337                } else {
5338                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5339                }
5340            } else {
5341                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5342            }
5343            return compareSignatures(s1, s2);
5344        }
5345    }
5346
5347    /**
5348     * This method should typically only be used when granting or revoking
5349     * permissions, since the app may immediately restart after this call.
5350     * <p>
5351     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5352     * guard your work against the app being relaunched.
5353     */
5354    private void killUid(int appId, int userId, String reason) {
5355        final long identity = Binder.clearCallingIdentity();
5356        try {
5357            IActivityManager am = ActivityManager.getService();
5358            if (am != null) {
5359                try {
5360                    am.killUid(appId, userId, reason);
5361                } catch (RemoteException e) {
5362                    /* ignore - same process */
5363                }
5364            }
5365        } finally {
5366            Binder.restoreCallingIdentity(identity);
5367        }
5368    }
5369
5370    /**
5371     * Compares two sets of signatures. Returns:
5372     * <br />
5373     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5374     * <br />
5375     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5376     * <br />
5377     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5378     * <br />
5379     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5380     * <br />
5381     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5382     */
5383    static int compareSignatures(Signature[] s1, Signature[] s2) {
5384        if (s1 == null) {
5385            return s2 == null
5386                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5387                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5388        }
5389
5390        if (s2 == null) {
5391            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5392        }
5393
5394        if (s1.length != s2.length) {
5395            return PackageManager.SIGNATURE_NO_MATCH;
5396        }
5397
5398        // Since both signature sets are of size 1, we can compare without HashSets.
5399        if (s1.length == 1) {
5400            return s1[0].equals(s2[0]) ?
5401                    PackageManager.SIGNATURE_MATCH :
5402                    PackageManager.SIGNATURE_NO_MATCH;
5403        }
5404
5405        ArraySet<Signature> set1 = new ArraySet<Signature>();
5406        for (Signature sig : s1) {
5407            set1.add(sig);
5408        }
5409        ArraySet<Signature> set2 = new ArraySet<Signature>();
5410        for (Signature sig : s2) {
5411            set2.add(sig);
5412        }
5413        // Make sure s2 contains all signatures in s1.
5414        if (set1.equals(set2)) {
5415            return PackageManager.SIGNATURE_MATCH;
5416        }
5417        return PackageManager.SIGNATURE_NO_MATCH;
5418    }
5419
5420    /**
5421     * If the database version for this type of package (internal storage or
5422     * external storage) is less than the version where package signatures
5423     * were updated, return true.
5424     */
5425    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5426        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5427        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5428    }
5429
5430    /**
5431     * Used for backward compatibility to make sure any packages with
5432     * certificate chains get upgraded to the new style. {@code existingSigs}
5433     * will be in the old format (since they were stored on disk from before the
5434     * system upgrade) and {@code scannedSigs} will be in the newer format.
5435     */
5436    private int compareSignaturesCompat(PackageSignatures existingSigs,
5437            PackageParser.Package scannedPkg) {
5438        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5439            return PackageManager.SIGNATURE_NO_MATCH;
5440        }
5441
5442        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5443        for (Signature sig : existingSigs.mSignatures) {
5444            existingSet.add(sig);
5445        }
5446        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5447        for (Signature sig : scannedPkg.mSignatures) {
5448            try {
5449                Signature[] chainSignatures = sig.getChainSignatures();
5450                for (Signature chainSig : chainSignatures) {
5451                    scannedCompatSet.add(chainSig);
5452                }
5453            } catch (CertificateEncodingException e) {
5454                scannedCompatSet.add(sig);
5455            }
5456        }
5457        /*
5458         * Make sure the expanded scanned set contains all signatures in the
5459         * existing one.
5460         */
5461        if (scannedCompatSet.equals(existingSet)) {
5462            // Migrate the old signatures to the new scheme.
5463            existingSigs.assignSignatures(scannedPkg.mSignatures);
5464            // The new KeySets will be re-added later in the scanning process.
5465            synchronized (mPackages) {
5466                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5467            }
5468            return PackageManager.SIGNATURE_MATCH;
5469        }
5470        return PackageManager.SIGNATURE_NO_MATCH;
5471    }
5472
5473    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5474        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5475        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5476    }
5477
5478    private int compareSignaturesRecover(PackageSignatures existingSigs,
5479            PackageParser.Package scannedPkg) {
5480        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5481            return PackageManager.SIGNATURE_NO_MATCH;
5482        }
5483
5484        String msg = null;
5485        try {
5486            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5487                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5488                        + scannedPkg.packageName);
5489                return PackageManager.SIGNATURE_MATCH;
5490            }
5491        } catch (CertificateException e) {
5492            msg = e.getMessage();
5493        }
5494
5495        logCriticalInfo(Log.INFO,
5496                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5497        return PackageManager.SIGNATURE_NO_MATCH;
5498    }
5499
5500    @Override
5501    public List<String> getAllPackages() {
5502        synchronized (mPackages) {
5503            return new ArrayList<String>(mPackages.keySet());
5504        }
5505    }
5506
5507    @Override
5508    public String[] getPackagesForUid(int uid) {
5509        final int userId = UserHandle.getUserId(uid);
5510        uid = UserHandle.getAppId(uid);
5511        // reader
5512        synchronized (mPackages) {
5513            Object obj = mSettings.getUserIdLPr(uid);
5514            if (obj instanceof SharedUserSetting) {
5515                final SharedUserSetting sus = (SharedUserSetting) obj;
5516                final int N = sus.packages.size();
5517                String[] res = new String[N];
5518                final Iterator<PackageSetting> it = sus.packages.iterator();
5519                int i = 0;
5520                while (it.hasNext()) {
5521                    PackageSetting ps = it.next();
5522                    if (ps.getInstalled(userId)) {
5523                        res[i++] = ps.name;
5524                    } else {
5525                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5526                    }
5527                }
5528                return res;
5529            } else if (obj instanceof PackageSetting) {
5530                final PackageSetting ps = (PackageSetting) obj;
5531                if (ps.getInstalled(userId)) {
5532                    return new String[]{ps.name};
5533                }
5534            }
5535        }
5536        return null;
5537    }
5538
5539    @Override
5540    public String getNameForUid(int uid) {
5541        // reader
5542        synchronized (mPackages) {
5543            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5544            if (obj instanceof SharedUserSetting) {
5545                final SharedUserSetting sus = (SharedUserSetting) obj;
5546                return sus.name + ":" + sus.userId;
5547            } else if (obj instanceof PackageSetting) {
5548                final PackageSetting ps = (PackageSetting) obj;
5549                return ps.name;
5550            }
5551        }
5552        return null;
5553    }
5554
5555    @Override
5556    public int getUidForSharedUser(String sharedUserName) {
5557        if(sharedUserName == null) {
5558            return -1;
5559        }
5560        // reader
5561        synchronized (mPackages) {
5562            SharedUserSetting suid;
5563            try {
5564                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5565                if (suid != null) {
5566                    return suid.userId;
5567                }
5568            } catch (PackageManagerException ignore) {
5569                // can't happen, but, still need to catch it
5570            }
5571            return -1;
5572        }
5573    }
5574
5575    @Override
5576    public int getFlagsForUid(int uid) {
5577        synchronized (mPackages) {
5578            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5579            if (obj instanceof SharedUserSetting) {
5580                final SharedUserSetting sus = (SharedUserSetting) obj;
5581                return sus.pkgFlags;
5582            } else if (obj instanceof PackageSetting) {
5583                final PackageSetting ps = (PackageSetting) obj;
5584                return ps.pkgFlags;
5585            }
5586        }
5587        return 0;
5588    }
5589
5590    @Override
5591    public int getPrivateFlagsForUid(int uid) {
5592        synchronized (mPackages) {
5593            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5594            if (obj instanceof SharedUserSetting) {
5595                final SharedUserSetting sus = (SharedUserSetting) obj;
5596                return sus.pkgPrivateFlags;
5597            } else if (obj instanceof PackageSetting) {
5598                final PackageSetting ps = (PackageSetting) obj;
5599                return ps.pkgPrivateFlags;
5600            }
5601        }
5602        return 0;
5603    }
5604
5605    @Override
5606    public boolean isUidPrivileged(int uid) {
5607        uid = UserHandle.getAppId(uid);
5608        // reader
5609        synchronized (mPackages) {
5610            Object obj = mSettings.getUserIdLPr(uid);
5611            if (obj instanceof SharedUserSetting) {
5612                final SharedUserSetting sus = (SharedUserSetting) obj;
5613                final Iterator<PackageSetting> it = sus.packages.iterator();
5614                while (it.hasNext()) {
5615                    if (it.next().isPrivileged()) {
5616                        return true;
5617                    }
5618                }
5619            } else if (obj instanceof PackageSetting) {
5620                final PackageSetting ps = (PackageSetting) obj;
5621                return ps.isPrivileged();
5622            }
5623        }
5624        return false;
5625    }
5626
5627    @Override
5628    public String[] getAppOpPermissionPackages(String permissionName) {
5629        synchronized (mPackages) {
5630            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5631            if (pkgs == null) {
5632                return null;
5633            }
5634            return pkgs.toArray(new String[pkgs.size()]);
5635        }
5636    }
5637
5638    @Override
5639    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5640            int flags, int userId) {
5641        return resolveIntentInternal(
5642                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5643    }
5644
5645    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5646            int flags, int userId, boolean includeInstantApp) {
5647        try {
5648            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5649
5650            if (!sUserManager.exists(userId)) return null;
5651            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5652            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5653                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5654
5655            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5656            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5657                    flags, userId, includeInstantApp);
5658            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5659
5660            final ResolveInfo bestChoice =
5661                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5662            return bestChoice;
5663        } finally {
5664            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5665        }
5666    }
5667
5668    @Override
5669    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5670        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5671            throw new SecurityException(
5672                    "findPersistentPreferredActivity can only be run by the system");
5673        }
5674        if (!sUserManager.exists(userId)) {
5675            return null;
5676        }
5677        intent = updateIntentForResolve(intent);
5678        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5679        final int flags = updateFlagsForResolve(0, userId, intent, false);
5680        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5681                userId);
5682        synchronized (mPackages) {
5683            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5684                    userId);
5685        }
5686    }
5687
5688    @Override
5689    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5690            IntentFilter filter, int match, ComponentName activity) {
5691        final int userId = UserHandle.getCallingUserId();
5692        if (DEBUG_PREFERRED) {
5693            Log.v(TAG, "setLastChosenActivity intent=" + intent
5694                + " resolvedType=" + resolvedType
5695                + " flags=" + flags
5696                + " filter=" + filter
5697                + " match=" + match
5698                + " activity=" + activity);
5699            filter.dump(new PrintStreamPrinter(System.out), "    ");
5700        }
5701        intent.setComponent(null);
5702        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5703                userId);
5704        // Find any earlier preferred or last chosen entries and nuke them
5705        findPreferredActivity(intent, resolvedType,
5706                flags, query, 0, false, true, false, userId);
5707        // Add the new activity as the last chosen for this filter
5708        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5709                "Setting last chosen");
5710    }
5711
5712    @Override
5713    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5714        final int userId = UserHandle.getCallingUserId();
5715        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5716        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5717                userId);
5718        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5719                false, false, false, userId);
5720    }
5721
5722    /**
5723     * Returns whether or not instant apps have been disabled remotely.
5724     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5725     * held. Otherwise we run the risk of deadlock.
5726     */
5727    private boolean isEphemeralDisabled() {
5728        // ephemeral apps have been disabled across the board
5729        if (DISABLE_EPHEMERAL_APPS) {
5730            return true;
5731        }
5732        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5733        if (!mSystemReady) {
5734            return true;
5735        }
5736        // we can't get a content resolver until the system is ready; these checks must happen last
5737        final ContentResolver resolver = mContext.getContentResolver();
5738        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5739            return true;
5740        }
5741        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5742    }
5743
5744    private boolean isEphemeralAllowed(
5745            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5746            boolean skipPackageCheck) {
5747        final int callingUser = UserHandle.getCallingUserId();
5748        if (callingUser != UserHandle.USER_SYSTEM) {
5749            return false;
5750        }
5751        if (mInstantAppResolverConnection == null) {
5752            return false;
5753        }
5754        if (mInstantAppInstallerComponent == null) {
5755            return false;
5756        }
5757        if (intent.getComponent() != null) {
5758            return false;
5759        }
5760        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5761            return false;
5762        }
5763        if (!skipPackageCheck && intent.getPackage() != null) {
5764            return false;
5765        }
5766        final boolean isWebUri = hasWebURI(intent);
5767        if (!isWebUri || intent.getData().getHost() == null) {
5768            return false;
5769        }
5770        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5771        // Or if there's already an ephemeral app installed that handles the action
5772        synchronized (mPackages) {
5773            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5774            for (int n = 0; n < count; n++) {
5775                ResolveInfo info = resolvedActivities.get(n);
5776                String packageName = info.activityInfo.packageName;
5777                PackageSetting ps = mSettings.mPackages.get(packageName);
5778                if (ps != null) {
5779                    // Try to get the status from User settings first
5780                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5781                    int status = (int) (packedStatus >> 32);
5782                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5783                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5784                        if (DEBUG_EPHEMERAL) {
5785                            Slog.v(TAG, "DENY ephemeral apps;"
5786                                + " pkg: " + packageName + ", status: " + status);
5787                        }
5788                        return false;
5789                    }
5790                    if (ps.getInstantApp(userId)) {
5791                        return false;
5792                    }
5793                }
5794            }
5795        }
5796        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5797        return true;
5798    }
5799
5800    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5801            Intent origIntent, String resolvedType, String callingPackage,
5802            int userId) {
5803        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5804                new InstantAppRequest(responseObj, origIntent, resolvedType,
5805                        callingPackage, userId));
5806        mHandler.sendMessage(msg);
5807    }
5808
5809    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5810            int flags, List<ResolveInfo> query, int userId) {
5811        if (query != null) {
5812            final int N = query.size();
5813            if (N == 1) {
5814                return query.get(0);
5815            } else if (N > 1) {
5816                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5817                // If there is more than one activity with the same priority,
5818                // then let the user decide between them.
5819                ResolveInfo r0 = query.get(0);
5820                ResolveInfo r1 = query.get(1);
5821                if (DEBUG_INTENT_MATCHING || debug) {
5822                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5823                            + r1.activityInfo.name + "=" + r1.priority);
5824                }
5825                // If the first activity has a higher priority, or a different
5826                // default, then it is always desirable to pick it.
5827                if (r0.priority != r1.priority
5828                        || r0.preferredOrder != r1.preferredOrder
5829                        || r0.isDefault != r1.isDefault) {
5830                    return query.get(0);
5831                }
5832                // If we have saved a preference for a preferred activity for
5833                // this Intent, use that.
5834                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5835                        flags, query, r0.priority, true, false, debug, userId);
5836                if (ri != null) {
5837                    return ri;
5838                }
5839                // If we have an ephemeral app, use it
5840                for (int i = 0; i < N; i++) {
5841                    ri = query.get(i);
5842                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5843                        return ri;
5844                    }
5845                }
5846                ri = new ResolveInfo(mResolveInfo);
5847                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5848                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5849                // If all of the options come from the same package, show the application's
5850                // label and icon instead of the generic resolver's.
5851                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5852                // and then throw away the ResolveInfo itself, meaning that the caller loses
5853                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5854                // a fallback for this case; we only set the target package's resources on
5855                // the ResolveInfo, not the ActivityInfo.
5856                final String intentPackage = intent.getPackage();
5857                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5858                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5859                    ri.resolvePackageName = intentPackage;
5860                    if (userNeedsBadging(userId)) {
5861                        ri.noResourceId = true;
5862                    } else {
5863                        ri.icon = appi.icon;
5864                    }
5865                    ri.iconResourceId = appi.icon;
5866                    ri.labelRes = appi.labelRes;
5867                }
5868                ri.activityInfo.applicationInfo = new ApplicationInfo(
5869                        ri.activityInfo.applicationInfo);
5870                if (userId != 0) {
5871                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5872                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5873                }
5874                // Make sure that the resolver is displayable in car mode
5875                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5876                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5877                return ri;
5878            }
5879        }
5880        return null;
5881    }
5882
5883    /**
5884     * Return true if the given list is not empty and all of its contents have
5885     * an activityInfo with the given package name.
5886     */
5887    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5888        if (ArrayUtils.isEmpty(list)) {
5889            return false;
5890        }
5891        for (int i = 0, N = list.size(); i < N; i++) {
5892            final ResolveInfo ri = list.get(i);
5893            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5894            if (ai == null || !packageName.equals(ai.packageName)) {
5895                return false;
5896            }
5897        }
5898        return true;
5899    }
5900
5901    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5902            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5903        final int N = query.size();
5904        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5905                .get(userId);
5906        // Get the list of persistent preferred activities that handle the intent
5907        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5908        List<PersistentPreferredActivity> pprefs = ppir != null
5909                ? ppir.queryIntent(intent, resolvedType,
5910                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5911                        userId)
5912                : null;
5913        if (pprefs != null && pprefs.size() > 0) {
5914            final int M = pprefs.size();
5915            for (int i=0; i<M; i++) {
5916                final PersistentPreferredActivity ppa = pprefs.get(i);
5917                if (DEBUG_PREFERRED || debug) {
5918                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5919                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5920                            + "\n  component=" + ppa.mComponent);
5921                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5922                }
5923                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5924                        flags | MATCH_DISABLED_COMPONENTS, userId);
5925                if (DEBUG_PREFERRED || debug) {
5926                    Slog.v(TAG, "Found persistent preferred activity:");
5927                    if (ai != null) {
5928                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5929                    } else {
5930                        Slog.v(TAG, "  null");
5931                    }
5932                }
5933                if (ai == null) {
5934                    // This previously registered persistent preferred activity
5935                    // component is no longer known. Ignore it and do NOT remove it.
5936                    continue;
5937                }
5938                for (int j=0; j<N; j++) {
5939                    final ResolveInfo ri = query.get(j);
5940                    if (!ri.activityInfo.applicationInfo.packageName
5941                            .equals(ai.applicationInfo.packageName)) {
5942                        continue;
5943                    }
5944                    if (!ri.activityInfo.name.equals(ai.name)) {
5945                        continue;
5946                    }
5947                    //  Found a persistent preference that can handle the intent.
5948                    if (DEBUG_PREFERRED || debug) {
5949                        Slog.v(TAG, "Returning persistent preferred activity: " +
5950                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5951                    }
5952                    return ri;
5953                }
5954            }
5955        }
5956        return null;
5957    }
5958
5959    // TODO: handle preferred activities missing while user has amnesia
5960    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5961            List<ResolveInfo> query, int priority, boolean always,
5962            boolean removeMatches, boolean debug, int userId) {
5963        if (!sUserManager.exists(userId)) return null;
5964        flags = updateFlagsForResolve(flags, userId, intent, false);
5965        intent = updateIntentForResolve(intent);
5966        // writer
5967        synchronized (mPackages) {
5968            // Try to find a matching persistent preferred activity.
5969            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5970                    debug, userId);
5971
5972            // If a persistent preferred activity matched, use it.
5973            if (pri != null) {
5974                return pri;
5975            }
5976
5977            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5978            // Get the list of preferred activities that handle the intent
5979            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5980            List<PreferredActivity> prefs = pir != null
5981                    ? pir.queryIntent(intent, resolvedType,
5982                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5983                            userId)
5984                    : null;
5985            if (prefs != null && prefs.size() > 0) {
5986                boolean changed = false;
5987                try {
5988                    // First figure out how good the original match set is.
5989                    // We will only allow preferred activities that came
5990                    // from the same match quality.
5991                    int match = 0;
5992
5993                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5994
5995                    final int N = query.size();
5996                    for (int j=0; j<N; j++) {
5997                        final ResolveInfo ri = query.get(j);
5998                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5999                                + ": 0x" + Integer.toHexString(match));
6000                        if (ri.match > match) {
6001                            match = ri.match;
6002                        }
6003                    }
6004
6005                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6006                            + Integer.toHexString(match));
6007
6008                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6009                    final int M = prefs.size();
6010                    for (int i=0; i<M; i++) {
6011                        final PreferredActivity pa = prefs.get(i);
6012                        if (DEBUG_PREFERRED || debug) {
6013                            Slog.v(TAG, "Checking PreferredActivity ds="
6014                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6015                                    + "\n  component=" + pa.mPref.mComponent);
6016                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6017                        }
6018                        if (pa.mPref.mMatch != match) {
6019                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6020                                    + Integer.toHexString(pa.mPref.mMatch));
6021                            continue;
6022                        }
6023                        // If it's not an "always" type preferred activity and that's what we're
6024                        // looking for, skip it.
6025                        if (always && !pa.mPref.mAlways) {
6026                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6027                            continue;
6028                        }
6029                        final ActivityInfo ai = getActivityInfo(
6030                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6031                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6032                                userId);
6033                        if (DEBUG_PREFERRED || debug) {
6034                            Slog.v(TAG, "Found preferred activity:");
6035                            if (ai != null) {
6036                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6037                            } else {
6038                                Slog.v(TAG, "  null");
6039                            }
6040                        }
6041                        if (ai == null) {
6042                            // This previously registered preferred activity
6043                            // component is no longer known.  Most likely an update
6044                            // to the app was installed and in the new version this
6045                            // component no longer exists.  Clean it up by removing
6046                            // it from the preferred activities list, and skip it.
6047                            Slog.w(TAG, "Removing dangling preferred activity: "
6048                                    + pa.mPref.mComponent);
6049                            pir.removeFilter(pa);
6050                            changed = true;
6051                            continue;
6052                        }
6053                        for (int j=0; j<N; j++) {
6054                            final ResolveInfo ri = query.get(j);
6055                            if (!ri.activityInfo.applicationInfo.packageName
6056                                    .equals(ai.applicationInfo.packageName)) {
6057                                continue;
6058                            }
6059                            if (!ri.activityInfo.name.equals(ai.name)) {
6060                                continue;
6061                            }
6062
6063                            if (removeMatches) {
6064                                pir.removeFilter(pa);
6065                                changed = true;
6066                                if (DEBUG_PREFERRED) {
6067                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6068                                }
6069                                break;
6070                            }
6071
6072                            // Okay we found a previously set preferred or last chosen app.
6073                            // If the result set is different from when this
6074                            // was created, we need to clear it and re-ask the
6075                            // user their preference, if we're looking for an "always" type entry.
6076                            if (always && !pa.mPref.sameSet(query)) {
6077                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6078                                        + intent + " type " + resolvedType);
6079                                if (DEBUG_PREFERRED) {
6080                                    Slog.v(TAG, "Removing preferred activity since set changed "
6081                                            + pa.mPref.mComponent);
6082                                }
6083                                pir.removeFilter(pa);
6084                                // Re-add the filter as a "last chosen" entry (!always)
6085                                PreferredActivity lastChosen = new PreferredActivity(
6086                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6087                                pir.addFilter(lastChosen);
6088                                changed = true;
6089                                return null;
6090                            }
6091
6092                            // Yay! Either the set matched or we're looking for the last chosen
6093                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6094                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6095                            return ri;
6096                        }
6097                    }
6098                } finally {
6099                    if (changed) {
6100                        if (DEBUG_PREFERRED) {
6101                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6102                        }
6103                        scheduleWritePackageRestrictionsLocked(userId);
6104                    }
6105                }
6106            }
6107        }
6108        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6109        return null;
6110    }
6111
6112    /*
6113     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6114     */
6115    @Override
6116    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6117            int targetUserId) {
6118        mContext.enforceCallingOrSelfPermission(
6119                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6120        List<CrossProfileIntentFilter> matches =
6121                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6122        if (matches != null) {
6123            int size = matches.size();
6124            for (int i = 0; i < size; i++) {
6125                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6126            }
6127        }
6128        if (hasWebURI(intent)) {
6129            // cross-profile app linking works only towards the parent.
6130            final UserInfo parent = getProfileParent(sourceUserId);
6131            synchronized(mPackages) {
6132                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6133                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6134                        intent, resolvedType, flags, sourceUserId, parent.id);
6135                return xpDomainInfo != null;
6136            }
6137        }
6138        return false;
6139    }
6140
6141    private UserInfo getProfileParent(int userId) {
6142        final long identity = Binder.clearCallingIdentity();
6143        try {
6144            return sUserManager.getProfileParent(userId);
6145        } finally {
6146            Binder.restoreCallingIdentity(identity);
6147        }
6148    }
6149
6150    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6151            String resolvedType, int userId) {
6152        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6153        if (resolver != null) {
6154            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6155        }
6156        return null;
6157    }
6158
6159    @Override
6160    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6161            String resolvedType, int flags, int userId) {
6162        try {
6163            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6164
6165            return new ParceledListSlice<>(
6166                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6167        } finally {
6168            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6169        }
6170    }
6171
6172    /**
6173     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6174     * instant, returns {@code null}.
6175     */
6176    private String getInstantAppPackageName(int callingUid) {
6177        final int appId = UserHandle.getAppId(callingUid);
6178        synchronized (mPackages) {
6179            final Object obj = mSettings.getUserIdLPr(appId);
6180            if (obj instanceof PackageSetting) {
6181                final PackageSetting ps = (PackageSetting) obj;
6182                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6183                return isInstantApp ? ps.pkg.packageName : null;
6184            }
6185        }
6186        return null;
6187    }
6188
6189    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6190            String resolvedType, int flags, int userId) {
6191        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6192    }
6193
6194    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6195            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6196        if (!sUserManager.exists(userId)) return Collections.emptyList();
6197        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6198        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6199        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6200                false /* requireFullPermission */, false /* checkShell */,
6201                "query intent activities");
6202        ComponentName comp = intent.getComponent();
6203        if (comp == null) {
6204            if (intent.getSelector() != null) {
6205                intent = intent.getSelector();
6206                comp = intent.getComponent();
6207            }
6208        }
6209
6210        if (comp != null) {
6211            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6212            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6213            if (ai != null) {
6214                // When specifying an explicit component, we prevent the activity from being
6215                // used when either 1) the calling package is normal and the activity is within
6216                // an ephemeral application or 2) the calling package is ephemeral and the
6217                // activity is not visible to ephemeral applications.
6218                final boolean matchInstantApp =
6219                        (flags & PackageManager.MATCH_INSTANT) != 0;
6220                final boolean matchVisibleToInstantAppOnly =
6221                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6222                final boolean isCallerInstantApp =
6223                        instantAppPkgName != null;
6224                final boolean isTargetSameInstantApp =
6225                        comp.getPackageName().equals(instantAppPkgName);
6226                final boolean isTargetInstantApp =
6227                        (ai.applicationInfo.privateFlags
6228                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6229                final boolean isTargetHiddenFromInstantApp =
6230                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6231                final boolean blockResolution =
6232                        !isTargetSameInstantApp
6233                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6234                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6235                                        && isTargetHiddenFromInstantApp));
6236                if (!blockResolution) {
6237                    final ResolveInfo ri = new ResolveInfo();
6238                    ri.activityInfo = ai;
6239                    list.add(ri);
6240                }
6241            }
6242            return applyPostResolutionFilter(list, instantAppPkgName);
6243        }
6244
6245        // reader
6246        boolean sortResult = false;
6247        boolean addEphemeral = false;
6248        List<ResolveInfo> result;
6249        final String pkgName = intent.getPackage();
6250        final boolean ephemeralDisabled = isEphemeralDisabled();
6251        synchronized (mPackages) {
6252            if (pkgName == null) {
6253                List<CrossProfileIntentFilter> matchingFilters =
6254                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6255                // Check for results that need to skip the current profile.
6256                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6257                        resolvedType, flags, userId);
6258                if (xpResolveInfo != null) {
6259                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6260                    xpResult.add(xpResolveInfo);
6261                    return applyPostResolutionFilter(
6262                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6263                }
6264
6265                // Check for results in the current profile.
6266                result = filterIfNotSystemUser(mActivities.queryIntent(
6267                        intent, resolvedType, flags, userId), userId);
6268                addEphemeral = !ephemeralDisabled
6269                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6270
6271                // Check for cross profile results.
6272                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6273                xpResolveInfo = queryCrossProfileIntents(
6274                        matchingFilters, intent, resolvedType, flags, userId,
6275                        hasNonNegativePriorityResult);
6276                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6277                    boolean isVisibleToUser = filterIfNotSystemUser(
6278                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6279                    if (isVisibleToUser) {
6280                        result.add(xpResolveInfo);
6281                        sortResult = true;
6282                    }
6283                }
6284                if (hasWebURI(intent)) {
6285                    CrossProfileDomainInfo xpDomainInfo = null;
6286                    final UserInfo parent = getProfileParent(userId);
6287                    if (parent != null) {
6288                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6289                                flags, userId, parent.id);
6290                    }
6291                    if (xpDomainInfo != null) {
6292                        if (xpResolveInfo != null) {
6293                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6294                            // in the result.
6295                            result.remove(xpResolveInfo);
6296                        }
6297                        if (result.size() == 0 && !addEphemeral) {
6298                            // No result in current profile, but found candidate in parent user.
6299                            // And we are not going to add emphemeral app, so we can return the
6300                            // result straight away.
6301                            result.add(xpDomainInfo.resolveInfo);
6302                            return applyPostResolutionFilter(result, instantAppPkgName);
6303                        }
6304                    } else if (result.size() <= 1 && !addEphemeral) {
6305                        // No result in parent user and <= 1 result in current profile, and we
6306                        // are not going to add emphemeral app, so we can return the result without
6307                        // further processing.
6308                        return applyPostResolutionFilter(result, instantAppPkgName);
6309                    }
6310                    // We have more than one candidate (combining results from current and parent
6311                    // profile), so we need filtering and sorting.
6312                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6313                            intent, flags, result, xpDomainInfo, userId);
6314                    sortResult = true;
6315                }
6316            } else {
6317                final PackageParser.Package pkg = mPackages.get(pkgName);
6318                if (pkg != null) {
6319                    return applyPostResolutionFilter(filterIfNotSystemUser(
6320                            mActivities.queryIntentForPackage(
6321                                    intent, resolvedType, flags, pkg.activities, userId),
6322                            userId), instantAppPkgName);
6323                } else {
6324                    // the caller wants to resolve for a particular package; however, there
6325                    // were no installed results, so, try to find an ephemeral result
6326                    addEphemeral =  !ephemeralDisabled
6327                            && isEphemeralAllowed(
6328                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6329                    result = new ArrayList<ResolveInfo>();
6330                }
6331            }
6332        }
6333        if (addEphemeral) {
6334            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6335            final InstantAppRequest requestObject = new InstantAppRequest(
6336                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6337                    null /*callingPackage*/, userId);
6338            final AuxiliaryResolveInfo auxiliaryResponse =
6339                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6340                            mContext, mInstantAppResolverConnection, requestObject);
6341            if (auxiliaryResponse != null) {
6342                if (DEBUG_EPHEMERAL) {
6343                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6344                }
6345                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6346                ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity);
6347                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6348                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6349                // make sure this resolver is the default
6350                ephemeralInstaller.isDefault = true;
6351                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6352                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6353                // add a non-generic filter
6354                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6355                ephemeralInstaller.filter.addDataPath(
6356                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6357                ephemeralInstaller.instantAppAvailable = true;
6358                result.add(ephemeralInstaller);
6359            }
6360            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6361        }
6362        if (sortResult) {
6363            Collections.sort(result, mResolvePrioritySorter);
6364        }
6365        return applyPostResolutionFilter(result, instantAppPkgName);
6366    }
6367
6368    private static class CrossProfileDomainInfo {
6369        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6370        ResolveInfo resolveInfo;
6371        /* Best domain verification status of the activities found in the other profile */
6372        int bestDomainVerificationStatus;
6373    }
6374
6375    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6376            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6377        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6378                sourceUserId)) {
6379            return null;
6380        }
6381        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6382                resolvedType, flags, parentUserId);
6383
6384        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6385            return null;
6386        }
6387        CrossProfileDomainInfo result = null;
6388        int size = resultTargetUser.size();
6389        for (int i = 0; i < size; i++) {
6390            ResolveInfo riTargetUser = resultTargetUser.get(i);
6391            // Intent filter verification is only for filters that specify a host. So don't return
6392            // those that handle all web uris.
6393            if (riTargetUser.handleAllWebDataURI) {
6394                continue;
6395            }
6396            String packageName = riTargetUser.activityInfo.packageName;
6397            PackageSetting ps = mSettings.mPackages.get(packageName);
6398            if (ps == null) {
6399                continue;
6400            }
6401            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6402            int status = (int)(verificationState >> 32);
6403            if (result == null) {
6404                result = new CrossProfileDomainInfo();
6405                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6406                        sourceUserId, parentUserId);
6407                result.bestDomainVerificationStatus = status;
6408            } else {
6409                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6410                        result.bestDomainVerificationStatus);
6411            }
6412        }
6413        // Don't consider matches with status NEVER across profiles.
6414        if (result != null && result.bestDomainVerificationStatus
6415                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6416            return null;
6417        }
6418        return result;
6419    }
6420
6421    /**
6422     * Verification statuses are ordered from the worse to the best, except for
6423     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6424     */
6425    private int bestDomainVerificationStatus(int status1, int status2) {
6426        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6427            return status2;
6428        }
6429        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6430            return status1;
6431        }
6432        return (int) MathUtils.max(status1, status2);
6433    }
6434
6435    private boolean isUserEnabled(int userId) {
6436        long callingId = Binder.clearCallingIdentity();
6437        try {
6438            UserInfo userInfo = sUserManager.getUserInfo(userId);
6439            return userInfo != null && userInfo.isEnabled();
6440        } finally {
6441            Binder.restoreCallingIdentity(callingId);
6442        }
6443    }
6444
6445    /**
6446     * Filter out activities with systemUserOnly flag set, when current user is not System.
6447     *
6448     * @return filtered list
6449     */
6450    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6451        if (userId == UserHandle.USER_SYSTEM) {
6452            return resolveInfos;
6453        }
6454        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6455            ResolveInfo info = resolveInfos.get(i);
6456            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6457                resolveInfos.remove(i);
6458            }
6459        }
6460        return resolveInfos;
6461    }
6462
6463    /**
6464     * Filters out ephemeral activities.
6465     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6466     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6467     *
6468     * @param resolveInfos The pre-filtered list of resolved activities
6469     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6470     *          is performed.
6471     * @return A filtered list of resolved activities.
6472     */
6473    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6474            String ephemeralPkgName) {
6475        // TODO: When adding on-demand split support for non-instant apps, remove this check
6476        // and always apply post filtering
6477        if (ephemeralPkgName == null) {
6478            return resolveInfos;
6479        }
6480        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6481            final ResolveInfo info = resolveInfos.get(i);
6482            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6483            // allow activities that are defined in the provided package
6484            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6485                if (info.activityInfo.splitName != null
6486                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6487                                info.activityInfo.splitName)) {
6488                    // requested activity is defined in a split that hasn't been installed yet.
6489                    // add the installer to the resolve list
6490                    if (DEBUG_EPHEMERAL) {
6491                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6492                    }
6493                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6494                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6495                            info.activityInfo.packageName, info.activityInfo.splitName,
6496                            info.activityInfo.applicationInfo.versionCode);
6497                    // make sure this resolver is the default
6498                    installerInfo.isDefault = true;
6499                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6500                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6501                    // add a non-generic filter
6502                    installerInfo.filter = new IntentFilter();
6503                    // load resources from the correct package
6504                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6505                    resolveInfos.set(i, installerInfo);
6506                }
6507                continue;
6508            }
6509            // allow activities that have been explicitly exposed to ephemeral apps
6510            if (!isEphemeralApp
6511                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6512                continue;
6513            }
6514            resolveInfos.remove(i);
6515        }
6516        return resolveInfos;
6517    }
6518
6519    /**
6520     * @param resolveInfos list of resolve infos in descending priority order
6521     * @return if the list contains a resolve info with non-negative priority
6522     */
6523    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6524        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6525    }
6526
6527    private static boolean hasWebURI(Intent intent) {
6528        if (intent.getData() == null) {
6529            return false;
6530        }
6531        final String scheme = intent.getScheme();
6532        if (TextUtils.isEmpty(scheme)) {
6533            return false;
6534        }
6535        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6536    }
6537
6538    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6539            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6540            int userId) {
6541        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6542
6543        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6544            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6545                    candidates.size());
6546        }
6547
6548        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6549        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6550        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6551        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6552        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6553        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6554
6555        synchronized (mPackages) {
6556            final int count = candidates.size();
6557            // First, try to use linked apps. Partition the candidates into four lists:
6558            // one for the final results, one for the "do not use ever", one for "undefined status"
6559            // and finally one for "browser app type".
6560            for (int n=0; n<count; n++) {
6561                ResolveInfo info = candidates.get(n);
6562                String packageName = info.activityInfo.packageName;
6563                PackageSetting ps = mSettings.mPackages.get(packageName);
6564                if (ps != null) {
6565                    // Add to the special match all list (Browser use case)
6566                    if (info.handleAllWebDataURI) {
6567                        matchAllList.add(info);
6568                        continue;
6569                    }
6570                    // Try to get the status from User settings first
6571                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6572                    int status = (int)(packedStatus >> 32);
6573                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6574                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6575                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6576                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6577                                    + " : linkgen=" + linkGeneration);
6578                        }
6579                        // Use link-enabled generation as preferredOrder, i.e.
6580                        // prefer newly-enabled over earlier-enabled.
6581                        info.preferredOrder = linkGeneration;
6582                        alwaysList.add(info);
6583                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6584                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6585                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6586                        }
6587                        neverList.add(info);
6588                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6589                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6590                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6591                        }
6592                        alwaysAskList.add(info);
6593                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6594                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6595                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6596                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6597                        }
6598                        undefinedList.add(info);
6599                    }
6600                }
6601            }
6602
6603            // We'll want to include browser possibilities in a few cases
6604            boolean includeBrowser = false;
6605
6606            // First try to add the "always" resolution(s) for the current user, if any
6607            if (alwaysList.size() > 0) {
6608                result.addAll(alwaysList);
6609            } else {
6610                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6611                result.addAll(undefinedList);
6612                // Maybe add one for the other profile.
6613                if (xpDomainInfo != null && (
6614                        xpDomainInfo.bestDomainVerificationStatus
6615                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6616                    result.add(xpDomainInfo.resolveInfo);
6617                }
6618                includeBrowser = true;
6619            }
6620
6621            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6622            // If there were 'always' entries their preferred order has been set, so we also
6623            // back that off to make the alternatives equivalent
6624            if (alwaysAskList.size() > 0) {
6625                for (ResolveInfo i : result) {
6626                    i.preferredOrder = 0;
6627                }
6628                result.addAll(alwaysAskList);
6629                includeBrowser = true;
6630            }
6631
6632            if (includeBrowser) {
6633                // Also add browsers (all of them or only the default one)
6634                if (DEBUG_DOMAIN_VERIFICATION) {
6635                    Slog.v(TAG, "   ...including browsers in candidate set");
6636                }
6637                if ((matchFlags & MATCH_ALL) != 0) {
6638                    result.addAll(matchAllList);
6639                } else {
6640                    // Browser/generic handling case.  If there's a default browser, go straight
6641                    // to that (but only if there is no other higher-priority match).
6642                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6643                    int maxMatchPrio = 0;
6644                    ResolveInfo defaultBrowserMatch = null;
6645                    final int numCandidates = matchAllList.size();
6646                    for (int n = 0; n < numCandidates; n++) {
6647                        ResolveInfo info = matchAllList.get(n);
6648                        // track the highest overall match priority...
6649                        if (info.priority > maxMatchPrio) {
6650                            maxMatchPrio = info.priority;
6651                        }
6652                        // ...and the highest-priority default browser match
6653                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6654                            if (defaultBrowserMatch == null
6655                                    || (defaultBrowserMatch.priority < info.priority)) {
6656                                if (debug) {
6657                                    Slog.v(TAG, "Considering default browser match " + info);
6658                                }
6659                                defaultBrowserMatch = info;
6660                            }
6661                        }
6662                    }
6663                    if (defaultBrowserMatch != null
6664                            && defaultBrowserMatch.priority >= maxMatchPrio
6665                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6666                    {
6667                        if (debug) {
6668                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6669                        }
6670                        result.add(defaultBrowserMatch);
6671                    } else {
6672                        result.addAll(matchAllList);
6673                    }
6674                }
6675
6676                // If there is nothing selected, add all candidates and remove the ones that the user
6677                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6678                if (result.size() == 0) {
6679                    result.addAll(candidates);
6680                    result.removeAll(neverList);
6681                }
6682            }
6683        }
6684        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6685            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6686                    result.size());
6687            for (ResolveInfo info : result) {
6688                Slog.v(TAG, "  + " + info.activityInfo);
6689            }
6690        }
6691        return result;
6692    }
6693
6694    // Returns a packed value as a long:
6695    //
6696    // high 'int'-sized word: link status: undefined/ask/never/always.
6697    // low 'int'-sized word: relative priority among 'always' results.
6698    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6699        long result = ps.getDomainVerificationStatusForUser(userId);
6700        // if none available, get the master status
6701        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6702            if (ps.getIntentFilterVerificationInfo() != null) {
6703                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6704            }
6705        }
6706        return result;
6707    }
6708
6709    private ResolveInfo querySkipCurrentProfileIntents(
6710            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6711            int flags, int sourceUserId) {
6712        if (matchingFilters != null) {
6713            int size = matchingFilters.size();
6714            for (int i = 0; i < size; i ++) {
6715                CrossProfileIntentFilter filter = matchingFilters.get(i);
6716                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6717                    // Checking if there are activities in the target user that can handle the
6718                    // intent.
6719                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6720                            resolvedType, flags, sourceUserId);
6721                    if (resolveInfo != null) {
6722                        return resolveInfo;
6723                    }
6724                }
6725            }
6726        }
6727        return null;
6728    }
6729
6730    // Return matching ResolveInfo in target user if any.
6731    private ResolveInfo queryCrossProfileIntents(
6732            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6733            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6734        if (matchingFilters != null) {
6735            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6736            // match the same intent. For performance reasons, it is better not to
6737            // run queryIntent twice for the same userId
6738            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6739            int size = matchingFilters.size();
6740            for (int i = 0; i < size; i++) {
6741                CrossProfileIntentFilter filter = matchingFilters.get(i);
6742                int targetUserId = filter.getTargetUserId();
6743                boolean skipCurrentProfile =
6744                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6745                boolean skipCurrentProfileIfNoMatchFound =
6746                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6747                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6748                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6749                    // Checking if there are activities in the target user that can handle the
6750                    // intent.
6751                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6752                            resolvedType, flags, sourceUserId);
6753                    if (resolveInfo != null) return resolveInfo;
6754                    alreadyTriedUserIds.put(targetUserId, true);
6755                }
6756            }
6757        }
6758        return null;
6759    }
6760
6761    /**
6762     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6763     * will forward the intent to the filter's target user.
6764     * Otherwise, returns null.
6765     */
6766    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6767            String resolvedType, int flags, int sourceUserId) {
6768        int targetUserId = filter.getTargetUserId();
6769        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6770                resolvedType, flags, targetUserId);
6771        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6772            // If all the matches in the target profile are suspended, return null.
6773            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6774                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6775                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6776                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6777                            targetUserId);
6778                }
6779            }
6780        }
6781        return null;
6782    }
6783
6784    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6785            int sourceUserId, int targetUserId) {
6786        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6787        long ident = Binder.clearCallingIdentity();
6788        boolean targetIsProfile;
6789        try {
6790            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6791        } finally {
6792            Binder.restoreCallingIdentity(ident);
6793        }
6794        String className;
6795        if (targetIsProfile) {
6796            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6797        } else {
6798            className = FORWARD_INTENT_TO_PARENT;
6799        }
6800        ComponentName forwardingActivityComponentName = new ComponentName(
6801                mAndroidApplication.packageName, className);
6802        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6803                sourceUserId);
6804        if (!targetIsProfile) {
6805            forwardingActivityInfo.showUserIcon = targetUserId;
6806            forwardingResolveInfo.noResourceId = true;
6807        }
6808        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6809        forwardingResolveInfo.priority = 0;
6810        forwardingResolveInfo.preferredOrder = 0;
6811        forwardingResolveInfo.match = 0;
6812        forwardingResolveInfo.isDefault = true;
6813        forwardingResolveInfo.filter = filter;
6814        forwardingResolveInfo.targetUserId = targetUserId;
6815        return forwardingResolveInfo;
6816    }
6817
6818    @Override
6819    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6820            Intent[] specifics, String[] specificTypes, Intent intent,
6821            String resolvedType, int flags, int userId) {
6822        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6823                specificTypes, intent, resolvedType, flags, userId));
6824    }
6825
6826    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6827            Intent[] specifics, String[] specificTypes, Intent intent,
6828            String resolvedType, int flags, int userId) {
6829        if (!sUserManager.exists(userId)) return Collections.emptyList();
6830        flags = updateFlagsForResolve(flags, userId, intent, false);
6831        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6832                false /* requireFullPermission */, false /* checkShell */,
6833                "query intent activity options");
6834        final String resultsAction = intent.getAction();
6835
6836        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6837                | PackageManager.GET_RESOLVED_FILTER, userId);
6838
6839        if (DEBUG_INTENT_MATCHING) {
6840            Log.v(TAG, "Query " + intent + ": " + results);
6841        }
6842
6843        int specificsPos = 0;
6844        int N;
6845
6846        // todo: note that the algorithm used here is O(N^2).  This
6847        // isn't a problem in our current environment, but if we start running
6848        // into situations where we have more than 5 or 10 matches then this
6849        // should probably be changed to something smarter...
6850
6851        // First we go through and resolve each of the specific items
6852        // that were supplied, taking care of removing any corresponding
6853        // duplicate items in the generic resolve list.
6854        if (specifics != null) {
6855            for (int i=0; i<specifics.length; i++) {
6856                final Intent sintent = specifics[i];
6857                if (sintent == null) {
6858                    continue;
6859                }
6860
6861                if (DEBUG_INTENT_MATCHING) {
6862                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6863                }
6864
6865                String action = sintent.getAction();
6866                if (resultsAction != null && resultsAction.equals(action)) {
6867                    // If this action was explicitly requested, then don't
6868                    // remove things that have it.
6869                    action = null;
6870                }
6871
6872                ResolveInfo ri = null;
6873                ActivityInfo ai = null;
6874
6875                ComponentName comp = sintent.getComponent();
6876                if (comp == null) {
6877                    ri = resolveIntent(
6878                        sintent,
6879                        specificTypes != null ? specificTypes[i] : null,
6880                            flags, userId);
6881                    if (ri == null) {
6882                        continue;
6883                    }
6884                    if (ri == mResolveInfo) {
6885                        // ACK!  Must do something better with this.
6886                    }
6887                    ai = ri.activityInfo;
6888                    comp = new ComponentName(ai.applicationInfo.packageName,
6889                            ai.name);
6890                } else {
6891                    ai = getActivityInfo(comp, flags, userId);
6892                    if (ai == null) {
6893                        continue;
6894                    }
6895                }
6896
6897                // Look for any generic query activities that are duplicates
6898                // of this specific one, and remove them from the results.
6899                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6900                N = results.size();
6901                int j;
6902                for (j=specificsPos; j<N; j++) {
6903                    ResolveInfo sri = results.get(j);
6904                    if ((sri.activityInfo.name.equals(comp.getClassName())
6905                            && sri.activityInfo.applicationInfo.packageName.equals(
6906                                    comp.getPackageName()))
6907                        || (action != null && sri.filter.matchAction(action))) {
6908                        results.remove(j);
6909                        if (DEBUG_INTENT_MATCHING) Log.v(
6910                            TAG, "Removing duplicate item from " + j
6911                            + " due to specific " + specificsPos);
6912                        if (ri == null) {
6913                            ri = sri;
6914                        }
6915                        j--;
6916                        N--;
6917                    }
6918                }
6919
6920                // Add this specific item to its proper place.
6921                if (ri == null) {
6922                    ri = new ResolveInfo();
6923                    ri.activityInfo = ai;
6924                }
6925                results.add(specificsPos, ri);
6926                ri.specificIndex = i;
6927                specificsPos++;
6928            }
6929        }
6930
6931        // Now we go through the remaining generic results and remove any
6932        // duplicate actions that are found here.
6933        N = results.size();
6934        for (int i=specificsPos; i<N-1; i++) {
6935            final ResolveInfo rii = results.get(i);
6936            if (rii.filter == null) {
6937                continue;
6938            }
6939
6940            // Iterate over all of the actions of this result's intent
6941            // filter...  typically this should be just one.
6942            final Iterator<String> it = rii.filter.actionsIterator();
6943            if (it == null) {
6944                continue;
6945            }
6946            while (it.hasNext()) {
6947                final String action = it.next();
6948                if (resultsAction != null && resultsAction.equals(action)) {
6949                    // If this action was explicitly requested, then don't
6950                    // remove things that have it.
6951                    continue;
6952                }
6953                for (int j=i+1; j<N; j++) {
6954                    final ResolveInfo rij = results.get(j);
6955                    if (rij.filter != null && rij.filter.hasAction(action)) {
6956                        results.remove(j);
6957                        if (DEBUG_INTENT_MATCHING) Log.v(
6958                            TAG, "Removing duplicate item from " + j
6959                            + " due to action " + action + " at " + i);
6960                        j--;
6961                        N--;
6962                    }
6963                }
6964            }
6965
6966            // If the caller didn't request filter information, drop it now
6967            // so we don't have to marshall/unmarshall it.
6968            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6969                rii.filter = null;
6970            }
6971        }
6972
6973        // Filter out the caller activity if so requested.
6974        if (caller != null) {
6975            N = results.size();
6976            for (int i=0; i<N; i++) {
6977                ActivityInfo ainfo = results.get(i).activityInfo;
6978                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6979                        && caller.getClassName().equals(ainfo.name)) {
6980                    results.remove(i);
6981                    break;
6982                }
6983            }
6984        }
6985
6986        // If the caller didn't request filter information,
6987        // drop them now so we don't have to
6988        // marshall/unmarshall it.
6989        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6990            N = results.size();
6991            for (int i=0; i<N; i++) {
6992                results.get(i).filter = null;
6993            }
6994        }
6995
6996        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6997        return results;
6998    }
6999
7000    @Override
7001    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7002            String resolvedType, int flags, int userId) {
7003        return new ParceledListSlice<>(
7004                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7005    }
7006
7007    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7008            String resolvedType, int flags, int userId) {
7009        if (!sUserManager.exists(userId)) return Collections.emptyList();
7010        flags = updateFlagsForResolve(flags, userId, intent, false);
7011        ComponentName comp = intent.getComponent();
7012        if (comp == null) {
7013            if (intent.getSelector() != null) {
7014                intent = intent.getSelector();
7015                comp = intent.getComponent();
7016            }
7017        }
7018        if (comp != null) {
7019            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7020            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7021            if (ai != null) {
7022                ResolveInfo ri = new ResolveInfo();
7023                ri.activityInfo = ai;
7024                list.add(ri);
7025            }
7026            return list;
7027        }
7028
7029        // reader
7030        synchronized (mPackages) {
7031            String pkgName = intent.getPackage();
7032            if (pkgName == null) {
7033                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7034            }
7035            final PackageParser.Package pkg = mPackages.get(pkgName);
7036            if (pkg != null) {
7037                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7038                        userId);
7039            }
7040            return Collections.emptyList();
7041        }
7042    }
7043
7044    @Override
7045    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7046        if (!sUserManager.exists(userId)) return null;
7047        flags = updateFlagsForResolve(flags, userId, intent, false);
7048        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7049        if (query != null) {
7050            if (query.size() >= 1) {
7051                // If there is more than one service with the same priority,
7052                // just arbitrarily pick the first one.
7053                return query.get(0);
7054            }
7055        }
7056        return null;
7057    }
7058
7059    @Override
7060    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7061            String resolvedType, int flags, int userId) {
7062        return new ParceledListSlice<>(
7063                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7064    }
7065
7066    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7067            String resolvedType, int flags, int userId) {
7068        if (!sUserManager.exists(userId)) return Collections.emptyList();
7069        flags = updateFlagsForResolve(flags, userId, intent, false);
7070        ComponentName comp = intent.getComponent();
7071        if (comp == null) {
7072            if (intent.getSelector() != null) {
7073                intent = intent.getSelector();
7074                comp = intent.getComponent();
7075            }
7076        }
7077        if (comp != null) {
7078            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7079            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7080            if (si != null) {
7081                final ResolveInfo ri = new ResolveInfo();
7082                ri.serviceInfo = si;
7083                list.add(ri);
7084            }
7085            return list;
7086        }
7087
7088        // reader
7089        synchronized (mPackages) {
7090            String pkgName = intent.getPackage();
7091            if (pkgName == null) {
7092                return mServices.queryIntent(intent, resolvedType, flags, userId);
7093            }
7094            final PackageParser.Package pkg = mPackages.get(pkgName);
7095            if (pkg != null) {
7096                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7097                        userId);
7098            }
7099            return Collections.emptyList();
7100        }
7101    }
7102
7103    @Override
7104    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7105            String resolvedType, int flags, int userId) {
7106        return new ParceledListSlice<>(
7107                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7108    }
7109
7110    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7111            Intent intent, String resolvedType, int flags, int userId) {
7112        if (!sUserManager.exists(userId)) return Collections.emptyList();
7113        flags = updateFlagsForResolve(flags, userId, intent, false);
7114        ComponentName comp = intent.getComponent();
7115        if (comp == null) {
7116            if (intent.getSelector() != null) {
7117                intent = intent.getSelector();
7118                comp = intent.getComponent();
7119            }
7120        }
7121        if (comp != null) {
7122            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7123            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7124            if (pi != null) {
7125                final ResolveInfo ri = new ResolveInfo();
7126                ri.providerInfo = pi;
7127                list.add(ri);
7128            }
7129            return list;
7130        }
7131
7132        // reader
7133        synchronized (mPackages) {
7134            String pkgName = intent.getPackage();
7135            if (pkgName == null) {
7136                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7137            }
7138            final PackageParser.Package pkg = mPackages.get(pkgName);
7139            if (pkg != null) {
7140                return mProviders.queryIntentForPackage(
7141                        intent, resolvedType, flags, pkg.providers, userId);
7142            }
7143            return Collections.emptyList();
7144        }
7145    }
7146
7147    @Override
7148    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7149        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7150        flags = updateFlagsForPackage(flags, userId, null);
7151        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7152        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7153                true /* requireFullPermission */, false /* checkShell */,
7154                "get installed packages");
7155
7156        // writer
7157        synchronized (mPackages) {
7158            ArrayList<PackageInfo> list;
7159            if (listUninstalled) {
7160                list = new ArrayList<>(mSettings.mPackages.size());
7161                for (PackageSetting ps : mSettings.mPackages.values()) {
7162                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7163                        continue;
7164                    }
7165                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7166                    if (pi != null) {
7167                        list.add(pi);
7168                    }
7169                }
7170            } else {
7171                list = new ArrayList<>(mPackages.size());
7172                for (PackageParser.Package p : mPackages.values()) {
7173                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7174                            Binder.getCallingUid(), userId)) {
7175                        continue;
7176                    }
7177                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7178                            p.mExtras, flags, userId);
7179                    if (pi != null) {
7180                        list.add(pi);
7181                    }
7182                }
7183            }
7184
7185            return new ParceledListSlice<>(list);
7186        }
7187    }
7188
7189    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7190            String[] permissions, boolean[] tmp, int flags, int userId) {
7191        int numMatch = 0;
7192        final PermissionsState permissionsState = ps.getPermissionsState();
7193        for (int i=0; i<permissions.length; i++) {
7194            final String permission = permissions[i];
7195            if (permissionsState.hasPermission(permission, userId)) {
7196                tmp[i] = true;
7197                numMatch++;
7198            } else {
7199                tmp[i] = false;
7200            }
7201        }
7202        if (numMatch == 0) {
7203            return;
7204        }
7205        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7206
7207        // The above might return null in cases of uninstalled apps or install-state
7208        // skew across users/profiles.
7209        if (pi != null) {
7210            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7211                if (numMatch == permissions.length) {
7212                    pi.requestedPermissions = permissions;
7213                } else {
7214                    pi.requestedPermissions = new String[numMatch];
7215                    numMatch = 0;
7216                    for (int i=0; i<permissions.length; i++) {
7217                        if (tmp[i]) {
7218                            pi.requestedPermissions[numMatch] = permissions[i];
7219                            numMatch++;
7220                        }
7221                    }
7222                }
7223            }
7224            list.add(pi);
7225        }
7226    }
7227
7228    @Override
7229    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7230            String[] permissions, int flags, int userId) {
7231        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7232        flags = updateFlagsForPackage(flags, userId, permissions);
7233        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7234                true /* requireFullPermission */, false /* checkShell */,
7235                "get packages holding permissions");
7236        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7237
7238        // writer
7239        synchronized (mPackages) {
7240            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7241            boolean[] tmpBools = new boolean[permissions.length];
7242            if (listUninstalled) {
7243                for (PackageSetting ps : mSettings.mPackages.values()) {
7244                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7245                            userId);
7246                }
7247            } else {
7248                for (PackageParser.Package pkg : mPackages.values()) {
7249                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7250                    if (ps != null) {
7251                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7252                                userId);
7253                    }
7254                }
7255            }
7256
7257            return new ParceledListSlice<PackageInfo>(list);
7258        }
7259    }
7260
7261    @Override
7262    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7263        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7264        flags = updateFlagsForApplication(flags, userId, null);
7265        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7266
7267        // writer
7268        synchronized (mPackages) {
7269            ArrayList<ApplicationInfo> list;
7270            if (listUninstalled) {
7271                list = new ArrayList<>(mSettings.mPackages.size());
7272                for (PackageSetting ps : mSettings.mPackages.values()) {
7273                    ApplicationInfo ai;
7274                    int effectiveFlags = flags;
7275                    if (ps.isSystem()) {
7276                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7277                    }
7278                    if (ps.pkg != null) {
7279                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7280                            continue;
7281                        }
7282                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7283                                ps.readUserState(userId), userId);
7284                        if (ai != null) {
7285                            rebaseEnabledOverlays(ai, userId);
7286                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7287                        }
7288                    } else {
7289                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7290                        // and already converts to externally visible package name
7291                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7292                                Binder.getCallingUid(), effectiveFlags, userId);
7293                    }
7294                    if (ai != null) {
7295                        list.add(ai);
7296                    }
7297                }
7298            } else {
7299                list = new ArrayList<>(mPackages.size());
7300                for (PackageParser.Package p : mPackages.values()) {
7301                    if (p.mExtras != null) {
7302                        PackageSetting ps = (PackageSetting) p.mExtras;
7303                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7304                            continue;
7305                        }
7306                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7307                                ps.readUserState(userId), userId);
7308                        if (ai != null) {
7309                            rebaseEnabledOverlays(ai, userId);
7310                            ai.packageName = resolveExternalPackageNameLPr(p);
7311                            list.add(ai);
7312                        }
7313                    }
7314                }
7315            }
7316
7317            return new ParceledListSlice<>(list);
7318        }
7319    }
7320
7321    @Override
7322    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7323        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7324            return null;
7325        }
7326
7327        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7328                "getEphemeralApplications");
7329        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7330                true /* requireFullPermission */, false /* checkShell */,
7331                "getEphemeralApplications");
7332        synchronized (mPackages) {
7333            List<InstantAppInfo> instantApps = mInstantAppRegistry
7334                    .getInstantAppsLPr(userId);
7335            if (instantApps != null) {
7336                return new ParceledListSlice<>(instantApps);
7337            }
7338        }
7339        return null;
7340    }
7341
7342    @Override
7343    public boolean isInstantApp(String packageName, int userId) {
7344        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7345                true /* requireFullPermission */, false /* checkShell */,
7346                "isInstantApp");
7347        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7348            return false;
7349        }
7350
7351        synchronized (mPackages) {
7352            final PackageSetting ps = mSettings.mPackages.get(packageName);
7353            final boolean returnAllowed =
7354                    ps != null
7355                    && (isCallerSameApp(packageName)
7356                            || mContext.checkCallingOrSelfPermission(
7357                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7358                                            == PERMISSION_GRANTED
7359                            || mInstantAppRegistry.isInstantAccessGranted(
7360                                    userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId));
7361            if (returnAllowed) {
7362                return ps.getInstantApp(userId);
7363            }
7364        }
7365        return false;
7366    }
7367
7368    @Override
7369    public byte[] getInstantAppCookie(String packageName, int userId) {
7370        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7371            return null;
7372        }
7373
7374        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7375                true /* requireFullPermission */, false /* checkShell */,
7376                "getInstantAppCookie");
7377        if (!isCallerSameApp(packageName)) {
7378            return null;
7379        }
7380        synchronized (mPackages) {
7381            return mInstantAppRegistry.getInstantAppCookieLPw(
7382                    packageName, userId);
7383        }
7384    }
7385
7386    @Override
7387    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7388        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7389            return true;
7390        }
7391
7392        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7393                true /* requireFullPermission */, true /* checkShell */,
7394                "setInstantAppCookie");
7395        if (!isCallerSameApp(packageName)) {
7396            return false;
7397        }
7398        synchronized (mPackages) {
7399            return mInstantAppRegistry.setInstantAppCookieLPw(
7400                    packageName, cookie, userId);
7401        }
7402    }
7403
7404    @Override
7405    public Bitmap getInstantAppIcon(String packageName, int userId) {
7406        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7407            return null;
7408        }
7409
7410        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7411                "getInstantAppIcon");
7412
7413        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7414                true /* requireFullPermission */, false /* checkShell */,
7415                "getInstantAppIcon");
7416
7417        synchronized (mPackages) {
7418            return mInstantAppRegistry.getInstantAppIconLPw(
7419                    packageName, userId);
7420        }
7421    }
7422
7423    private boolean isCallerSameApp(String packageName) {
7424        PackageParser.Package pkg = mPackages.get(packageName);
7425        return pkg != null
7426                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7427    }
7428
7429    @Override
7430    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7431        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7432    }
7433
7434    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7435        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7436
7437        // reader
7438        synchronized (mPackages) {
7439            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7440            final int userId = UserHandle.getCallingUserId();
7441            while (i.hasNext()) {
7442                final PackageParser.Package p = i.next();
7443                if (p.applicationInfo == null) continue;
7444
7445                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7446                        && !p.applicationInfo.isDirectBootAware();
7447                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7448                        && p.applicationInfo.isDirectBootAware();
7449
7450                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7451                        && (!mSafeMode || isSystemApp(p))
7452                        && (matchesUnaware || matchesAware)) {
7453                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7454                    if (ps != null) {
7455                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7456                                ps.readUserState(userId), userId);
7457                        if (ai != null) {
7458                            rebaseEnabledOverlays(ai, userId);
7459                            finalList.add(ai);
7460                        }
7461                    }
7462                }
7463            }
7464        }
7465
7466        return finalList;
7467    }
7468
7469    @Override
7470    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7471        if (!sUserManager.exists(userId)) return null;
7472        flags = updateFlagsForComponent(flags, userId, name);
7473        // reader
7474        synchronized (mPackages) {
7475            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7476            PackageSetting ps = provider != null
7477                    ? mSettings.mPackages.get(provider.owner.packageName)
7478                    : null;
7479            return ps != null
7480                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7481                    ? PackageParser.generateProviderInfo(provider, flags,
7482                            ps.readUserState(userId), userId)
7483                    : null;
7484        }
7485    }
7486
7487    /**
7488     * @deprecated
7489     */
7490    @Deprecated
7491    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7492        // reader
7493        synchronized (mPackages) {
7494            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7495                    .entrySet().iterator();
7496            final int userId = UserHandle.getCallingUserId();
7497            while (i.hasNext()) {
7498                Map.Entry<String, PackageParser.Provider> entry = i.next();
7499                PackageParser.Provider p = entry.getValue();
7500                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7501
7502                if (ps != null && p.syncable
7503                        && (!mSafeMode || (p.info.applicationInfo.flags
7504                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7505                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7506                            ps.readUserState(userId), userId);
7507                    if (info != null) {
7508                        outNames.add(entry.getKey());
7509                        outInfo.add(info);
7510                    }
7511                }
7512            }
7513        }
7514    }
7515
7516    @Override
7517    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7518            int uid, int flags, String metaDataKey) {
7519        final int userId = processName != null ? UserHandle.getUserId(uid)
7520                : UserHandle.getCallingUserId();
7521        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7522        flags = updateFlagsForComponent(flags, userId, processName);
7523
7524        ArrayList<ProviderInfo> finalList = null;
7525        // reader
7526        synchronized (mPackages) {
7527            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7528            while (i.hasNext()) {
7529                final PackageParser.Provider p = i.next();
7530                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7531                if (ps != null && p.info.authority != null
7532                        && (processName == null
7533                                || (p.info.processName.equals(processName)
7534                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7535                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7536
7537                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7538                    // parameter.
7539                    if (metaDataKey != null
7540                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7541                        continue;
7542                    }
7543
7544                    if (finalList == null) {
7545                        finalList = new ArrayList<ProviderInfo>(3);
7546                    }
7547                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7548                            ps.readUserState(userId), userId);
7549                    if (info != null) {
7550                        finalList.add(info);
7551                    }
7552                }
7553            }
7554        }
7555
7556        if (finalList != null) {
7557            Collections.sort(finalList, mProviderInitOrderSorter);
7558            return new ParceledListSlice<ProviderInfo>(finalList);
7559        }
7560
7561        return ParceledListSlice.emptyList();
7562    }
7563
7564    @Override
7565    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7566        // reader
7567        synchronized (mPackages) {
7568            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7569            return PackageParser.generateInstrumentationInfo(i, flags);
7570        }
7571    }
7572
7573    @Override
7574    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7575            String targetPackage, int flags) {
7576        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7577    }
7578
7579    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7580            int flags) {
7581        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7582
7583        // reader
7584        synchronized (mPackages) {
7585            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7586            while (i.hasNext()) {
7587                final PackageParser.Instrumentation p = i.next();
7588                if (targetPackage == null
7589                        || targetPackage.equals(p.info.targetPackage)) {
7590                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7591                            flags);
7592                    if (ii != null) {
7593                        finalList.add(ii);
7594                    }
7595                }
7596            }
7597        }
7598
7599        return finalList;
7600    }
7601
7602    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7603        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7604        try {
7605            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7606        } finally {
7607            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7608        }
7609    }
7610
7611    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7612        final File[] files = dir.listFiles();
7613        if (ArrayUtils.isEmpty(files)) {
7614            Log.d(TAG, "No files in app dir " + dir);
7615            return;
7616        }
7617
7618        if (DEBUG_PACKAGE_SCANNING) {
7619            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7620                    + " flags=0x" + Integer.toHexString(parseFlags));
7621        }
7622        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7623                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7624
7625        // Submit files for parsing in parallel
7626        int fileCount = 0;
7627        for (File file : files) {
7628            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7629                    && !PackageInstallerService.isStageName(file.getName());
7630            if (!isPackage) {
7631                // Ignore entries which are not packages
7632                continue;
7633            }
7634            parallelPackageParser.submit(file, parseFlags);
7635            fileCount++;
7636        }
7637
7638        // Process results one by one
7639        for (; fileCount > 0; fileCount--) {
7640            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7641            Throwable throwable = parseResult.throwable;
7642            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7643
7644            if (throwable == null) {
7645                // Static shared libraries have synthetic package names
7646                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7647                    renameStaticSharedLibraryPackage(parseResult.pkg);
7648                }
7649                try {
7650                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7651                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7652                                currentTime, null);
7653                    }
7654                } catch (PackageManagerException e) {
7655                    errorCode = e.error;
7656                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7657                }
7658            } else if (throwable instanceof PackageParser.PackageParserException) {
7659                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7660                        throwable;
7661                errorCode = e.error;
7662                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7663            } else {
7664                throw new IllegalStateException("Unexpected exception occurred while parsing "
7665                        + parseResult.scanFile, throwable);
7666            }
7667
7668            // Delete invalid userdata apps
7669            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7670                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7671                logCriticalInfo(Log.WARN,
7672                        "Deleting invalid package at " + parseResult.scanFile);
7673                removeCodePathLI(parseResult.scanFile);
7674            }
7675        }
7676        parallelPackageParser.close();
7677    }
7678
7679    private static File getSettingsProblemFile() {
7680        File dataDir = Environment.getDataDirectory();
7681        File systemDir = new File(dataDir, "system");
7682        File fname = new File(systemDir, "uiderrors.txt");
7683        return fname;
7684    }
7685
7686    static void reportSettingsProblem(int priority, String msg) {
7687        logCriticalInfo(priority, msg);
7688    }
7689
7690    public static void logCriticalInfo(int priority, String msg) {
7691        Slog.println(priority, TAG, msg);
7692        EventLogTags.writePmCriticalInfo(msg);
7693        try {
7694            File fname = getSettingsProblemFile();
7695            FileOutputStream out = new FileOutputStream(fname, true);
7696            PrintWriter pw = new FastPrintWriter(out);
7697            SimpleDateFormat formatter = new SimpleDateFormat();
7698            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7699            pw.println(dateString + ": " + msg);
7700            pw.close();
7701            FileUtils.setPermissions(
7702                    fname.toString(),
7703                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7704                    -1, -1);
7705        } catch (java.io.IOException e) {
7706        }
7707    }
7708
7709    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7710        if (srcFile.isDirectory()) {
7711            final File baseFile = new File(pkg.baseCodePath);
7712            long maxModifiedTime = baseFile.lastModified();
7713            if (pkg.splitCodePaths != null) {
7714                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7715                    final File splitFile = new File(pkg.splitCodePaths[i]);
7716                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7717                }
7718            }
7719            return maxModifiedTime;
7720        }
7721        return srcFile.lastModified();
7722    }
7723
7724    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7725            final int policyFlags) throws PackageManagerException {
7726        // When upgrading from pre-N MR1, verify the package time stamp using the package
7727        // directory and not the APK file.
7728        final long lastModifiedTime = mIsPreNMR1Upgrade
7729                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7730        if (ps != null
7731                && ps.codePath.equals(srcFile)
7732                && ps.timeStamp == lastModifiedTime
7733                && !isCompatSignatureUpdateNeeded(pkg)
7734                && !isRecoverSignatureUpdateNeeded(pkg)) {
7735            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7736            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7737            ArraySet<PublicKey> signingKs;
7738            synchronized (mPackages) {
7739                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7740            }
7741            if (ps.signatures.mSignatures != null
7742                    && ps.signatures.mSignatures.length != 0
7743                    && signingKs != null) {
7744                // Optimization: reuse the existing cached certificates
7745                // if the package appears to be unchanged.
7746                pkg.mSignatures = ps.signatures.mSignatures;
7747                pkg.mSigningKeys = signingKs;
7748                return;
7749            }
7750
7751            Slog.w(TAG, "PackageSetting for " + ps.name
7752                    + " is missing signatures.  Collecting certs again to recover them.");
7753        } else {
7754            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7755        }
7756
7757        try {
7758            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7759            PackageParser.collectCertificates(pkg, policyFlags);
7760        } catch (PackageParserException e) {
7761            throw PackageManagerException.from(e);
7762        } finally {
7763            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7764        }
7765    }
7766
7767    /**
7768     *  Traces a package scan.
7769     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7770     */
7771    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7772            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7773        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7774        try {
7775            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7776        } finally {
7777            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7778        }
7779    }
7780
7781    /**
7782     *  Scans a package and returns the newly parsed package.
7783     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7784     */
7785    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7786            long currentTime, UserHandle user) throws PackageManagerException {
7787        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7788        PackageParser pp = new PackageParser();
7789        pp.setSeparateProcesses(mSeparateProcesses);
7790        pp.setOnlyCoreApps(mOnlyCore);
7791        pp.setDisplayMetrics(mMetrics);
7792        pp.setCallback(mPackageParserCallback);
7793
7794        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7795            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7796        }
7797
7798        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7799        final PackageParser.Package pkg;
7800        try {
7801            pkg = pp.parsePackage(scanFile, parseFlags);
7802        } catch (PackageParserException e) {
7803            throw PackageManagerException.from(e);
7804        } finally {
7805            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7806        }
7807
7808        // Static shared libraries have synthetic package names
7809        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7810            renameStaticSharedLibraryPackage(pkg);
7811        }
7812
7813        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7814    }
7815
7816    /**
7817     *  Scans a package and returns the newly parsed package.
7818     *  @throws PackageManagerException on a parse error.
7819     */
7820    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7821            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7822            throws PackageManagerException {
7823        // If the package has children and this is the first dive in the function
7824        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7825        // packages (parent and children) would be successfully scanned before the
7826        // actual scan since scanning mutates internal state and we want to atomically
7827        // install the package and its children.
7828        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7829            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7830                scanFlags |= SCAN_CHECK_ONLY;
7831            }
7832        } else {
7833            scanFlags &= ~SCAN_CHECK_ONLY;
7834        }
7835
7836        // Scan the parent
7837        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7838                scanFlags, currentTime, user);
7839
7840        // Scan the children
7841        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7842        for (int i = 0; i < childCount; i++) {
7843            PackageParser.Package childPackage = pkg.childPackages.get(i);
7844            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7845                    currentTime, user);
7846        }
7847
7848
7849        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7850            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7851        }
7852
7853        return scannedPkg;
7854    }
7855
7856    /**
7857     *  Scans a package and returns the newly parsed package.
7858     *  @throws PackageManagerException on a parse error.
7859     */
7860    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7861            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7862            throws PackageManagerException {
7863        PackageSetting ps = null;
7864        PackageSetting updatedPkg;
7865        // reader
7866        synchronized (mPackages) {
7867            // Look to see if we already know about this package.
7868            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7869            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7870                // This package has been renamed to its original name.  Let's
7871                // use that.
7872                ps = mSettings.getPackageLPr(oldName);
7873            }
7874            // If there was no original package, see one for the real package name.
7875            if (ps == null) {
7876                ps = mSettings.getPackageLPr(pkg.packageName);
7877            }
7878            // Check to see if this package could be hiding/updating a system
7879            // package.  Must look for it either under the original or real
7880            // package name depending on our state.
7881            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7882            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7883
7884            // If this is a package we don't know about on the system partition, we
7885            // may need to remove disabled child packages on the system partition
7886            // or may need to not add child packages if the parent apk is updated
7887            // on the data partition and no longer defines this child package.
7888            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7889                // If this is a parent package for an updated system app and this system
7890                // app got an OTA update which no longer defines some of the child packages
7891                // we have to prune them from the disabled system packages.
7892                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7893                if (disabledPs != null) {
7894                    final int scannedChildCount = (pkg.childPackages != null)
7895                            ? pkg.childPackages.size() : 0;
7896                    final int disabledChildCount = disabledPs.childPackageNames != null
7897                            ? disabledPs.childPackageNames.size() : 0;
7898                    for (int i = 0; i < disabledChildCount; i++) {
7899                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7900                        boolean disabledPackageAvailable = false;
7901                        for (int j = 0; j < scannedChildCount; j++) {
7902                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7903                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7904                                disabledPackageAvailable = true;
7905                                break;
7906                            }
7907                         }
7908                         if (!disabledPackageAvailable) {
7909                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7910                         }
7911                    }
7912                }
7913            }
7914        }
7915
7916        boolean updatedPkgBetter = false;
7917        // First check if this is a system package that may involve an update
7918        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7919            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7920            // it needs to drop FLAG_PRIVILEGED.
7921            if (locationIsPrivileged(scanFile)) {
7922                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7923            } else {
7924                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7925            }
7926
7927            if (ps != null && !ps.codePath.equals(scanFile)) {
7928                // The path has changed from what was last scanned...  check the
7929                // version of the new path against what we have stored to determine
7930                // what to do.
7931                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7932                if (pkg.mVersionCode <= ps.versionCode) {
7933                    // The system package has been updated and the code path does not match
7934                    // Ignore entry. Skip it.
7935                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7936                            + " ignored: updated version " + ps.versionCode
7937                            + " better than this " + pkg.mVersionCode);
7938                    if (!updatedPkg.codePath.equals(scanFile)) {
7939                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7940                                + ps.name + " changing from " + updatedPkg.codePathString
7941                                + " to " + scanFile);
7942                        updatedPkg.codePath = scanFile;
7943                        updatedPkg.codePathString = scanFile.toString();
7944                        updatedPkg.resourcePath = scanFile;
7945                        updatedPkg.resourcePathString = scanFile.toString();
7946                    }
7947                    updatedPkg.pkg = pkg;
7948                    updatedPkg.versionCode = pkg.mVersionCode;
7949
7950                    // Update the disabled system child packages to point to the package too.
7951                    final int childCount = updatedPkg.childPackageNames != null
7952                            ? updatedPkg.childPackageNames.size() : 0;
7953                    for (int i = 0; i < childCount; i++) {
7954                        String childPackageName = updatedPkg.childPackageNames.get(i);
7955                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7956                                childPackageName);
7957                        if (updatedChildPkg != null) {
7958                            updatedChildPkg.pkg = pkg;
7959                            updatedChildPkg.versionCode = pkg.mVersionCode;
7960                        }
7961                    }
7962
7963                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7964                            + scanFile + " ignored: updated version " + ps.versionCode
7965                            + " better than this " + pkg.mVersionCode);
7966                } else {
7967                    // The current app on the system partition is better than
7968                    // what we have updated to on the data partition; switch
7969                    // back to the system partition version.
7970                    // At this point, its safely assumed that package installation for
7971                    // apps in system partition will go through. If not there won't be a working
7972                    // version of the app
7973                    // writer
7974                    synchronized (mPackages) {
7975                        // Just remove the loaded entries from package lists.
7976                        mPackages.remove(ps.name);
7977                    }
7978
7979                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7980                            + " reverting from " + ps.codePathString
7981                            + ": new version " + pkg.mVersionCode
7982                            + " better than installed " + ps.versionCode);
7983
7984                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7985                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7986                    synchronized (mInstallLock) {
7987                        args.cleanUpResourcesLI();
7988                    }
7989                    synchronized (mPackages) {
7990                        mSettings.enableSystemPackageLPw(ps.name);
7991                    }
7992                    updatedPkgBetter = true;
7993                }
7994            }
7995        }
7996
7997        if (updatedPkg != null) {
7998            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7999            // initially
8000            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8001
8002            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8003            // flag set initially
8004            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8005                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8006            }
8007        }
8008
8009        // Verify certificates against what was last scanned
8010        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8011
8012        /*
8013         * A new system app appeared, but we already had a non-system one of the
8014         * same name installed earlier.
8015         */
8016        boolean shouldHideSystemApp = false;
8017        if (updatedPkg == null && ps != null
8018                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8019            /*
8020             * Check to make sure the signatures match first. If they don't,
8021             * wipe the installed application and its data.
8022             */
8023            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8024                    != PackageManager.SIGNATURE_MATCH) {
8025                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8026                        + " signatures don't match existing userdata copy; removing");
8027                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8028                        "scanPackageInternalLI")) {
8029                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8030                }
8031                ps = null;
8032            } else {
8033                /*
8034                 * If the newly-added system app is an older version than the
8035                 * already installed version, hide it. It will be scanned later
8036                 * and re-added like an update.
8037                 */
8038                if (pkg.mVersionCode <= ps.versionCode) {
8039                    shouldHideSystemApp = true;
8040                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8041                            + " but new version " + pkg.mVersionCode + " better than installed "
8042                            + ps.versionCode + "; hiding system");
8043                } else {
8044                    /*
8045                     * The newly found system app is a newer version that the
8046                     * one previously installed. Simply remove the
8047                     * already-installed application and replace it with our own
8048                     * while keeping the application data.
8049                     */
8050                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8051                            + " reverting from " + ps.codePathString + ": new version "
8052                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8053                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8054                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8055                    synchronized (mInstallLock) {
8056                        args.cleanUpResourcesLI();
8057                    }
8058                }
8059            }
8060        }
8061
8062        // The apk is forward locked (not public) if its code and resources
8063        // are kept in different files. (except for app in either system or
8064        // vendor path).
8065        // TODO grab this value from PackageSettings
8066        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8067            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8068                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8069            }
8070        }
8071
8072        // TODO: extend to support forward-locked splits
8073        String resourcePath = null;
8074        String baseResourcePath = null;
8075        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8076            if (ps != null && ps.resourcePathString != null) {
8077                resourcePath = ps.resourcePathString;
8078                baseResourcePath = ps.resourcePathString;
8079            } else {
8080                // Should not happen at all. Just log an error.
8081                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8082            }
8083        } else {
8084            resourcePath = pkg.codePath;
8085            baseResourcePath = pkg.baseCodePath;
8086        }
8087
8088        // Set application objects path explicitly.
8089        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8090        pkg.setApplicationInfoCodePath(pkg.codePath);
8091        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8092        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8093        pkg.setApplicationInfoResourcePath(resourcePath);
8094        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8095        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8096
8097        final int userId = ((user == null) ? 0 : user.getIdentifier());
8098        if (ps != null && ps.getInstantApp(userId)) {
8099            scanFlags |= SCAN_AS_INSTANT_APP;
8100        }
8101
8102        // Note that we invoke the following method only if we are about to unpack an application
8103        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8104                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8105
8106        /*
8107         * If the system app should be overridden by a previously installed
8108         * data, hide the system app now and let the /data/app scan pick it up
8109         * again.
8110         */
8111        if (shouldHideSystemApp) {
8112            synchronized (mPackages) {
8113                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8114            }
8115        }
8116
8117        return scannedPkg;
8118    }
8119
8120    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8121        // Derive the new package synthetic package name
8122        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8123                + pkg.staticSharedLibVersion);
8124    }
8125
8126    private static String fixProcessName(String defProcessName,
8127            String processName) {
8128        if (processName == null) {
8129            return defProcessName;
8130        }
8131        return processName;
8132    }
8133
8134    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8135            throws PackageManagerException {
8136        if (pkgSetting.signatures.mSignatures != null) {
8137            // Already existing package. Make sure signatures match
8138            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8139                    == PackageManager.SIGNATURE_MATCH;
8140            if (!match) {
8141                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8142                        == PackageManager.SIGNATURE_MATCH;
8143            }
8144            if (!match) {
8145                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8146                        == PackageManager.SIGNATURE_MATCH;
8147            }
8148            if (!match) {
8149                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8150                        + pkg.packageName + " signatures do not match the "
8151                        + "previously installed version; ignoring!");
8152            }
8153        }
8154
8155        // Check for shared user signatures
8156        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8157            // Already existing package. Make sure signatures match
8158            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8159                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8160            if (!match) {
8161                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8162                        == PackageManager.SIGNATURE_MATCH;
8163            }
8164            if (!match) {
8165                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8166                        == PackageManager.SIGNATURE_MATCH;
8167            }
8168            if (!match) {
8169                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8170                        "Package " + pkg.packageName
8171                        + " has no signatures that match those in shared user "
8172                        + pkgSetting.sharedUser.name + "; ignoring!");
8173            }
8174        }
8175    }
8176
8177    /**
8178     * Enforces that only the system UID or root's UID can call a method exposed
8179     * via Binder.
8180     *
8181     * @param message used as message if SecurityException is thrown
8182     * @throws SecurityException if the caller is not system or root
8183     */
8184    private static final void enforceSystemOrRoot(String message) {
8185        final int uid = Binder.getCallingUid();
8186        if (uid != Process.SYSTEM_UID && uid != 0) {
8187            throw new SecurityException(message);
8188        }
8189    }
8190
8191    @Override
8192    public void performFstrimIfNeeded() {
8193        enforceSystemOrRoot("Only the system can request fstrim");
8194
8195        // Before everything else, see whether we need to fstrim.
8196        try {
8197            IStorageManager sm = PackageHelper.getStorageManager();
8198            if (sm != null) {
8199                boolean doTrim = false;
8200                final long interval = android.provider.Settings.Global.getLong(
8201                        mContext.getContentResolver(),
8202                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8203                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8204                if (interval > 0) {
8205                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8206                    if (timeSinceLast > interval) {
8207                        doTrim = true;
8208                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8209                                + "; running immediately");
8210                    }
8211                }
8212                if (doTrim) {
8213                    final boolean dexOptDialogShown;
8214                    synchronized (mPackages) {
8215                        dexOptDialogShown = mDexOptDialogShown;
8216                    }
8217                    if (!isFirstBoot() && dexOptDialogShown) {
8218                        try {
8219                            ActivityManager.getService().showBootMessage(
8220                                    mContext.getResources().getString(
8221                                            R.string.android_upgrading_fstrim), true);
8222                        } catch (RemoteException e) {
8223                        }
8224                    }
8225                    sm.runMaintenance();
8226                }
8227            } else {
8228                Slog.e(TAG, "storageManager service unavailable!");
8229            }
8230        } catch (RemoteException e) {
8231            // Can't happen; StorageManagerService is local
8232        }
8233    }
8234
8235    @Override
8236    public void updatePackagesIfNeeded() {
8237        enforceSystemOrRoot("Only the system can request package update");
8238
8239        // We need to re-extract after an OTA.
8240        boolean causeUpgrade = isUpgrade();
8241
8242        // First boot or factory reset.
8243        // Note: we also handle devices that are upgrading to N right now as if it is their
8244        //       first boot, as they do not have profile data.
8245        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8246
8247        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8248        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8249
8250        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8251            return;
8252        }
8253
8254        List<PackageParser.Package> pkgs;
8255        synchronized (mPackages) {
8256            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8257        }
8258
8259        final long startTime = System.nanoTime();
8260        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8261                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8262
8263        final int elapsedTimeSeconds =
8264                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8265
8266        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8267        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8268        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8269        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8270        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8271    }
8272
8273    /**
8274     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8275     * containing statistics about the invocation. The array consists of three elements,
8276     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8277     * and {@code numberOfPackagesFailed}.
8278     */
8279    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8280            String compilerFilter) {
8281
8282        int numberOfPackagesVisited = 0;
8283        int numberOfPackagesOptimized = 0;
8284        int numberOfPackagesSkipped = 0;
8285        int numberOfPackagesFailed = 0;
8286        final int numberOfPackagesToDexopt = pkgs.size();
8287
8288        for (PackageParser.Package pkg : pkgs) {
8289            numberOfPackagesVisited++;
8290
8291            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8292                if (DEBUG_DEXOPT) {
8293                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8294                }
8295                numberOfPackagesSkipped++;
8296                continue;
8297            }
8298
8299            if (DEBUG_DEXOPT) {
8300                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8301                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8302            }
8303
8304            if (showDialog) {
8305                try {
8306                    ActivityManager.getService().showBootMessage(
8307                            mContext.getResources().getString(R.string.android_upgrading_apk,
8308                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8309                } catch (RemoteException e) {
8310                }
8311                synchronized (mPackages) {
8312                    mDexOptDialogShown = true;
8313                }
8314            }
8315
8316            // If the OTA updates a system app which was previously preopted to a non-preopted state
8317            // the app might end up being verified at runtime. That's because by default the apps
8318            // are verify-profile but for preopted apps there's no profile.
8319            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8320            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8321            // filter (by default interpret-only).
8322            // Note that at this stage unused apps are already filtered.
8323            if (isSystemApp(pkg) &&
8324                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8325                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8326                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8327            }
8328
8329            // checkProfiles is false to avoid merging profiles during boot which
8330            // might interfere with background compilation (b/28612421).
8331            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8332            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8333            // trade-off worth doing to save boot time work.
8334            int dexOptStatus = performDexOptTraced(pkg.packageName,
8335                    false /* checkProfiles */,
8336                    compilerFilter,
8337                    false /* force */);
8338            switch (dexOptStatus) {
8339                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8340                    numberOfPackagesOptimized++;
8341                    break;
8342                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8343                    numberOfPackagesSkipped++;
8344                    break;
8345                case PackageDexOptimizer.DEX_OPT_FAILED:
8346                    numberOfPackagesFailed++;
8347                    break;
8348                default:
8349                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8350                    break;
8351            }
8352        }
8353
8354        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8355                numberOfPackagesFailed };
8356    }
8357
8358    @Override
8359    public void notifyPackageUse(String packageName, int reason) {
8360        synchronized (mPackages) {
8361            PackageParser.Package p = mPackages.get(packageName);
8362            if (p == null) {
8363                return;
8364            }
8365            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8366        }
8367    }
8368
8369    @Override
8370    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8371        int userId = UserHandle.getCallingUserId();
8372        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8373        if (ai == null) {
8374            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8375                + loadingPackageName + ", user=" + userId);
8376            return;
8377        }
8378        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8379    }
8380
8381    // TODO: this is not used nor needed. Delete it.
8382    @Override
8383    public boolean performDexOptIfNeeded(String packageName) {
8384        int dexOptStatus = performDexOptTraced(packageName,
8385                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8386        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8387    }
8388
8389    @Override
8390    public boolean performDexOpt(String packageName,
8391            boolean checkProfiles, int compileReason, boolean force) {
8392        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8393                getCompilerFilterForReason(compileReason), force);
8394        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8395    }
8396
8397    @Override
8398    public boolean performDexOptMode(String packageName,
8399            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8400        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8401                targetCompilerFilter, force);
8402        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8403    }
8404
8405    private int performDexOptTraced(String packageName,
8406                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8407        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8408        try {
8409            return performDexOptInternal(packageName, checkProfiles,
8410                    targetCompilerFilter, force);
8411        } finally {
8412            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8413        }
8414    }
8415
8416    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8417    // if the package can now be considered up to date for the given filter.
8418    private int performDexOptInternal(String packageName,
8419                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8420        PackageParser.Package p;
8421        synchronized (mPackages) {
8422            p = mPackages.get(packageName);
8423            if (p == null) {
8424                // Package could not be found. Report failure.
8425                return PackageDexOptimizer.DEX_OPT_FAILED;
8426            }
8427            mPackageUsage.maybeWriteAsync(mPackages);
8428            mCompilerStats.maybeWriteAsync();
8429        }
8430        long callingId = Binder.clearCallingIdentity();
8431        try {
8432            synchronized (mInstallLock) {
8433                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8434                        targetCompilerFilter, force);
8435            }
8436        } finally {
8437            Binder.restoreCallingIdentity(callingId);
8438        }
8439    }
8440
8441    public ArraySet<String> getOptimizablePackages() {
8442        ArraySet<String> pkgs = new ArraySet<String>();
8443        synchronized (mPackages) {
8444            for (PackageParser.Package p : mPackages.values()) {
8445                if (PackageDexOptimizer.canOptimizePackage(p)) {
8446                    pkgs.add(p.packageName);
8447                }
8448            }
8449        }
8450        return pkgs;
8451    }
8452
8453    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8454            boolean checkProfiles, String targetCompilerFilter,
8455            boolean force) {
8456        // Select the dex optimizer based on the force parameter.
8457        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8458        //       allocate an object here.
8459        PackageDexOptimizer pdo = force
8460                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8461                : mPackageDexOptimizer;
8462
8463        // Optimize all dependencies first. Note: we ignore the return value and march on
8464        // on errors.
8465        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8466        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8467        if (!deps.isEmpty()) {
8468            for (PackageParser.Package depPackage : deps) {
8469                // TODO: Analyze and investigate if we (should) profile libraries.
8470                // Currently this will do a full compilation of the library by default.
8471                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8472                        false /* checkProfiles */,
8473                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8474                        getOrCreateCompilerPackageStats(depPackage),
8475                        mDexManager.isUsedByOtherApps(p.packageName));
8476            }
8477        }
8478        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8479                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8480                mDexManager.isUsedByOtherApps(p.packageName));
8481    }
8482
8483    // Performs dexopt on the used secondary dex files belonging to the given package.
8484    // Returns true if all dex files were process successfully (which could mean either dexopt or
8485    // skip). Returns false if any of the files caused errors.
8486    @Override
8487    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8488            boolean force) {
8489        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8490    }
8491
8492    public boolean performDexOptSecondary(String packageName, int compileReason,
8493            boolean force) {
8494        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8495    }
8496
8497    /**
8498     * Reconcile the information we have about the secondary dex files belonging to
8499     * {@code packagName} and the actual dex files. For all dex files that were
8500     * deleted, update the internal records and delete the generated oat files.
8501     */
8502    @Override
8503    public void reconcileSecondaryDexFiles(String packageName) {
8504        mDexManager.reconcileSecondaryDexFiles(packageName);
8505    }
8506
8507    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8508    // a reference there.
8509    /*package*/ DexManager getDexManager() {
8510        return mDexManager;
8511    }
8512
8513    /**
8514     * Execute the background dexopt job immediately.
8515     */
8516    @Override
8517    public boolean runBackgroundDexoptJob() {
8518        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8519    }
8520
8521    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8522        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8523                || p.usesStaticLibraries != null) {
8524            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8525            Set<String> collectedNames = new HashSet<>();
8526            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8527
8528            retValue.remove(p);
8529
8530            return retValue;
8531        } else {
8532            return Collections.emptyList();
8533        }
8534    }
8535
8536    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8537            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8538        if (!collectedNames.contains(p.packageName)) {
8539            collectedNames.add(p.packageName);
8540            collected.add(p);
8541
8542            if (p.usesLibraries != null) {
8543                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8544                        null, collected, collectedNames);
8545            }
8546            if (p.usesOptionalLibraries != null) {
8547                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8548                        null, collected, collectedNames);
8549            }
8550            if (p.usesStaticLibraries != null) {
8551                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8552                        p.usesStaticLibrariesVersions, collected, collectedNames);
8553            }
8554        }
8555    }
8556
8557    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8558            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8559        final int libNameCount = libs.size();
8560        for (int i = 0; i < libNameCount; i++) {
8561            String libName = libs.get(i);
8562            int version = (versions != null && versions.length == libNameCount)
8563                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8564            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8565            if (libPkg != null) {
8566                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8567            }
8568        }
8569    }
8570
8571    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8572        synchronized (mPackages) {
8573            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8574            if (libEntry != null) {
8575                return mPackages.get(libEntry.apk);
8576            }
8577            return null;
8578        }
8579    }
8580
8581    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8582        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8583        if (versionedLib == null) {
8584            return null;
8585        }
8586        return versionedLib.get(version);
8587    }
8588
8589    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8590        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8591                pkg.staticSharedLibName);
8592        if (versionedLib == null) {
8593            return null;
8594        }
8595        int previousLibVersion = -1;
8596        final int versionCount = versionedLib.size();
8597        for (int i = 0; i < versionCount; i++) {
8598            final int libVersion = versionedLib.keyAt(i);
8599            if (libVersion < pkg.staticSharedLibVersion) {
8600                previousLibVersion = Math.max(previousLibVersion, libVersion);
8601            }
8602        }
8603        if (previousLibVersion >= 0) {
8604            return versionedLib.get(previousLibVersion);
8605        }
8606        return null;
8607    }
8608
8609    public void shutdown() {
8610        mPackageUsage.writeNow(mPackages);
8611        mCompilerStats.writeNow();
8612    }
8613
8614    @Override
8615    public void dumpProfiles(String packageName) {
8616        PackageParser.Package pkg;
8617        synchronized (mPackages) {
8618            pkg = mPackages.get(packageName);
8619            if (pkg == null) {
8620                throw new IllegalArgumentException("Unknown package: " + packageName);
8621            }
8622        }
8623        /* Only the shell, root, or the app user should be able to dump profiles. */
8624        int callingUid = Binder.getCallingUid();
8625        if (callingUid != Process.SHELL_UID &&
8626            callingUid != Process.ROOT_UID &&
8627            callingUid != pkg.applicationInfo.uid) {
8628            throw new SecurityException("dumpProfiles");
8629        }
8630
8631        synchronized (mInstallLock) {
8632            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8633            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8634            try {
8635                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8636                String codePaths = TextUtils.join(";", allCodePaths);
8637                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8638            } catch (InstallerException e) {
8639                Slog.w(TAG, "Failed to dump profiles", e);
8640            }
8641            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8642        }
8643    }
8644
8645    @Override
8646    public void forceDexOpt(String packageName) {
8647        enforceSystemOrRoot("forceDexOpt");
8648
8649        PackageParser.Package pkg;
8650        synchronized (mPackages) {
8651            pkg = mPackages.get(packageName);
8652            if (pkg == null) {
8653                throw new IllegalArgumentException("Unknown package: " + packageName);
8654            }
8655        }
8656
8657        synchronized (mInstallLock) {
8658            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8659
8660            // Whoever is calling forceDexOpt wants a fully compiled package.
8661            // Don't use profiles since that may cause compilation to be skipped.
8662            final int res = performDexOptInternalWithDependenciesLI(pkg,
8663                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8664                    true /* force */);
8665
8666            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8667            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8668                throw new IllegalStateException("Failed to dexopt: " + res);
8669            }
8670        }
8671    }
8672
8673    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8674        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8675            Slog.w(TAG, "Unable to update from " + oldPkg.name
8676                    + " to " + newPkg.packageName
8677                    + ": old package not in system partition");
8678            return false;
8679        } else if (mPackages.get(oldPkg.name) != null) {
8680            Slog.w(TAG, "Unable to update from " + oldPkg.name
8681                    + " to " + newPkg.packageName
8682                    + ": old package still exists");
8683            return false;
8684        }
8685        return true;
8686    }
8687
8688    void removeCodePathLI(File codePath) {
8689        if (codePath.isDirectory()) {
8690            try {
8691                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8692            } catch (InstallerException e) {
8693                Slog.w(TAG, "Failed to remove code path", e);
8694            }
8695        } else {
8696            codePath.delete();
8697        }
8698    }
8699
8700    private int[] resolveUserIds(int userId) {
8701        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8702    }
8703
8704    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8705        if (pkg == null) {
8706            Slog.wtf(TAG, "Package was null!", new Throwable());
8707            return;
8708        }
8709        clearAppDataLeafLIF(pkg, userId, flags);
8710        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8711        for (int i = 0; i < childCount; i++) {
8712            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8713        }
8714    }
8715
8716    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8717        final PackageSetting ps;
8718        synchronized (mPackages) {
8719            ps = mSettings.mPackages.get(pkg.packageName);
8720        }
8721        for (int realUserId : resolveUserIds(userId)) {
8722            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8723            try {
8724                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8725                        ceDataInode);
8726            } catch (InstallerException e) {
8727                Slog.w(TAG, String.valueOf(e));
8728            }
8729        }
8730    }
8731
8732    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8733        if (pkg == null) {
8734            Slog.wtf(TAG, "Package was null!", new Throwable());
8735            return;
8736        }
8737        destroyAppDataLeafLIF(pkg, userId, flags);
8738        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8739        for (int i = 0; i < childCount; i++) {
8740            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8741        }
8742    }
8743
8744    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8745        final PackageSetting ps;
8746        synchronized (mPackages) {
8747            ps = mSettings.mPackages.get(pkg.packageName);
8748        }
8749        for (int realUserId : resolveUserIds(userId)) {
8750            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8751            try {
8752                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8753                        ceDataInode);
8754            } catch (InstallerException e) {
8755                Slog.w(TAG, String.valueOf(e));
8756            }
8757            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8758        }
8759    }
8760
8761    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8762        if (pkg == null) {
8763            Slog.wtf(TAG, "Package was null!", new Throwable());
8764            return;
8765        }
8766        destroyAppProfilesLeafLIF(pkg);
8767        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8768        for (int i = 0; i < childCount; i++) {
8769            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8770        }
8771    }
8772
8773    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8774        try {
8775            mInstaller.destroyAppProfiles(pkg.packageName);
8776        } catch (InstallerException e) {
8777            Slog.w(TAG, String.valueOf(e));
8778        }
8779    }
8780
8781    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8782        if (pkg == null) {
8783            Slog.wtf(TAG, "Package was null!", new Throwable());
8784            return;
8785        }
8786        clearAppProfilesLeafLIF(pkg);
8787        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8788        for (int i = 0; i < childCount; i++) {
8789            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8790        }
8791    }
8792
8793    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8794        try {
8795            mInstaller.clearAppProfiles(pkg.packageName);
8796        } catch (InstallerException e) {
8797            Slog.w(TAG, String.valueOf(e));
8798        }
8799    }
8800
8801    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8802            long lastUpdateTime) {
8803        // Set parent install/update time
8804        PackageSetting ps = (PackageSetting) pkg.mExtras;
8805        if (ps != null) {
8806            ps.firstInstallTime = firstInstallTime;
8807            ps.lastUpdateTime = lastUpdateTime;
8808        }
8809        // Set children install/update time
8810        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8811        for (int i = 0; i < childCount; i++) {
8812            PackageParser.Package childPkg = pkg.childPackages.get(i);
8813            ps = (PackageSetting) childPkg.mExtras;
8814            if (ps != null) {
8815                ps.firstInstallTime = firstInstallTime;
8816                ps.lastUpdateTime = lastUpdateTime;
8817            }
8818        }
8819    }
8820
8821    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8822            PackageParser.Package changingLib) {
8823        if (file.path != null) {
8824            usesLibraryFiles.add(file.path);
8825            return;
8826        }
8827        PackageParser.Package p = mPackages.get(file.apk);
8828        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8829            // If we are doing this while in the middle of updating a library apk,
8830            // then we need to make sure to use that new apk for determining the
8831            // dependencies here.  (We haven't yet finished committing the new apk
8832            // to the package manager state.)
8833            if (p == null || p.packageName.equals(changingLib.packageName)) {
8834                p = changingLib;
8835            }
8836        }
8837        if (p != null) {
8838            usesLibraryFiles.addAll(p.getAllCodePaths());
8839        }
8840    }
8841
8842    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8843            PackageParser.Package changingLib) throws PackageManagerException {
8844        if (pkg == null) {
8845            return;
8846        }
8847        ArraySet<String> usesLibraryFiles = null;
8848        if (pkg.usesLibraries != null) {
8849            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8850                    null, null, pkg.packageName, changingLib, true, null);
8851        }
8852        if (pkg.usesStaticLibraries != null) {
8853            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8854                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8855                    pkg.packageName, changingLib, true, usesLibraryFiles);
8856        }
8857        if (pkg.usesOptionalLibraries != null) {
8858            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8859                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8860        }
8861        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8862            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8863        } else {
8864            pkg.usesLibraryFiles = null;
8865        }
8866    }
8867
8868    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8869            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8870            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8871            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8872            throws PackageManagerException {
8873        final int libCount = requestedLibraries.size();
8874        for (int i = 0; i < libCount; i++) {
8875            final String libName = requestedLibraries.get(i);
8876            final int libVersion = requiredVersions != null ? requiredVersions[i]
8877                    : SharedLibraryInfo.VERSION_UNDEFINED;
8878            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8879            if (libEntry == null) {
8880                if (required) {
8881                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8882                            "Package " + packageName + " requires unavailable shared library "
8883                                    + libName + "; failing!");
8884                } else {
8885                    Slog.w(TAG, "Package " + packageName
8886                            + " desires unavailable shared library "
8887                            + libName + "; ignoring!");
8888                }
8889            } else {
8890                if (requiredVersions != null && requiredCertDigests != null) {
8891                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8892                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8893                            "Package " + packageName + " requires unavailable static shared"
8894                                    + " library " + libName + " version "
8895                                    + libEntry.info.getVersion() + "; failing!");
8896                    }
8897
8898                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8899                    if (libPkg == null) {
8900                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8901                                "Package " + packageName + " requires unavailable static shared"
8902                                        + " library; failing!");
8903                    }
8904
8905                    String expectedCertDigest = requiredCertDigests[i];
8906                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8907                                libPkg.mSignatures[0]);
8908                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8909                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8910                                "Package " + packageName + " requires differently signed" +
8911                                        " static shared library; failing!");
8912                    }
8913                }
8914
8915                if (outUsedLibraries == null) {
8916                    outUsedLibraries = new ArraySet<>();
8917                }
8918                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8919            }
8920        }
8921        return outUsedLibraries;
8922    }
8923
8924    private static boolean hasString(List<String> list, List<String> which) {
8925        if (list == null) {
8926            return false;
8927        }
8928        for (int i=list.size()-1; i>=0; i--) {
8929            for (int j=which.size()-1; j>=0; j--) {
8930                if (which.get(j).equals(list.get(i))) {
8931                    return true;
8932                }
8933            }
8934        }
8935        return false;
8936    }
8937
8938    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8939            PackageParser.Package changingPkg) {
8940        ArrayList<PackageParser.Package> res = null;
8941        for (PackageParser.Package pkg : mPackages.values()) {
8942            if (changingPkg != null
8943                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8944                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8945                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8946                            changingPkg.staticSharedLibName)) {
8947                return null;
8948            }
8949            if (res == null) {
8950                res = new ArrayList<>();
8951            }
8952            res.add(pkg);
8953            try {
8954                updateSharedLibrariesLPr(pkg, changingPkg);
8955            } catch (PackageManagerException e) {
8956                // If a system app update or an app and a required lib missing we
8957                // delete the package and for updated system apps keep the data as
8958                // it is better for the user to reinstall than to be in an limbo
8959                // state. Also libs disappearing under an app should never happen
8960                // - just in case.
8961                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8962                    final int flags = pkg.isUpdatedSystemApp()
8963                            ? PackageManager.DELETE_KEEP_DATA : 0;
8964                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8965                            flags , null, true, null);
8966                }
8967                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8968            }
8969        }
8970        return res;
8971    }
8972
8973    /**
8974     * Derive the value of the {@code cpuAbiOverride} based on the provided
8975     * value and an optional stored value from the package settings.
8976     */
8977    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8978        String cpuAbiOverride = null;
8979
8980        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8981            cpuAbiOverride = null;
8982        } else if (abiOverride != null) {
8983            cpuAbiOverride = abiOverride;
8984        } else if (settings != null) {
8985            cpuAbiOverride = settings.cpuAbiOverrideString;
8986        }
8987
8988        return cpuAbiOverride;
8989    }
8990
8991    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8992            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8993                    throws PackageManagerException {
8994        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8995        // If the package has children and this is the first dive in the function
8996        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8997        // whether all packages (parent and children) would be successfully scanned
8998        // before the actual scan since scanning mutates internal state and we want
8999        // to atomically install the package and its children.
9000        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9001            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9002                scanFlags |= SCAN_CHECK_ONLY;
9003            }
9004        } else {
9005            scanFlags &= ~SCAN_CHECK_ONLY;
9006        }
9007
9008        final PackageParser.Package scannedPkg;
9009        try {
9010            // Scan the parent
9011            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9012            // Scan the children
9013            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9014            for (int i = 0; i < childCount; i++) {
9015                PackageParser.Package childPkg = pkg.childPackages.get(i);
9016                scanPackageLI(childPkg, policyFlags,
9017                        scanFlags, currentTime, user);
9018            }
9019        } finally {
9020            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9021        }
9022
9023        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9024            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9025        }
9026
9027        return scannedPkg;
9028    }
9029
9030    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9031            int scanFlags, long currentTime, @Nullable UserHandle user)
9032                    throws PackageManagerException {
9033        boolean success = false;
9034        try {
9035            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9036                    currentTime, user);
9037            success = true;
9038            return res;
9039        } finally {
9040            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9041                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9042                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9043                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9044                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9045            }
9046        }
9047    }
9048
9049    /**
9050     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9051     */
9052    private static boolean apkHasCode(String fileName) {
9053        StrictJarFile jarFile = null;
9054        try {
9055            jarFile = new StrictJarFile(fileName,
9056                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9057            return jarFile.findEntry("classes.dex") != null;
9058        } catch (IOException ignore) {
9059        } finally {
9060            try {
9061                if (jarFile != null) {
9062                    jarFile.close();
9063                }
9064            } catch (IOException ignore) {}
9065        }
9066        return false;
9067    }
9068
9069    /**
9070     * Enforces code policy for the package. This ensures that if an APK has
9071     * declared hasCode="true" in its manifest that the APK actually contains
9072     * code.
9073     *
9074     * @throws PackageManagerException If bytecode could not be found when it should exist
9075     */
9076    private static void assertCodePolicy(PackageParser.Package pkg)
9077            throws PackageManagerException {
9078        final boolean shouldHaveCode =
9079                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9080        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9081            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9082                    "Package " + pkg.baseCodePath + " code is missing");
9083        }
9084
9085        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9086            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9087                final boolean splitShouldHaveCode =
9088                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9089                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9090                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9091                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9092                }
9093            }
9094        }
9095    }
9096
9097    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9098            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9099                    throws PackageManagerException {
9100        if (DEBUG_PACKAGE_SCANNING) {
9101            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9102                Log.d(TAG, "Scanning package " + pkg.packageName);
9103        }
9104
9105        applyPolicy(pkg, policyFlags);
9106
9107        assertPackageIsValid(pkg, policyFlags, scanFlags);
9108
9109        // Initialize package source and resource directories
9110        final File scanFile = new File(pkg.codePath);
9111        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9112        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9113
9114        SharedUserSetting suid = null;
9115        PackageSetting pkgSetting = null;
9116
9117        // Getting the package setting may have a side-effect, so if we
9118        // are only checking if scan would succeed, stash a copy of the
9119        // old setting to restore at the end.
9120        PackageSetting nonMutatedPs = null;
9121
9122        // We keep references to the derived CPU Abis from settings in oder to reuse
9123        // them in the case where we're not upgrading or booting for the first time.
9124        String primaryCpuAbiFromSettings = null;
9125        String secondaryCpuAbiFromSettings = null;
9126
9127        // writer
9128        synchronized (mPackages) {
9129            if (pkg.mSharedUserId != null) {
9130                // SIDE EFFECTS; may potentially allocate a new shared user
9131                suid = mSettings.getSharedUserLPw(
9132                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9133                if (DEBUG_PACKAGE_SCANNING) {
9134                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9135                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9136                                + "): packages=" + suid.packages);
9137                }
9138            }
9139
9140            // Check if we are renaming from an original package name.
9141            PackageSetting origPackage = null;
9142            String realName = null;
9143            if (pkg.mOriginalPackages != null) {
9144                // This package may need to be renamed to a previously
9145                // installed name.  Let's check on that...
9146                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9147                if (pkg.mOriginalPackages.contains(renamed)) {
9148                    // This package had originally been installed as the
9149                    // original name, and we have already taken care of
9150                    // transitioning to the new one.  Just update the new
9151                    // one to continue using the old name.
9152                    realName = pkg.mRealPackage;
9153                    if (!pkg.packageName.equals(renamed)) {
9154                        // Callers into this function may have already taken
9155                        // care of renaming the package; only do it here if
9156                        // it is not already done.
9157                        pkg.setPackageName(renamed);
9158                    }
9159                } else {
9160                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9161                        if ((origPackage = mSettings.getPackageLPr(
9162                                pkg.mOriginalPackages.get(i))) != null) {
9163                            // We do have the package already installed under its
9164                            // original name...  should we use it?
9165                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9166                                // New package is not compatible with original.
9167                                origPackage = null;
9168                                continue;
9169                            } else if (origPackage.sharedUser != null) {
9170                                // Make sure uid is compatible between packages.
9171                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9172                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9173                                            + " to " + pkg.packageName + ": old uid "
9174                                            + origPackage.sharedUser.name
9175                                            + " differs from " + pkg.mSharedUserId);
9176                                    origPackage = null;
9177                                    continue;
9178                                }
9179                                // TODO: Add case when shared user id is added [b/28144775]
9180                            } else {
9181                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9182                                        + pkg.packageName + " to old name " + origPackage.name);
9183                            }
9184                            break;
9185                        }
9186                    }
9187                }
9188            }
9189
9190            if (mTransferedPackages.contains(pkg.packageName)) {
9191                Slog.w(TAG, "Package " + pkg.packageName
9192                        + " was transferred to another, but its .apk remains");
9193            }
9194
9195            // See comments in nonMutatedPs declaration
9196            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9197                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9198                if (foundPs != null) {
9199                    nonMutatedPs = new PackageSetting(foundPs);
9200                }
9201            }
9202
9203            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9204                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9205                if (foundPs != null) {
9206                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9207                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9208                }
9209            }
9210
9211            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9212            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9213                PackageManagerService.reportSettingsProblem(Log.WARN,
9214                        "Package " + pkg.packageName + " shared user changed from "
9215                                + (pkgSetting.sharedUser != null
9216                                        ? pkgSetting.sharedUser.name : "<nothing>")
9217                                + " to "
9218                                + (suid != null ? suid.name : "<nothing>")
9219                                + "; replacing with new");
9220                pkgSetting = null;
9221            }
9222            final PackageSetting oldPkgSetting =
9223                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9224            final PackageSetting disabledPkgSetting =
9225                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9226
9227            String[] usesStaticLibraries = null;
9228            if (pkg.usesStaticLibraries != null) {
9229                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9230                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9231            }
9232
9233            if (pkgSetting == null) {
9234                final String parentPackageName = (pkg.parentPackage != null)
9235                        ? pkg.parentPackage.packageName : null;
9236                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9237                // REMOVE SharedUserSetting from method; update in a separate call
9238                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9239                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9240                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9241                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9242                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9243                        true /*allowInstall*/, instantApp, parentPackageName,
9244                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9245                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9246                // SIDE EFFECTS; updates system state; move elsewhere
9247                if (origPackage != null) {
9248                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9249                }
9250                mSettings.addUserToSettingLPw(pkgSetting);
9251            } else {
9252                // REMOVE SharedUserSetting from method; update in a separate call.
9253                //
9254                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9255                // secondaryCpuAbi are not known at this point so we always update them
9256                // to null here, only to reset them at a later point.
9257                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9258                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9259                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9260                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9261                        UserManagerService.getInstance(), usesStaticLibraries,
9262                        pkg.usesStaticLibrariesVersions);
9263            }
9264            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9265            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9266
9267            // SIDE EFFECTS; modifies system state; move elsewhere
9268            if (pkgSetting.origPackage != null) {
9269                // If we are first transitioning from an original package,
9270                // fix up the new package's name now.  We need to do this after
9271                // looking up the package under its new name, so getPackageLP
9272                // can take care of fiddling things correctly.
9273                pkg.setPackageName(origPackage.name);
9274
9275                // File a report about this.
9276                String msg = "New package " + pkgSetting.realName
9277                        + " renamed to replace old package " + pkgSetting.name;
9278                reportSettingsProblem(Log.WARN, msg);
9279
9280                // Make a note of it.
9281                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9282                    mTransferedPackages.add(origPackage.name);
9283                }
9284
9285                // No longer need to retain this.
9286                pkgSetting.origPackage = null;
9287            }
9288
9289            // SIDE EFFECTS; modifies system state; move elsewhere
9290            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9291                // Make a note of it.
9292                mTransferedPackages.add(pkg.packageName);
9293            }
9294
9295            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9296                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9297            }
9298
9299            if ((scanFlags & SCAN_BOOTING) == 0
9300                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9301                // Check all shared libraries and map to their actual file path.
9302                // We only do this here for apps not on a system dir, because those
9303                // are the only ones that can fail an install due to this.  We
9304                // will take care of the system apps by updating all of their
9305                // library paths after the scan is done. Also during the initial
9306                // scan don't update any libs as we do this wholesale after all
9307                // apps are scanned to avoid dependency based scanning.
9308                updateSharedLibrariesLPr(pkg, null);
9309            }
9310
9311            if (mFoundPolicyFile) {
9312                SELinuxMMAC.assignSeInfoValue(pkg);
9313            }
9314            pkg.applicationInfo.uid = pkgSetting.appId;
9315            pkg.mExtras = pkgSetting;
9316
9317
9318            // Static shared libs have same package with different versions where
9319            // we internally use a synthetic package name to allow multiple versions
9320            // of the same package, therefore we need to compare signatures against
9321            // the package setting for the latest library version.
9322            PackageSetting signatureCheckPs = pkgSetting;
9323            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9324                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9325                if (libraryEntry != null) {
9326                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9327                }
9328            }
9329
9330            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9331                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9332                    // We just determined the app is signed correctly, so bring
9333                    // over the latest parsed certs.
9334                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9335                } else {
9336                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9337                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9338                                "Package " + pkg.packageName + " upgrade keys do not match the "
9339                                + "previously installed version");
9340                    } else {
9341                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9342                        String msg = "System package " + pkg.packageName
9343                                + " signature changed; retaining data.";
9344                        reportSettingsProblem(Log.WARN, msg);
9345                    }
9346                }
9347            } else {
9348                try {
9349                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9350                    verifySignaturesLP(signatureCheckPs, pkg);
9351                    // We just determined the app is signed correctly, so bring
9352                    // over the latest parsed certs.
9353                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9354                } catch (PackageManagerException e) {
9355                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9356                        throw e;
9357                    }
9358                    // The signature has changed, but this package is in the system
9359                    // image...  let's recover!
9360                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9361                    // However...  if this package is part of a shared user, but it
9362                    // doesn't match the signature of the shared user, let's fail.
9363                    // What this means is that you can't change the signatures
9364                    // associated with an overall shared user, which doesn't seem all
9365                    // that unreasonable.
9366                    if (signatureCheckPs.sharedUser != null) {
9367                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9368                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9369                            throw new PackageManagerException(
9370                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9371                                    "Signature mismatch for shared user: "
9372                                            + pkgSetting.sharedUser);
9373                        }
9374                    }
9375                    // File a report about this.
9376                    String msg = "System package " + pkg.packageName
9377                            + " signature changed; retaining data.";
9378                    reportSettingsProblem(Log.WARN, msg);
9379                }
9380            }
9381
9382            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9383                // This package wants to adopt ownership of permissions from
9384                // another package.
9385                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9386                    final String origName = pkg.mAdoptPermissions.get(i);
9387                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9388                    if (orig != null) {
9389                        if (verifyPackageUpdateLPr(orig, pkg)) {
9390                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9391                                    + pkg.packageName);
9392                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9393                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9394                        }
9395                    }
9396                }
9397            }
9398        }
9399
9400        pkg.applicationInfo.processName = fixProcessName(
9401                pkg.applicationInfo.packageName,
9402                pkg.applicationInfo.processName);
9403
9404        if (pkg != mPlatformPackage) {
9405            // Get all of our default paths setup
9406            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9407        }
9408
9409        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9410
9411        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9412            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9413                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9414                derivePackageAbi(
9415                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9416                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9417
9418                // Some system apps still use directory structure for native libraries
9419                // in which case we might end up not detecting abi solely based on apk
9420                // structure. Try to detect abi based on directory structure.
9421                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9422                        pkg.applicationInfo.primaryCpuAbi == null) {
9423                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9424                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9425                }
9426            } else {
9427                // This is not a first boot or an upgrade, don't bother deriving the
9428                // ABI during the scan. Instead, trust the value that was stored in the
9429                // package setting.
9430                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9431                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9432
9433                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9434
9435                if (DEBUG_ABI_SELECTION) {
9436                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9437                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9438                        pkg.applicationInfo.secondaryCpuAbi);
9439                }
9440            }
9441        } else {
9442            if ((scanFlags & SCAN_MOVE) != 0) {
9443                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9444                // but we already have this packages package info in the PackageSetting. We just
9445                // use that and derive the native library path based on the new codepath.
9446                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9447                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9448            }
9449
9450            // Set native library paths again. For moves, the path will be updated based on the
9451            // ABIs we've determined above. For non-moves, the path will be updated based on the
9452            // ABIs we determined during compilation, but the path will depend on the final
9453            // package path (after the rename away from the stage path).
9454            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9455        }
9456
9457        // This is a special case for the "system" package, where the ABI is
9458        // dictated by the zygote configuration (and init.rc). We should keep track
9459        // of this ABI so that we can deal with "normal" applications that run under
9460        // the same UID correctly.
9461        if (mPlatformPackage == pkg) {
9462            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9463                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9464        }
9465
9466        // If there's a mismatch between the abi-override in the package setting
9467        // and the abiOverride specified for the install. Warn about this because we
9468        // would've already compiled the app without taking the package setting into
9469        // account.
9470        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9471            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9472                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9473                        " for package " + pkg.packageName);
9474            }
9475        }
9476
9477        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9478        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9479        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9480
9481        // Copy the derived override back to the parsed package, so that we can
9482        // update the package settings accordingly.
9483        pkg.cpuAbiOverride = cpuAbiOverride;
9484
9485        if (DEBUG_ABI_SELECTION) {
9486            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9487                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9488                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9489        }
9490
9491        // Push the derived path down into PackageSettings so we know what to
9492        // clean up at uninstall time.
9493        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9494
9495        if (DEBUG_ABI_SELECTION) {
9496            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9497                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9498                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9499        }
9500
9501        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9502        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9503            // We don't do this here during boot because we can do it all
9504            // at once after scanning all existing packages.
9505            //
9506            // We also do this *before* we perform dexopt on this package, so that
9507            // we can avoid redundant dexopts, and also to make sure we've got the
9508            // code and package path correct.
9509            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9510        }
9511
9512        if (mFactoryTest && pkg.requestedPermissions.contains(
9513                android.Manifest.permission.FACTORY_TEST)) {
9514            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9515        }
9516
9517        if (isSystemApp(pkg)) {
9518            pkgSetting.isOrphaned = true;
9519        }
9520
9521        // Take care of first install / last update times.
9522        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9523        if (currentTime != 0) {
9524            if (pkgSetting.firstInstallTime == 0) {
9525                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9526            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9527                pkgSetting.lastUpdateTime = currentTime;
9528            }
9529        } else if (pkgSetting.firstInstallTime == 0) {
9530            // We need *something*.  Take time time stamp of the file.
9531            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9532        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9533            if (scanFileTime != pkgSetting.timeStamp) {
9534                // A package on the system image has changed; consider this
9535                // to be an update.
9536                pkgSetting.lastUpdateTime = scanFileTime;
9537            }
9538        }
9539        pkgSetting.setTimeStamp(scanFileTime);
9540
9541        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9542            if (nonMutatedPs != null) {
9543                synchronized (mPackages) {
9544                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9545                }
9546            }
9547        } else {
9548            final int userId = user == null ? 0 : user.getIdentifier();
9549            // Modify state for the given package setting
9550            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9551                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9552            if (pkgSetting.getInstantApp(userId)) {
9553                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9554            }
9555        }
9556        return pkg;
9557    }
9558
9559    /**
9560     * Applies policy to the parsed package based upon the given policy flags.
9561     * Ensures the package is in a good state.
9562     * <p>
9563     * Implementation detail: This method must NOT have any side effect. It would
9564     * ideally be static, but, it requires locks to read system state.
9565     */
9566    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9567        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9568            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9569            if (pkg.applicationInfo.isDirectBootAware()) {
9570                // we're direct boot aware; set for all components
9571                for (PackageParser.Service s : pkg.services) {
9572                    s.info.encryptionAware = s.info.directBootAware = true;
9573                }
9574                for (PackageParser.Provider p : pkg.providers) {
9575                    p.info.encryptionAware = p.info.directBootAware = true;
9576                }
9577                for (PackageParser.Activity a : pkg.activities) {
9578                    a.info.encryptionAware = a.info.directBootAware = true;
9579                }
9580                for (PackageParser.Activity r : pkg.receivers) {
9581                    r.info.encryptionAware = r.info.directBootAware = true;
9582                }
9583            }
9584        } else {
9585            // Only allow system apps to be flagged as core apps.
9586            pkg.coreApp = false;
9587            // clear flags not applicable to regular apps
9588            pkg.applicationInfo.privateFlags &=
9589                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9590            pkg.applicationInfo.privateFlags &=
9591                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9592        }
9593        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9594
9595        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9596            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9597        }
9598
9599        if (!isSystemApp(pkg)) {
9600            // Only system apps can use these features.
9601            pkg.mOriginalPackages = null;
9602            pkg.mRealPackage = null;
9603            pkg.mAdoptPermissions = null;
9604        }
9605    }
9606
9607    /**
9608     * Asserts the parsed package is valid according to the given policy. If the
9609     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9610     * <p>
9611     * Implementation detail: This method must NOT have any side effects. It would
9612     * ideally be static, but, it requires locks to read system state.
9613     *
9614     * @throws PackageManagerException If the package fails any of the validation checks
9615     */
9616    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9617            throws PackageManagerException {
9618        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9619            assertCodePolicy(pkg);
9620        }
9621
9622        if (pkg.applicationInfo.getCodePath() == null ||
9623                pkg.applicationInfo.getResourcePath() == null) {
9624            // Bail out. The resource and code paths haven't been set.
9625            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9626                    "Code and resource paths haven't been set correctly");
9627        }
9628
9629        // Make sure we're not adding any bogus keyset info
9630        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9631        ksms.assertScannedPackageValid(pkg);
9632
9633        synchronized (mPackages) {
9634            // The special "android" package can only be defined once
9635            if (pkg.packageName.equals("android")) {
9636                if (mAndroidApplication != null) {
9637                    Slog.w(TAG, "*************************************************");
9638                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9639                    Slog.w(TAG, " codePath=" + pkg.codePath);
9640                    Slog.w(TAG, "*************************************************");
9641                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9642                            "Core android package being redefined.  Skipping.");
9643                }
9644            }
9645
9646            // A package name must be unique; don't allow duplicates
9647            if (mPackages.containsKey(pkg.packageName)) {
9648                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9649                        "Application package " + pkg.packageName
9650                        + " already installed.  Skipping duplicate.");
9651            }
9652
9653            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9654                // Static libs have a synthetic package name containing the version
9655                // but we still want the base name to be unique.
9656                if (mPackages.containsKey(pkg.manifestPackageName)) {
9657                    throw new PackageManagerException(
9658                            "Duplicate static shared lib provider package");
9659                }
9660
9661                // Static shared libraries should have at least O target SDK
9662                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9663                    throw new PackageManagerException(
9664                            "Packages declaring static-shared libs must target O SDK or higher");
9665                }
9666
9667                // Package declaring static a shared lib cannot be instant apps
9668                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9669                    throw new PackageManagerException(
9670                            "Packages declaring static-shared libs cannot be instant apps");
9671                }
9672
9673                // Package declaring static a shared lib cannot be renamed since the package
9674                // name is synthetic and apps can't code around package manager internals.
9675                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9676                    throw new PackageManagerException(
9677                            "Packages declaring static-shared libs cannot be renamed");
9678                }
9679
9680                // Package declaring static a shared lib cannot declare child packages
9681                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9682                    throw new PackageManagerException(
9683                            "Packages declaring static-shared libs cannot have child packages");
9684                }
9685
9686                // Package declaring static a shared lib cannot declare dynamic libs
9687                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9688                    throw new PackageManagerException(
9689                            "Packages declaring static-shared libs cannot declare dynamic libs");
9690                }
9691
9692                // Package declaring static a shared lib cannot declare shared users
9693                if (pkg.mSharedUserId != null) {
9694                    throw new PackageManagerException(
9695                            "Packages declaring static-shared libs cannot declare shared users");
9696                }
9697
9698                // Static shared libs cannot declare activities
9699                if (!pkg.activities.isEmpty()) {
9700                    throw new PackageManagerException(
9701                            "Static shared libs cannot declare activities");
9702                }
9703
9704                // Static shared libs cannot declare services
9705                if (!pkg.services.isEmpty()) {
9706                    throw new PackageManagerException(
9707                            "Static shared libs cannot declare services");
9708                }
9709
9710                // Static shared libs cannot declare providers
9711                if (!pkg.providers.isEmpty()) {
9712                    throw new PackageManagerException(
9713                            "Static shared libs cannot declare content providers");
9714                }
9715
9716                // Static shared libs cannot declare receivers
9717                if (!pkg.receivers.isEmpty()) {
9718                    throw new PackageManagerException(
9719                            "Static shared libs cannot declare broadcast receivers");
9720                }
9721
9722                // Static shared libs cannot declare permission groups
9723                if (!pkg.permissionGroups.isEmpty()) {
9724                    throw new PackageManagerException(
9725                            "Static shared libs cannot declare permission groups");
9726                }
9727
9728                // Static shared libs cannot declare permissions
9729                if (!pkg.permissions.isEmpty()) {
9730                    throw new PackageManagerException(
9731                            "Static shared libs cannot declare permissions");
9732                }
9733
9734                // Static shared libs cannot declare protected broadcasts
9735                if (pkg.protectedBroadcasts != null) {
9736                    throw new PackageManagerException(
9737                            "Static shared libs cannot declare protected broadcasts");
9738                }
9739
9740                // Static shared libs cannot be overlay targets
9741                if (pkg.mOverlayTarget != null) {
9742                    throw new PackageManagerException(
9743                            "Static shared libs cannot be overlay targets");
9744                }
9745
9746                // The version codes must be ordered as lib versions
9747                int minVersionCode = Integer.MIN_VALUE;
9748                int maxVersionCode = Integer.MAX_VALUE;
9749
9750                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9751                        pkg.staticSharedLibName);
9752                if (versionedLib != null) {
9753                    final int versionCount = versionedLib.size();
9754                    for (int i = 0; i < versionCount; i++) {
9755                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9756                        // TODO: We will change version code to long, so in the new API it is long
9757                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9758                                .getVersionCode();
9759                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9760                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9761                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9762                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9763                        } else {
9764                            minVersionCode = maxVersionCode = libVersionCode;
9765                            break;
9766                        }
9767                    }
9768                }
9769                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9770                    throw new PackageManagerException("Static shared"
9771                            + " lib version codes must be ordered as lib versions");
9772                }
9773            }
9774
9775            // Only privileged apps and updated privileged apps can add child packages.
9776            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9777                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9778                    throw new PackageManagerException("Only privileged apps can add child "
9779                            + "packages. Ignoring package " + pkg.packageName);
9780                }
9781                final int childCount = pkg.childPackages.size();
9782                for (int i = 0; i < childCount; i++) {
9783                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9784                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9785                            childPkg.packageName)) {
9786                        throw new PackageManagerException("Can't override child of "
9787                                + "another disabled app. Ignoring package " + pkg.packageName);
9788                    }
9789                }
9790            }
9791
9792            // If we're only installing presumed-existing packages, require that the
9793            // scanned APK is both already known and at the path previously established
9794            // for it.  Previously unknown packages we pick up normally, but if we have an
9795            // a priori expectation about this package's install presence, enforce it.
9796            // With a singular exception for new system packages. When an OTA contains
9797            // a new system package, we allow the codepath to change from a system location
9798            // to the user-installed location. If we don't allow this change, any newer,
9799            // user-installed version of the application will be ignored.
9800            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9801                if (mExpectingBetter.containsKey(pkg.packageName)) {
9802                    logCriticalInfo(Log.WARN,
9803                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9804                } else {
9805                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9806                    if (known != null) {
9807                        if (DEBUG_PACKAGE_SCANNING) {
9808                            Log.d(TAG, "Examining " + pkg.codePath
9809                                    + " and requiring known paths " + known.codePathString
9810                                    + " & " + known.resourcePathString);
9811                        }
9812                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9813                                || !pkg.applicationInfo.getResourcePath().equals(
9814                                        known.resourcePathString)) {
9815                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9816                                    "Application package " + pkg.packageName
9817                                    + " found at " + pkg.applicationInfo.getCodePath()
9818                                    + " but expected at " + known.codePathString
9819                                    + "; ignoring.");
9820                        }
9821                    }
9822                }
9823            }
9824
9825            // Verify that this new package doesn't have any content providers
9826            // that conflict with existing packages.  Only do this if the
9827            // package isn't already installed, since we don't want to break
9828            // things that are installed.
9829            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9830                final int N = pkg.providers.size();
9831                int i;
9832                for (i=0; i<N; i++) {
9833                    PackageParser.Provider p = pkg.providers.get(i);
9834                    if (p.info.authority != null) {
9835                        String names[] = p.info.authority.split(";");
9836                        for (int j = 0; j < names.length; j++) {
9837                            if (mProvidersByAuthority.containsKey(names[j])) {
9838                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9839                                final String otherPackageName =
9840                                        ((other != null && other.getComponentName() != null) ?
9841                                                other.getComponentName().getPackageName() : "?");
9842                                throw new PackageManagerException(
9843                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9844                                        "Can't install because provider name " + names[j]
9845                                                + " (in package " + pkg.applicationInfo.packageName
9846                                                + ") is already used by " + otherPackageName);
9847                            }
9848                        }
9849                    }
9850                }
9851            }
9852        }
9853    }
9854
9855    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9856            int type, String declaringPackageName, int declaringVersionCode) {
9857        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9858        if (versionedLib == null) {
9859            versionedLib = new SparseArray<>();
9860            mSharedLibraries.put(name, versionedLib);
9861            if (type == SharedLibraryInfo.TYPE_STATIC) {
9862                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9863            }
9864        } else if (versionedLib.indexOfKey(version) >= 0) {
9865            return false;
9866        }
9867        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9868                version, type, declaringPackageName, declaringVersionCode);
9869        versionedLib.put(version, libEntry);
9870        return true;
9871    }
9872
9873    private boolean removeSharedLibraryLPw(String name, int version) {
9874        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9875        if (versionedLib == null) {
9876            return false;
9877        }
9878        final int libIdx = versionedLib.indexOfKey(version);
9879        if (libIdx < 0) {
9880            return false;
9881        }
9882        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9883        versionedLib.remove(version);
9884        if (versionedLib.size() <= 0) {
9885            mSharedLibraries.remove(name);
9886            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9887                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9888                        .getPackageName());
9889            }
9890        }
9891        return true;
9892    }
9893
9894    /**
9895     * Adds a scanned package to the system. When this method is finished, the package will
9896     * be available for query, resolution, etc...
9897     */
9898    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9899            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9900        final String pkgName = pkg.packageName;
9901        if (mCustomResolverComponentName != null &&
9902                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9903            setUpCustomResolverActivity(pkg);
9904        }
9905
9906        if (pkg.packageName.equals("android")) {
9907            synchronized (mPackages) {
9908                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9909                    // Set up information for our fall-back user intent resolution activity.
9910                    mPlatformPackage = pkg;
9911                    pkg.mVersionCode = mSdkVersion;
9912                    mAndroidApplication = pkg.applicationInfo;
9913                    if (!mResolverReplaced) {
9914                        mResolveActivity.applicationInfo = mAndroidApplication;
9915                        mResolveActivity.name = ResolverActivity.class.getName();
9916                        mResolveActivity.packageName = mAndroidApplication.packageName;
9917                        mResolveActivity.processName = "system:ui";
9918                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9919                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9920                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9921                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9922                        mResolveActivity.exported = true;
9923                        mResolveActivity.enabled = true;
9924                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9925                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9926                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9927                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9928                                | ActivityInfo.CONFIG_ORIENTATION
9929                                | ActivityInfo.CONFIG_KEYBOARD
9930                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9931                        mResolveInfo.activityInfo = mResolveActivity;
9932                        mResolveInfo.priority = 0;
9933                        mResolveInfo.preferredOrder = 0;
9934                        mResolveInfo.match = 0;
9935                        mResolveComponentName = new ComponentName(
9936                                mAndroidApplication.packageName, mResolveActivity.name);
9937                    }
9938                }
9939            }
9940        }
9941
9942        ArrayList<PackageParser.Package> clientLibPkgs = null;
9943        // writer
9944        synchronized (mPackages) {
9945            boolean hasStaticSharedLibs = false;
9946
9947            // Any app can add new static shared libraries
9948            if (pkg.staticSharedLibName != null) {
9949                // Static shared libs don't allow renaming as they have synthetic package
9950                // names to allow install of multiple versions, so use name from manifest.
9951                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9952                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9953                        pkg.manifestPackageName, pkg.mVersionCode)) {
9954                    hasStaticSharedLibs = true;
9955                } else {
9956                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9957                                + pkg.staticSharedLibName + " already exists; skipping");
9958                }
9959                // Static shared libs cannot be updated once installed since they
9960                // use synthetic package name which includes the version code, so
9961                // not need to update other packages's shared lib dependencies.
9962            }
9963
9964            if (!hasStaticSharedLibs
9965                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9966                // Only system apps can add new dynamic shared libraries.
9967                if (pkg.libraryNames != null) {
9968                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9969                        String name = pkg.libraryNames.get(i);
9970                        boolean allowed = false;
9971                        if (pkg.isUpdatedSystemApp()) {
9972                            // New library entries can only be added through the
9973                            // system image.  This is important to get rid of a lot
9974                            // of nasty edge cases: for example if we allowed a non-
9975                            // system update of the app to add a library, then uninstalling
9976                            // the update would make the library go away, and assumptions
9977                            // we made such as through app install filtering would now
9978                            // have allowed apps on the device which aren't compatible
9979                            // with it.  Better to just have the restriction here, be
9980                            // conservative, and create many fewer cases that can negatively
9981                            // impact the user experience.
9982                            final PackageSetting sysPs = mSettings
9983                                    .getDisabledSystemPkgLPr(pkg.packageName);
9984                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9985                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9986                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9987                                        allowed = true;
9988                                        break;
9989                                    }
9990                                }
9991                            }
9992                        } else {
9993                            allowed = true;
9994                        }
9995                        if (allowed) {
9996                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9997                                    SharedLibraryInfo.VERSION_UNDEFINED,
9998                                    SharedLibraryInfo.TYPE_DYNAMIC,
9999                                    pkg.packageName, pkg.mVersionCode)) {
10000                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10001                                        + name + " already exists; skipping");
10002                            }
10003                        } else {
10004                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10005                                    + name + " that is not declared on system image; skipping");
10006                        }
10007                    }
10008
10009                    if ((scanFlags & SCAN_BOOTING) == 0) {
10010                        // If we are not booting, we need to update any applications
10011                        // that are clients of our shared library.  If we are booting,
10012                        // this will all be done once the scan is complete.
10013                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10014                    }
10015                }
10016            }
10017        }
10018
10019        if ((scanFlags & SCAN_BOOTING) != 0) {
10020            // No apps can run during boot scan, so they don't need to be frozen
10021        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10022            // Caller asked to not kill app, so it's probably not frozen
10023        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10024            // Caller asked us to ignore frozen check for some reason; they
10025            // probably didn't know the package name
10026        } else {
10027            // We're doing major surgery on this package, so it better be frozen
10028            // right now to keep it from launching
10029            checkPackageFrozen(pkgName);
10030        }
10031
10032        // Also need to kill any apps that are dependent on the library.
10033        if (clientLibPkgs != null) {
10034            for (int i=0; i<clientLibPkgs.size(); i++) {
10035                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10036                killApplication(clientPkg.applicationInfo.packageName,
10037                        clientPkg.applicationInfo.uid, "update lib");
10038            }
10039        }
10040
10041        // writer
10042        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10043
10044        synchronized (mPackages) {
10045            // We don't expect installation to fail beyond this point
10046
10047            // Add the new setting to mSettings
10048            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10049            // Add the new setting to mPackages
10050            mPackages.put(pkg.applicationInfo.packageName, pkg);
10051            // Make sure we don't accidentally delete its data.
10052            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10053            while (iter.hasNext()) {
10054                PackageCleanItem item = iter.next();
10055                if (pkgName.equals(item.packageName)) {
10056                    iter.remove();
10057                }
10058            }
10059
10060            // Add the package's KeySets to the global KeySetManagerService
10061            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10062            ksms.addScannedPackageLPw(pkg);
10063
10064            int N = pkg.providers.size();
10065            StringBuilder r = null;
10066            int i;
10067            for (i=0; i<N; i++) {
10068                PackageParser.Provider p = pkg.providers.get(i);
10069                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10070                        p.info.processName);
10071                mProviders.addProvider(p);
10072                p.syncable = p.info.isSyncable;
10073                if (p.info.authority != null) {
10074                    String names[] = p.info.authority.split(";");
10075                    p.info.authority = null;
10076                    for (int j = 0; j < names.length; j++) {
10077                        if (j == 1 && p.syncable) {
10078                            // We only want the first authority for a provider to possibly be
10079                            // syncable, so if we already added this provider using a different
10080                            // authority clear the syncable flag. We copy the provider before
10081                            // changing it because the mProviders object contains a reference
10082                            // to a provider that we don't want to change.
10083                            // Only do this for the second authority since the resulting provider
10084                            // object can be the same for all future authorities for this provider.
10085                            p = new PackageParser.Provider(p);
10086                            p.syncable = false;
10087                        }
10088                        if (!mProvidersByAuthority.containsKey(names[j])) {
10089                            mProvidersByAuthority.put(names[j], p);
10090                            if (p.info.authority == null) {
10091                                p.info.authority = names[j];
10092                            } else {
10093                                p.info.authority = p.info.authority + ";" + names[j];
10094                            }
10095                            if (DEBUG_PACKAGE_SCANNING) {
10096                                if (chatty)
10097                                    Log.d(TAG, "Registered content provider: " + names[j]
10098                                            + ", className = " + p.info.name + ", isSyncable = "
10099                                            + p.info.isSyncable);
10100                            }
10101                        } else {
10102                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10103                            Slog.w(TAG, "Skipping provider name " + names[j] +
10104                                    " (in package " + pkg.applicationInfo.packageName +
10105                                    "): name already used by "
10106                                    + ((other != null && other.getComponentName() != null)
10107                                            ? other.getComponentName().getPackageName() : "?"));
10108                        }
10109                    }
10110                }
10111                if (chatty) {
10112                    if (r == null) {
10113                        r = new StringBuilder(256);
10114                    } else {
10115                        r.append(' ');
10116                    }
10117                    r.append(p.info.name);
10118                }
10119            }
10120            if (r != null) {
10121                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10122            }
10123
10124            N = pkg.services.size();
10125            r = null;
10126            for (i=0; i<N; i++) {
10127                PackageParser.Service s = pkg.services.get(i);
10128                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10129                        s.info.processName);
10130                mServices.addService(s);
10131                if (chatty) {
10132                    if (r == null) {
10133                        r = new StringBuilder(256);
10134                    } else {
10135                        r.append(' ');
10136                    }
10137                    r.append(s.info.name);
10138                }
10139            }
10140            if (r != null) {
10141                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10142            }
10143
10144            N = pkg.receivers.size();
10145            r = null;
10146            for (i=0; i<N; i++) {
10147                PackageParser.Activity a = pkg.receivers.get(i);
10148                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10149                        a.info.processName);
10150                mReceivers.addActivity(a, "receiver");
10151                if (chatty) {
10152                    if (r == null) {
10153                        r = new StringBuilder(256);
10154                    } else {
10155                        r.append(' ');
10156                    }
10157                    r.append(a.info.name);
10158                }
10159            }
10160            if (r != null) {
10161                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10162            }
10163
10164            N = pkg.activities.size();
10165            r = null;
10166            for (i=0; i<N; i++) {
10167                PackageParser.Activity a = pkg.activities.get(i);
10168                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10169                        a.info.processName);
10170                mActivities.addActivity(a, "activity");
10171                if (chatty) {
10172                    if (r == null) {
10173                        r = new StringBuilder(256);
10174                    } else {
10175                        r.append(' ');
10176                    }
10177                    r.append(a.info.name);
10178                }
10179            }
10180            if (r != null) {
10181                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10182            }
10183
10184            N = pkg.permissionGroups.size();
10185            r = null;
10186            for (i=0; i<N; i++) {
10187                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10188                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10189                final String curPackageName = cur == null ? null : cur.info.packageName;
10190                // Dont allow ephemeral apps to define new permission groups.
10191                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10192                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10193                            + pg.info.packageName
10194                            + " ignored: instant apps cannot define new permission groups.");
10195                    continue;
10196                }
10197                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10198                if (cur == null || isPackageUpdate) {
10199                    mPermissionGroups.put(pg.info.name, pg);
10200                    if (chatty) {
10201                        if (r == null) {
10202                            r = new StringBuilder(256);
10203                        } else {
10204                            r.append(' ');
10205                        }
10206                        if (isPackageUpdate) {
10207                            r.append("UPD:");
10208                        }
10209                        r.append(pg.info.name);
10210                    }
10211                } else {
10212                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10213                            + pg.info.packageName + " ignored: original from "
10214                            + cur.info.packageName);
10215                    if (chatty) {
10216                        if (r == null) {
10217                            r = new StringBuilder(256);
10218                        } else {
10219                            r.append(' ');
10220                        }
10221                        r.append("DUP:");
10222                        r.append(pg.info.name);
10223                    }
10224                }
10225            }
10226            if (r != null) {
10227                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10228            }
10229
10230            N = pkg.permissions.size();
10231            r = null;
10232            for (i=0; i<N; i++) {
10233                PackageParser.Permission p = pkg.permissions.get(i);
10234
10235                // Dont allow ephemeral apps to define new permissions.
10236                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10237                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10238                            + p.info.packageName
10239                            + " ignored: instant apps cannot define new permissions.");
10240                    continue;
10241                }
10242
10243                // Assume by default that we did not install this permission into the system.
10244                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10245
10246                // Now that permission groups have a special meaning, we ignore permission
10247                // groups for legacy apps to prevent unexpected behavior. In particular,
10248                // permissions for one app being granted to someone just becase they happen
10249                // to be in a group defined by another app (before this had no implications).
10250                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10251                    p.group = mPermissionGroups.get(p.info.group);
10252                    // Warn for a permission in an unknown group.
10253                    if (p.info.group != null && p.group == null) {
10254                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10255                                + p.info.packageName + " in an unknown group " + p.info.group);
10256                    }
10257                }
10258
10259                ArrayMap<String, BasePermission> permissionMap =
10260                        p.tree ? mSettings.mPermissionTrees
10261                                : mSettings.mPermissions;
10262                BasePermission bp = permissionMap.get(p.info.name);
10263
10264                // Allow system apps to redefine non-system permissions
10265                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10266                    final boolean currentOwnerIsSystem = (bp.perm != null
10267                            && isSystemApp(bp.perm.owner));
10268                    if (isSystemApp(p.owner)) {
10269                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10270                            // It's a built-in permission and no owner, take ownership now
10271                            bp.packageSetting = pkgSetting;
10272                            bp.perm = p;
10273                            bp.uid = pkg.applicationInfo.uid;
10274                            bp.sourcePackage = p.info.packageName;
10275                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10276                        } else if (!currentOwnerIsSystem) {
10277                            String msg = "New decl " + p.owner + " of permission  "
10278                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10279                            reportSettingsProblem(Log.WARN, msg);
10280                            bp = null;
10281                        }
10282                    }
10283                }
10284
10285                if (bp == null) {
10286                    bp = new BasePermission(p.info.name, p.info.packageName,
10287                            BasePermission.TYPE_NORMAL);
10288                    permissionMap.put(p.info.name, bp);
10289                }
10290
10291                if (bp.perm == null) {
10292                    if (bp.sourcePackage == null
10293                            || bp.sourcePackage.equals(p.info.packageName)) {
10294                        BasePermission tree = findPermissionTreeLP(p.info.name);
10295                        if (tree == null
10296                                || tree.sourcePackage.equals(p.info.packageName)) {
10297                            bp.packageSetting = pkgSetting;
10298                            bp.perm = p;
10299                            bp.uid = pkg.applicationInfo.uid;
10300                            bp.sourcePackage = p.info.packageName;
10301                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10302                            if (chatty) {
10303                                if (r == null) {
10304                                    r = new StringBuilder(256);
10305                                } else {
10306                                    r.append(' ');
10307                                }
10308                                r.append(p.info.name);
10309                            }
10310                        } else {
10311                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10312                                    + p.info.packageName + " ignored: base tree "
10313                                    + tree.name + " is from package "
10314                                    + tree.sourcePackage);
10315                        }
10316                    } else {
10317                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10318                                + p.info.packageName + " ignored: original from "
10319                                + bp.sourcePackage);
10320                    }
10321                } else if (chatty) {
10322                    if (r == null) {
10323                        r = new StringBuilder(256);
10324                    } else {
10325                        r.append(' ');
10326                    }
10327                    r.append("DUP:");
10328                    r.append(p.info.name);
10329                }
10330                if (bp.perm == p) {
10331                    bp.protectionLevel = p.info.protectionLevel;
10332                }
10333            }
10334
10335            if (r != null) {
10336                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10337            }
10338
10339            N = pkg.instrumentation.size();
10340            r = null;
10341            for (i=0; i<N; i++) {
10342                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10343                a.info.packageName = pkg.applicationInfo.packageName;
10344                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10345                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10346                a.info.splitNames = pkg.splitNames;
10347                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10348                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10349                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10350                a.info.dataDir = pkg.applicationInfo.dataDir;
10351                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10352                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10353                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10354                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10355                mInstrumentation.put(a.getComponentName(), a);
10356                if (chatty) {
10357                    if (r == null) {
10358                        r = new StringBuilder(256);
10359                    } else {
10360                        r.append(' ');
10361                    }
10362                    r.append(a.info.name);
10363                }
10364            }
10365            if (r != null) {
10366                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10367            }
10368
10369            if (pkg.protectedBroadcasts != null) {
10370                N = pkg.protectedBroadcasts.size();
10371                for (i=0; i<N; i++) {
10372                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10373                }
10374            }
10375        }
10376
10377        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10378    }
10379
10380    /**
10381     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10382     * is derived purely on the basis of the contents of {@code scanFile} and
10383     * {@code cpuAbiOverride}.
10384     *
10385     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10386     */
10387    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10388                                 String cpuAbiOverride, boolean extractLibs,
10389                                 File appLib32InstallDir)
10390            throws PackageManagerException {
10391        // Give ourselves some initial paths; we'll come back for another
10392        // pass once we've determined ABI below.
10393        setNativeLibraryPaths(pkg, appLib32InstallDir);
10394
10395        // We would never need to extract libs for forward-locked and external packages,
10396        // since the container service will do it for us. We shouldn't attempt to
10397        // extract libs from system app when it was not updated.
10398        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10399                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10400            extractLibs = false;
10401        }
10402
10403        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10404        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10405
10406        NativeLibraryHelper.Handle handle = null;
10407        try {
10408            handle = NativeLibraryHelper.Handle.create(pkg);
10409            // TODO(multiArch): This can be null for apps that didn't go through the
10410            // usual installation process. We can calculate it again, like we
10411            // do during install time.
10412            //
10413            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10414            // unnecessary.
10415            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10416
10417            // Null out the abis so that they can be recalculated.
10418            pkg.applicationInfo.primaryCpuAbi = null;
10419            pkg.applicationInfo.secondaryCpuAbi = null;
10420            if (isMultiArch(pkg.applicationInfo)) {
10421                // Warn if we've set an abiOverride for multi-lib packages..
10422                // By definition, we need to copy both 32 and 64 bit libraries for
10423                // such packages.
10424                if (pkg.cpuAbiOverride != null
10425                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10426                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10427                }
10428
10429                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10430                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10431                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10432                    if (extractLibs) {
10433                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10434                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10435                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10436                                useIsaSpecificSubdirs);
10437                    } else {
10438                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10439                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10440                    }
10441                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10442                }
10443
10444                maybeThrowExceptionForMultiArchCopy(
10445                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10446
10447                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10448                    if (extractLibs) {
10449                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10450                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10451                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10452                                useIsaSpecificSubdirs);
10453                    } else {
10454                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10455                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10456                    }
10457                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10458                }
10459
10460                maybeThrowExceptionForMultiArchCopy(
10461                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10462
10463                if (abi64 >= 0) {
10464                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10465                }
10466
10467                if (abi32 >= 0) {
10468                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10469                    if (abi64 >= 0) {
10470                        if (pkg.use32bitAbi) {
10471                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10472                            pkg.applicationInfo.primaryCpuAbi = abi;
10473                        } else {
10474                            pkg.applicationInfo.secondaryCpuAbi = abi;
10475                        }
10476                    } else {
10477                        pkg.applicationInfo.primaryCpuAbi = abi;
10478                    }
10479                }
10480
10481            } else {
10482                String[] abiList = (cpuAbiOverride != null) ?
10483                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10484
10485                // Enable gross and lame hacks for apps that are built with old
10486                // SDK tools. We must scan their APKs for renderscript bitcode and
10487                // not launch them if it's present. Don't bother checking on devices
10488                // that don't have 64 bit support.
10489                boolean needsRenderScriptOverride = false;
10490                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10491                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10492                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10493                    needsRenderScriptOverride = true;
10494                }
10495
10496                final int copyRet;
10497                if (extractLibs) {
10498                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10499                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10500                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10501                } else {
10502                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10503                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10504                }
10505                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10506
10507                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10508                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10509                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10510                }
10511
10512                if (copyRet >= 0) {
10513                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10514                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10515                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10516                } else if (needsRenderScriptOverride) {
10517                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10518                }
10519            }
10520        } catch (IOException ioe) {
10521            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10522        } finally {
10523            IoUtils.closeQuietly(handle);
10524        }
10525
10526        // Now that we've calculated the ABIs and determined if it's an internal app,
10527        // we will go ahead and populate the nativeLibraryPath.
10528        setNativeLibraryPaths(pkg, appLib32InstallDir);
10529    }
10530
10531    /**
10532     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10533     * i.e, so that all packages can be run inside a single process if required.
10534     *
10535     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10536     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10537     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10538     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10539     * updating a package that belongs to a shared user.
10540     *
10541     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10542     * adds unnecessary complexity.
10543     */
10544    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10545            PackageParser.Package scannedPackage) {
10546        String requiredInstructionSet = null;
10547        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10548            requiredInstructionSet = VMRuntime.getInstructionSet(
10549                     scannedPackage.applicationInfo.primaryCpuAbi);
10550        }
10551
10552        PackageSetting requirer = null;
10553        for (PackageSetting ps : packagesForUser) {
10554            // If packagesForUser contains scannedPackage, we skip it. This will happen
10555            // when scannedPackage is an update of an existing package. Without this check,
10556            // we will never be able to change the ABI of any package belonging to a shared
10557            // user, even if it's compatible with other packages.
10558            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10559                if (ps.primaryCpuAbiString == null) {
10560                    continue;
10561                }
10562
10563                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10564                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10565                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10566                    // this but there's not much we can do.
10567                    String errorMessage = "Instruction set mismatch, "
10568                            + ((requirer == null) ? "[caller]" : requirer)
10569                            + " requires " + requiredInstructionSet + " whereas " + ps
10570                            + " requires " + instructionSet;
10571                    Slog.w(TAG, errorMessage);
10572                }
10573
10574                if (requiredInstructionSet == null) {
10575                    requiredInstructionSet = instructionSet;
10576                    requirer = ps;
10577                }
10578            }
10579        }
10580
10581        if (requiredInstructionSet != null) {
10582            String adjustedAbi;
10583            if (requirer != null) {
10584                // requirer != null implies that either scannedPackage was null or that scannedPackage
10585                // did not require an ABI, in which case we have to adjust scannedPackage to match
10586                // the ABI of the set (which is the same as requirer's ABI)
10587                adjustedAbi = requirer.primaryCpuAbiString;
10588                if (scannedPackage != null) {
10589                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10590                }
10591            } else {
10592                // requirer == null implies that we're updating all ABIs in the set to
10593                // match scannedPackage.
10594                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10595            }
10596
10597            for (PackageSetting ps : packagesForUser) {
10598                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10599                    if (ps.primaryCpuAbiString != null) {
10600                        continue;
10601                    }
10602
10603                    ps.primaryCpuAbiString = adjustedAbi;
10604                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10605                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10606                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10607                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10608                                + " (requirer="
10609                                + (requirer != null ? requirer.pkg : "null")
10610                                + ", scannedPackage="
10611                                + (scannedPackage != null ? scannedPackage : "null")
10612                                + ")");
10613                        try {
10614                            mInstaller.rmdex(ps.codePathString,
10615                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10616                        } catch (InstallerException ignored) {
10617                        }
10618                    }
10619                }
10620            }
10621        }
10622    }
10623
10624    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10625        synchronized (mPackages) {
10626            mResolverReplaced = true;
10627            // Set up information for custom user intent resolution activity.
10628            mResolveActivity.applicationInfo = pkg.applicationInfo;
10629            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10630            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10631            mResolveActivity.processName = pkg.applicationInfo.packageName;
10632            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10633            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10634                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10635            mResolveActivity.theme = 0;
10636            mResolveActivity.exported = true;
10637            mResolveActivity.enabled = true;
10638            mResolveInfo.activityInfo = mResolveActivity;
10639            mResolveInfo.priority = 0;
10640            mResolveInfo.preferredOrder = 0;
10641            mResolveInfo.match = 0;
10642            mResolveComponentName = mCustomResolverComponentName;
10643            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10644                    mResolveComponentName);
10645        }
10646    }
10647
10648    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10649        if (installerActivity == null) {
10650            if (DEBUG_EPHEMERAL) {
10651                Slog.d(TAG, "Clear ephemeral installer activity");
10652            }
10653            mInstantAppInstallerActivity = null;
10654            return;
10655        }
10656
10657        if (DEBUG_EPHEMERAL) {
10658            Slog.d(TAG, "Set ephemeral installer activity: "
10659                    + installerActivity.getComponentName());
10660        }
10661        // Set up information for ephemeral installer activity
10662        mInstantAppInstallerActivity = installerActivity;
10663        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10664                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10665        mInstantAppInstallerActivity.exported = true;
10666        mInstantAppInstallerActivity.enabled = true;
10667        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10668        mInstantAppInstallerInfo.priority = 0;
10669        mInstantAppInstallerInfo.preferredOrder = 1;
10670        mInstantAppInstallerInfo.isDefault = true;
10671        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10672                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10673    }
10674
10675    private static String calculateBundledApkRoot(final String codePathString) {
10676        final File codePath = new File(codePathString);
10677        final File codeRoot;
10678        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10679            codeRoot = Environment.getRootDirectory();
10680        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10681            codeRoot = Environment.getOemDirectory();
10682        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10683            codeRoot = Environment.getVendorDirectory();
10684        } else {
10685            // Unrecognized code path; take its top real segment as the apk root:
10686            // e.g. /something/app/blah.apk => /something
10687            try {
10688                File f = codePath.getCanonicalFile();
10689                File parent = f.getParentFile();    // non-null because codePath is a file
10690                File tmp;
10691                while ((tmp = parent.getParentFile()) != null) {
10692                    f = parent;
10693                    parent = tmp;
10694                }
10695                codeRoot = f;
10696                Slog.w(TAG, "Unrecognized code path "
10697                        + codePath + " - using " + codeRoot);
10698            } catch (IOException e) {
10699                // Can't canonicalize the code path -- shenanigans?
10700                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10701                return Environment.getRootDirectory().getPath();
10702            }
10703        }
10704        return codeRoot.getPath();
10705    }
10706
10707    /**
10708     * Derive and set the location of native libraries for the given package,
10709     * which varies depending on where and how the package was installed.
10710     */
10711    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10712        final ApplicationInfo info = pkg.applicationInfo;
10713        final String codePath = pkg.codePath;
10714        final File codeFile = new File(codePath);
10715        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10716        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10717
10718        info.nativeLibraryRootDir = null;
10719        info.nativeLibraryRootRequiresIsa = false;
10720        info.nativeLibraryDir = null;
10721        info.secondaryNativeLibraryDir = null;
10722
10723        if (isApkFile(codeFile)) {
10724            // Monolithic install
10725            if (bundledApp) {
10726                // If "/system/lib64/apkname" exists, assume that is the per-package
10727                // native library directory to use; otherwise use "/system/lib/apkname".
10728                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10729                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10730                        getPrimaryInstructionSet(info));
10731
10732                // This is a bundled system app so choose the path based on the ABI.
10733                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10734                // is just the default path.
10735                final String apkName = deriveCodePathName(codePath);
10736                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10737                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10738                        apkName).getAbsolutePath();
10739
10740                if (info.secondaryCpuAbi != null) {
10741                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10742                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10743                            secondaryLibDir, apkName).getAbsolutePath();
10744                }
10745            } else if (asecApp) {
10746                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10747                        .getAbsolutePath();
10748            } else {
10749                final String apkName = deriveCodePathName(codePath);
10750                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10751                        .getAbsolutePath();
10752            }
10753
10754            info.nativeLibraryRootRequiresIsa = false;
10755            info.nativeLibraryDir = info.nativeLibraryRootDir;
10756        } else {
10757            // Cluster install
10758            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10759            info.nativeLibraryRootRequiresIsa = true;
10760
10761            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10762                    getPrimaryInstructionSet(info)).getAbsolutePath();
10763
10764            if (info.secondaryCpuAbi != null) {
10765                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10766                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10767            }
10768        }
10769    }
10770
10771    /**
10772     * Calculate the abis and roots for a bundled app. These can uniquely
10773     * be determined from the contents of the system partition, i.e whether
10774     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10775     * of this information, and instead assume that the system was built
10776     * sensibly.
10777     */
10778    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10779                                           PackageSetting pkgSetting) {
10780        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10781
10782        // If "/system/lib64/apkname" exists, assume that is the per-package
10783        // native library directory to use; otherwise use "/system/lib/apkname".
10784        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10785        setBundledAppAbi(pkg, apkRoot, apkName);
10786        // pkgSetting might be null during rescan following uninstall of updates
10787        // to a bundled app, so accommodate that possibility.  The settings in
10788        // that case will be established later from the parsed package.
10789        //
10790        // If the settings aren't null, sync them up with what we've just derived.
10791        // note that apkRoot isn't stored in the package settings.
10792        if (pkgSetting != null) {
10793            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10794            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10795        }
10796    }
10797
10798    /**
10799     * Deduces the ABI of a bundled app and sets the relevant fields on the
10800     * parsed pkg object.
10801     *
10802     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10803     *        under which system libraries are installed.
10804     * @param apkName the name of the installed package.
10805     */
10806    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10807        final File codeFile = new File(pkg.codePath);
10808
10809        final boolean has64BitLibs;
10810        final boolean has32BitLibs;
10811        if (isApkFile(codeFile)) {
10812            // Monolithic install
10813            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10814            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10815        } else {
10816            // Cluster install
10817            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10818            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10819                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10820                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10821                has64BitLibs = (new File(rootDir, isa)).exists();
10822            } else {
10823                has64BitLibs = false;
10824            }
10825            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10826                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10827                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10828                has32BitLibs = (new File(rootDir, isa)).exists();
10829            } else {
10830                has32BitLibs = false;
10831            }
10832        }
10833
10834        if (has64BitLibs && !has32BitLibs) {
10835            // The package has 64 bit libs, but not 32 bit libs. Its primary
10836            // ABI should be 64 bit. We can safely assume here that the bundled
10837            // native libraries correspond to the most preferred ABI in the list.
10838
10839            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10840            pkg.applicationInfo.secondaryCpuAbi = null;
10841        } else if (has32BitLibs && !has64BitLibs) {
10842            // The package has 32 bit libs but not 64 bit libs. Its primary
10843            // ABI should be 32 bit.
10844
10845            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10846            pkg.applicationInfo.secondaryCpuAbi = null;
10847        } else if (has32BitLibs && has64BitLibs) {
10848            // The application has both 64 and 32 bit bundled libraries. We check
10849            // here that the app declares multiArch support, and warn if it doesn't.
10850            //
10851            // We will be lenient here and record both ABIs. The primary will be the
10852            // ABI that's higher on the list, i.e, a device that's configured to prefer
10853            // 64 bit apps will see a 64 bit primary ABI,
10854
10855            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10856                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10857            }
10858
10859            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10860                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10861                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10862            } else {
10863                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10864                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10865            }
10866        } else {
10867            pkg.applicationInfo.primaryCpuAbi = null;
10868            pkg.applicationInfo.secondaryCpuAbi = null;
10869        }
10870    }
10871
10872    private void killApplication(String pkgName, int appId, String reason) {
10873        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10874    }
10875
10876    private void killApplication(String pkgName, int appId, int userId, String reason) {
10877        // Request the ActivityManager to kill the process(only for existing packages)
10878        // so that we do not end up in a confused state while the user is still using the older
10879        // version of the application while the new one gets installed.
10880        final long token = Binder.clearCallingIdentity();
10881        try {
10882            IActivityManager am = ActivityManager.getService();
10883            if (am != null) {
10884                try {
10885                    am.killApplication(pkgName, appId, userId, reason);
10886                } catch (RemoteException e) {
10887                }
10888            }
10889        } finally {
10890            Binder.restoreCallingIdentity(token);
10891        }
10892    }
10893
10894    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10895        // Remove the parent package setting
10896        PackageSetting ps = (PackageSetting) pkg.mExtras;
10897        if (ps != null) {
10898            removePackageLI(ps, chatty);
10899        }
10900        // Remove the child package setting
10901        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10902        for (int i = 0; i < childCount; i++) {
10903            PackageParser.Package childPkg = pkg.childPackages.get(i);
10904            ps = (PackageSetting) childPkg.mExtras;
10905            if (ps != null) {
10906                removePackageLI(ps, chatty);
10907            }
10908        }
10909    }
10910
10911    void removePackageLI(PackageSetting ps, boolean chatty) {
10912        if (DEBUG_INSTALL) {
10913            if (chatty)
10914                Log.d(TAG, "Removing package " + ps.name);
10915        }
10916
10917        // writer
10918        synchronized (mPackages) {
10919            mPackages.remove(ps.name);
10920            final PackageParser.Package pkg = ps.pkg;
10921            if (pkg != null) {
10922                cleanPackageDataStructuresLILPw(pkg, chatty);
10923            }
10924        }
10925    }
10926
10927    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10928        if (DEBUG_INSTALL) {
10929            if (chatty)
10930                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10931        }
10932
10933        // writer
10934        synchronized (mPackages) {
10935            // Remove the parent package
10936            mPackages.remove(pkg.applicationInfo.packageName);
10937            cleanPackageDataStructuresLILPw(pkg, chatty);
10938
10939            // Remove the child packages
10940            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10941            for (int i = 0; i < childCount; i++) {
10942                PackageParser.Package childPkg = pkg.childPackages.get(i);
10943                mPackages.remove(childPkg.applicationInfo.packageName);
10944                cleanPackageDataStructuresLILPw(childPkg, chatty);
10945            }
10946        }
10947    }
10948
10949    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10950        int N = pkg.providers.size();
10951        StringBuilder r = null;
10952        int i;
10953        for (i=0; i<N; i++) {
10954            PackageParser.Provider p = pkg.providers.get(i);
10955            mProviders.removeProvider(p);
10956            if (p.info.authority == null) {
10957
10958                /* There was another ContentProvider with this authority when
10959                 * this app was installed so this authority is null,
10960                 * Ignore it as we don't have to unregister the provider.
10961                 */
10962                continue;
10963            }
10964            String names[] = p.info.authority.split(";");
10965            for (int j = 0; j < names.length; j++) {
10966                if (mProvidersByAuthority.get(names[j]) == p) {
10967                    mProvidersByAuthority.remove(names[j]);
10968                    if (DEBUG_REMOVE) {
10969                        if (chatty)
10970                            Log.d(TAG, "Unregistered content provider: " + names[j]
10971                                    + ", className = " + p.info.name + ", isSyncable = "
10972                                    + p.info.isSyncable);
10973                    }
10974                }
10975            }
10976            if (DEBUG_REMOVE && chatty) {
10977                if (r == null) {
10978                    r = new StringBuilder(256);
10979                } else {
10980                    r.append(' ');
10981                }
10982                r.append(p.info.name);
10983            }
10984        }
10985        if (r != null) {
10986            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10987        }
10988
10989        N = pkg.services.size();
10990        r = null;
10991        for (i=0; i<N; i++) {
10992            PackageParser.Service s = pkg.services.get(i);
10993            mServices.removeService(s);
10994            if (chatty) {
10995                if (r == null) {
10996                    r = new StringBuilder(256);
10997                } else {
10998                    r.append(' ');
10999                }
11000                r.append(s.info.name);
11001            }
11002        }
11003        if (r != null) {
11004            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11005        }
11006
11007        N = pkg.receivers.size();
11008        r = null;
11009        for (i=0; i<N; i++) {
11010            PackageParser.Activity a = pkg.receivers.get(i);
11011            mReceivers.removeActivity(a, "receiver");
11012            if (DEBUG_REMOVE && chatty) {
11013                if (r == null) {
11014                    r = new StringBuilder(256);
11015                } else {
11016                    r.append(' ');
11017                }
11018                r.append(a.info.name);
11019            }
11020        }
11021        if (r != null) {
11022            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11023        }
11024
11025        N = pkg.activities.size();
11026        r = null;
11027        for (i=0; i<N; i++) {
11028            PackageParser.Activity a = pkg.activities.get(i);
11029            mActivities.removeActivity(a, "activity");
11030            if (DEBUG_REMOVE && chatty) {
11031                if (r == null) {
11032                    r = new StringBuilder(256);
11033                } else {
11034                    r.append(' ');
11035                }
11036                r.append(a.info.name);
11037            }
11038        }
11039        if (r != null) {
11040            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11041        }
11042
11043        N = pkg.permissions.size();
11044        r = null;
11045        for (i=0; i<N; i++) {
11046            PackageParser.Permission p = pkg.permissions.get(i);
11047            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11048            if (bp == null) {
11049                bp = mSettings.mPermissionTrees.get(p.info.name);
11050            }
11051            if (bp != null && bp.perm == p) {
11052                bp.perm = null;
11053                if (DEBUG_REMOVE && chatty) {
11054                    if (r == null) {
11055                        r = new StringBuilder(256);
11056                    } else {
11057                        r.append(' ');
11058                    }
11059                    r.append(p.info.name);
11060                }
11061            }
11062            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11063                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11064                if (appOpPkgs != null) {
11065                    appOpPkgs.remove(pkg.packageName);
11066                }
11067            }
11068        }
11069        if (r != null) {
11070            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11071        }
11072
11073        N = pkg.requestedPermissions.size();
11074        r = null;
11075        for (i=0; i<N; i++) {
11076            String perm = pkg.requestedPermissions.get(i);
11077            BasePermission bp = mSettings.mPermissions.get(perm);
11078            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11079                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11080                if (appOpPkgs != null) {
11081                    appOpPkgs.remove(pkg.packageName);
11082                    if (appOpPkgs.isEmpty()) {
11083                        mAppOpPermissionPackages.remove(perm);
11084                    }
11085                }
11086            }
11087        }
11088        if (r != null) {
11089            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11090        }
11091
11092        N = pkg.instrumentation.size();
11093        r = null;
11094        for (i=0; i<N; i++) {
11095            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11096            mInstrumentation.remove(a.getComponentName());
11097            if (DEBUG_REMOVE && chatty) {
11098                if (r == null) {
11099                    r = new StringBuilder(256);
11100                } else {
11101                    r.append(' ');
11102                }
11103                r.append(a.info.name);
11104            }
11105        }
11106        if (r != null) {
11107            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11108        }
11109
11110        r = null;
11111        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11112            // Only system apps can hold shared libraries.
11113            if (pkg.libraryNames != null) {
11114                for (i = 0; i < pkg.libraryNames.size(); i++) {
11115                    String name = pkg.libraryNames.get(i);
11116                    if (removeSharedLibraryLPw(name, 0)) {
11117                        if (DEBUG_REMOVE && chatty) {
11118                            if (r == null) {
11119                                r = new StringBuilder(256);
11120                            } else {
11121                                r.append(' ');
11122                            }
11123                            r.append(name);
11124                        }
11125                    }
11126                }
11127            }
11128        }
11129
11130        r = null;
11131
11132        // Any package can hold static shared libraries.
11133        if (pkg.staticSharedLibName != null) {
11134            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11135                if (DEBUG_REMOVE && chatty) {
11136                    if (r == null) {
11137                        r = new StringBuilder(256);
11138                    } else {
11139                        r.append(' ');
11140                    }
11141                    r.append(pkg.staticSharedLibName);
11142                }
11143            }
11144        }
11145
11146        if (r != null) {
11147            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11148        }
11149    }
11150
11151    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11152        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11153            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11154                return true;
11155            }
11156        }
11157        return false;
11158    }
11159
11160    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11161    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11162    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11163
11164    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11165        // Update the parent permissions
11166        updatePermissionsLPw(pkg.packageName, pkg, flags);
11167        // Update the child permissions
11168        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11169        for (int i = 0; i < childCount; i++) {
11170            PackageParser.Package childPkg = pkg.childPackages.get(i);
11171            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11172        }
11173    }
11174
11175    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11176            int flags) {
11177        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11178        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11179    }
11180
11181    private void updatePermissionsLPw(String changingPkg,
11182            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11183        // Make sure there are no dangling permission trees.
11184        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11185        while (it.hasNext()) {
11186            final BasePermission bp = it.next();
11187            if (bp.packageSetting == null) {
11188                // We may not yet have parsed the package, so just see if
11189                // we still know about its settings.
11190                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11191            }
11192            if (bp.packageSetting == null) {
11193                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11194                        + " from package " + bp.sourcePackage);
11195                it.remove();
11196            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11197                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11198                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11199                            + " from package " + bp.sourcePackage);
11200                    flags |= UPDATE_PERMISSIONS_ALL;
11201                    it.remove();
11202                }
11203            }
11204        }
11205
11206        // Make sure all dynamic permissions have been assigned to a package,
11207        // and make sure there are no dangling permissions.
11208        it = mSettings.mPermissions.values().iterator();
11209        while (it.hasNext()) {
11210            final BasePermission bp = it.next();
11211            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11212                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11213                        + bp.name + " pkg=" + bp.sourcePackage
11214                        + " info=" + bp.pendingInfo);
11215                if (bp.packageSetting == null && bp.pendingInfo != null) {
11216                    final BasePermission tree = findPermissionTreeLP(bp.name);
11217                    if (tree != null && tree.perm != null) {
11218                        bp.packageSetting = tree.packageSetting;
11219                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11220                                new PermissionInfo(bp.pendingInfo));
11221                        bp.perm.info.packageName = tree.perm.info.packageName;
11222                        bp.perm.info.name = bp.name;
11223                        bp.uid = tree.uid;
11224                    }
11225                }
11226            }
11227            if (bp.packageSetting == null) {
11228                // We may not yet have parsed the package, so just see if
11229                // we still know about its settings.
11230                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11231            }
11232            if (bp.packageSetting == null) {
11233                Slog.w(TAG, "Removing dangling permission: " + bp.name
11234                        + " from package " + bp.sourcePackage);
11235                it.remove();
11236            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11237                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11238                    Slog.i(TAG, "Removing old permission: " + bp.name
11239                            + " from package " + bp.sourcePackage);
11240                    flags |= UPDATE_PERMISSIONS_ALL;
11241                    it.remove();
11242                }
11243            }
11244        }
11245
11246        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11247        // Now update the permissions for all packages, in particular
11248        // replace the granted permissions of the system packages.
11249        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11250            for (PackageParser.Package pkg : mPackages.values()) {
11251                if (pkg != pkgInfo) {
11252                    // Only replace for packages on requested volume
11253                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11254                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11255                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11256                    grantPermissionsLPw(pkg, replace, changingPkg);
11257                }
11258            }
11259        }
11260
11261        if (pkgInfo != null) {
11262            // Only replace for packages on requested volume
11263            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11264            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11265                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11266            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11267        }
11268        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11269    }
11270
11271    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11272            String packageOfInterest) {
11273        // IMPORTANT: There are two types of permissions: install and runtime.
11274        // Install time permissions are granted when the app is installed to
11275        // all device users and users added in the future. Runtime permissions
11276        // are granted at runtime explicitly to specific users. Normal and signature
11277        // protected permissions are install time permissions. Dangerous permissions
11278        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11279        // otherwise they are runtime permissions. This function does not manage
11280        // runtime permissions except for the case an app targeting Lollipop MR1
11281        // being upgraded to target a newer SDK, in which case dangerous permissions
11282        // are transformed from install time to runtime ones.
11283
11284        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11285        if (ps == null) {
11286            return;
11287        }
11288
11289        PermissionsState permissionsState = ps.getPermissionsState();
11290        PermissionsState origPermissions = permissionsState;
11291
11292        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11293
11294        boolean runtimePermissionsRevoked = false;
11295        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11296
11297        boolean changedInstallPermission = false;
11298
11299        if (replace) {
11300            ps.installPermissionsFixed = false;
11301            if (!ps.isSharedUser()) {
11302                origPermissions = new PermissionsState(permissionsState);
11303                permissionsState.reset();
11304            } else {
11305                // We need to know only about runtime permission changes since the
11306                // calling code always writes the install permissions state but
11307                // the runtime ones are written only if changed. The only cases of
11308                // changed runtime permissions here are promotion of an install to
11309                // runtime and revocation of a runtime from a shared user.
11310                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11311                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11312                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11313                    runtimePermissionsRevoked = true;
11314                }
11315            }
11316        }
11317
11318        permissionsState.setGlobalGids(mGlobalGids);
11319
11320        final int N = pkg.requestedPermissions.size();
11321        for (int i=0; i<N; i++) {
11322            final String name = pkg.requestedPermissions.get(i);
11323            final BasePermission bp = mSettings.mPermissions.get(name);
11324
11325            if (DEBUG_INSTALL) {
11326                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11327            }
11328
11329            if (bp == null || bp.packageSetting == null) {
11330                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11331                    Slog.w(TAG, "Unknown permission " + name
11332                            + " in package " + pkg.packageName);
11333                }
11334                continue;
11335            }
11336
11337
11338            // Limit ephemeral apps to ephemeral allowed permissions.
11339            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11340                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11341                        + pkg.packageName);
11342                continue;
11343            }
11344
11345            final String perm = bp.name;
11346            boolean allowedSig = false;
11347            int grant = GRANT_DENIED;
11348
11349            // Keep track of app op permissions.
11350            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11351                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11352                if (pkgs == null) {
11353                    pkgs = new ArraySet<>();
11354                    mAppOpPermissionPackages.put(bp.name, pkgs);
11355                }
11356                pkgs.add(pkg.packageName);
11357            }
11358
11359            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11360            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11361                    >= Build.VERSION_CODES.M;
11362            switch (level) {
11363                case PermissionInfo.PROTECTION_NORMAL: {
11364                    // For all apps normal permissions are install time ones.
11365                    grant = GRANT_INSTALL;
11366                } break;
11367
11368                case PermissionInfo.PROTECTION_DANGEROUS: {
11369                    // If a permission review is required for legacy apps we represent
11370                    // their permissions as always granted runtime ones since we need
11371                    // to keep the review required permission flag per user while an
11372                    // install permission's state is shared across all users.
11373                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11374                        // For legacy apps dangerous permissions are install time ones.
11375                        grant = GRANT_INSTALL;
11376                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11377                        // For legacy apps that became modern, install becomes runtime.
11378                        grant = GRANT_UPGRADE;
11379                    } else if (mPromoteSystemApps
11380                            && isSystemApp(ps)
11381                            && mExistingSystemPackages.contains(ps.name)) {
11382                        // For legacy system apps, install becomes runtime.
11383                        // We cannot check hasInstallPermission() for system apps since those
11384                        // permissions were granted implicitly and not persisted pre-M.
11385                        grant = GRANT_UPGRADE;
11386                    } else {
11387                        // For modern apps keep runtime permissions unchanged.
11388                        grant = GRANT_RUNTIME;
11389                    }
11390                } break;
11391
11392                case PermissionInfo.PROTECTION_SIGNATURE: {
11393                    // For all apps signature permissions are install time ones.
11394                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11395                    if (allowedSig) {
11396                        grant = GRANT_INSTALL;
11397                    }
11398                } break;
11399            }
11400
11401            if (DEBUG_INSTALL) {
11402                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11403            }
11404
11405            if (grant != GRANT_DENIED) {
11406                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11407                    // If this is an existing, non-system package, then
11408                    // we can't add any new permissions to it.
11409                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11410                        // Except...  if this is a permission that was added
11411                        // to the platform (note: need to only do this when
11412                        // updating the platform).
11413                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11414                            grant = GRANT_DENIED;
11415                        }
11416                    }
11417                }
11418
11419                switch (grant) {
11420                    case GRANT_INSTALL: {
11421                        // Revoke this as runtime permission to handle the case of
11422                        // a runtime permission being downgraded to an install one.
11423                        // Also in permission review mode we keep dangerous permissions
11424                        // for legacy apps
11425                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11426                            if (origPermissions.getRuntimePermissionState(
11427                                    bp.name, userId) != null) {
11428                                // Revoke the runtime permission and clear the flags.
11429                                origPermissions.revokeRuntimePermission(bp, userId);
11430                                origPermissions.updatePermissionFlags(bp, userId,
11431                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11432                                // If we revoked a permission permission, we have to write.
11433                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11434                                        changedRuntimePermissionUserIds, userId);
11435                            }
11436                        }
11437                        // Grant an install permission.
11438                        if (permissionsState.grantInstallPermission(bp) !=
11439                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11440                            changedInstallPermission = true;
11441                        }
11442                    } break;
11443
11444                    case GRANT_RUNTIME: {
11445                        // Grant previously granted runtime permissions.
11446                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11447                            PermissionState permissionState = origPermissions
11448                                    .getRuntimePermissionState(bp.name, userId);
11449                            int flags = permissionState != null
11450                                    ? permissionState.getFlags() : 0;
11451                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11452                                // Don't propagate the permission in a permission review mode if
11453                                // the former was revoked, i.e. marked to not propagate on upgrade.
11454                                // Note that in a permission review mode install permissions are
11455                                // represented as constantly granted runtime ones since we need to
11456                                // keep a per user state associated with the permission. Also the
11457                                // revoke on upgrade flag is no longer applicable and is reset.
11458                                final boolean revokeOnUpgrade = (flags & PackageManager
11459                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11460                                if (revokeOnUpgrade) {
11461                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11462                                    // Since we changed the flags, we have to write.
11463                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11464                                            changedRuntimePermissionUserIds, userId);
11465                                }
11466                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11467                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11468                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11469                                        // If we cannot put the permission as it was,
11470                                        // we have to write.
11471                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11472                                                changedRuntimePermissionUserIds, userId);
11473                                    }
11474                                }
11475
11476                                // If the app supports runtime permissions no need for a review.
11477                                if (mPermissionReviewRequired
11478                                        && appSupportsRuntimePermissions
11479                                        && (flags & PackageManager
11480                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11481                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11482                                    // Since we changed the flags, we have to write.
11483                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11484                                            changedRuntimePermissionUserIds, userId);
11485                                }
11486                            } else if (mPermissionReviewRequired
11487                                    && !appSupportsRuntimePermissions) {
11488                                // For legacy apps that need a permission review, every new
11489                                // runtime permission is granted but it is pending a review.
11490                                // We also need to review only platform defined runtime
11491                                // permissions as these are the only ones the platform knows
11492                                // how to disable the API to simulate revocation as legacy
11493                                // apps don't expect to run with revoked permissions.
11494                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11495                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11496                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11497                                        // We changed the flags, hence have to write.
11498                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11499                                                changedRuntimePermissionUserIds, userId);
11500                                    }
11501                                }
11502                                if (permissionsState.grantRuntimePermission(bp, userId)
11503                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11504                                    // We changed the permission, hence have to write.
11505                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11506                                            changedRuntimePermissionUserIds, userId);
11507                                }
11508                            }
11509                            // Propagate the permission flags.
11510                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11511                        }
11512                    } break;
11513
11514                    case GRANT_UPGRADE: {
11515                        // Grant runtime permissions for a previously held install permission.
11516                        PermissionState permissionState = origPermissions
11517                                .getInstallPermissionState(bp.name);
11518                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11519
11520                        if (origPermissions.revokeInstallPermission(bp)
11521                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11522                            // We will be transferring the permission flags, so clear them.
11523                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11524                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11525                            changedInstallPermission = true;
11526                        }
11527
11528                        // If the permission is not to be promoted to runtime we ignore it and
11529                        // also its other flags as they are not applicable to install permissions.
11530                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11531                            for (int userId : currentUserIds) {
11532                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11533                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11534                                    // Transfer the permission flags.
11535                                    permissionsState.updatePermissionFlags(bp, userId,
11536                                            flags, flags);
11537                                    // If we granted the permission, we have to write.
11538                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11539                                            changedRuntimePermissionUserIds, userId);
11540                                }
11541                            }
11542                        }
11543                    } break;
11544
11545                    default: {
11546                        if (packageOfInterest == null
11547                                || packageOfInterest.equals(pkg.packageName)) {
11548                            Slog.w(TAG, "Not granting permission " + perm
11549                                    + " to package " + pkg.packageName
11550                                    + " because it was previously installed without");
11551                        }
11552                    } break;
11553                }
11554            } else {
11555                if (permissionsState.revokeInstallPermission(bp) !=
11556                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11557                    // Also drop the permission flags.
11558                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11559                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11560                    changedInstallPermission = true;
11561                    Slog.i(TAG, "Un-granting permission " + perm
11562                            + " from package " + pkg.packageName
11563                            + " (protectionLevel=" + bp.protectionLevel
11564                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11565                            + ")");
11566                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11567                    // Don't print warning for app op permissions, since it is fine for them
11568                    // not to be granted, there is a UI for the user to decide.
11569                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11570                        Slog.w(TAG, "Not granting permission " + perm
11571                                + " to package " + pkg.packageName
11572                                + " (protectionLevel=" + bp.protectionLevel
11573                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11574                                + ")");
11575                    }
11576                }
11577            }
11578        }
11579
11580        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11581                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11582            // This is the first that we have heard about this package, so the
11583            // permissions we have now selected are fixed until explicitly
11584            // changed.
11585            ps.installPermissionsFixed = true;
11586        }
11587
11588        // Persist the runtime permissions state for users with changes. If permissions
11589        // were revoked because no app in the shared user declares them we have to
11590        // write synchronously to avoid losing runtime permissions state.
11591        for (int userId : changedRuntimePermissionUserIds) {
11592            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11593        }
11594    }
11595
11596    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11597        boolean allowed = false;
11598        final int NP = PackageParser.NEW_PERMISSIONS.length;
11599        for (int ip=0; ip<NP; ip++) {
11600            final PackageParser.NewPermissionInfo npi
11601                    = PackageParser.NEW_PERMISSIONS[ip];
11602            if (npi.name.equals(perm)
11603                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11604                allowed = true;
11605                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11606                        + pkg.packageName);
11607                break;
11608            }
11609        }
11610        return allowed;
11611    }
11612
11613    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11614            BasePermission bp, PermissionsState origPermissions) {
11615        boolean privilegedPermission = (bp.protectionLevel
11616                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11617        boolean privappPermissionsDisable =
11618                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11619        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11620        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11621        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11622                && !platformPackage && platformPermission) {
11623            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11624                    .getPrivAppPermissions(pkg.packageName);
11625            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11626            if (!whitelisted) {
11627                Slog.w(TAG, "Privileged permission " + perm + " for package "
11628                        + pkg.packageName + " - not in privapp-permissions whitelist");
11629                // Only report violations for apps on system image
11630                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11631                    if (mPrivappPermissionsViolations == null) {
11632                        mPrivappPermissionsViolations = new ArraySet<>();
11633                    }
11634                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11635                }
11636                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11637                    return false;
11638                }
11639            }
11640        }
11641        boolean allowed = (compareSignatures(
11642                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11643                        == PackageManager.SIGNATURE_MATCH)
11644                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11645                        == PackageManager.SIGNATURE_MATCH);
11646        if (!allowed && privilegedPermission) {
11647            if (isSystemApp(pkg)) {
11648                // For updated system applications, a system permission
11649                // is granted only if it had been defined by the original application.
11650                if (pkg.isUpdatedSystemApp()) {
11651                    final PackageSetting sysPs = mSettings
11652                            .getDisabledSystemPkgLPr(pkg.packageName);
11653                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11654                        // If the original was granted this permission, we take
11655                        // that grant decision as read and propagate it to the
11656                        // update.
11657                        if (sysPs.isPrivileged()) {
11658                            allowed = true;
11659                        }
11660                    } else {
11661                        // The system apk may have been updated with an older
11662                        // version of the one on the data partition, but which
11663                        // granted a new system permission that it didn't have
11664                        // before.  In this case we do want to allow the app to
11665                        // now get the new permission if the ancestral apk is
11666                        // privileged to get it.
11667                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11668                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11669                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11670                                    allowed = true;
11671                                    break;
11672                                }
11673                            }
11674                        }
11675                        // Also if a privileged parent package on the system image or any of
11676                        // its children requested a privileged permission, the updated child
11677                        // packages can also get the permission.
11678                        if (pkg.parentPackage != null) {
11679                            final PackageSetting disabledSysParentPs = mSettings
11680                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11681                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11682                                    && disabledSysParentPs.isPrivileged()) {
11683                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11684                                    allowed = true;
11685                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11686                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11687                                    for (int i = 0; i < count; i++) {
11688                                        PackageParser.Package disabledSysChildPkg =
11689                                                disabledSysParentPs.pkg.childPackages.get(i);
11690                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11691                                                perm)) {
11692                                            allowed = true;
11693                                            break;
11694                                        }
11695                                    }
11696                                }
11697                            }
11698                        }
11699                    }
11700                } else {
11701                    allowed = isPrivilegedApp(pkg);
11702                }
11703            }
11704        }
11705        if (!allowed) {
11706            if (!allowed && (bp.protectionLevel
11707                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11708                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11709                // If this was a previously normal/dangerous permission that got moved
11710                // to a system permission as part of the runtime permission redesign, then
11711                // we still want to blindly grant it to old apps.
11712                allowed = true;
11713            }
11714            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11715                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11716                // If this permission is to be granted to the system installer and
11717                // this app is an installer, then it gets the permission.
11718                allowed = true;
11719            }
11720            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11721                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11722                // If this permission is to be granted to the system verifier and
11723                // this app is a verifier, then it gets the permission.
11724                allowed = true;
11725            }
11726            if (!allowed && (bp.protectionLevel
11727                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11728                    && isSystemApp(pkg)) {
11729                // Any pre-installed system app is allowed to get this permission.
11730                allowed = true;
11731            }
11732            if (!allowed && (bp.protectionLevel
11733                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11734                // For development permissions, a development permission
11735                // is granted only if it was already granted.
11736                allowed = origPermissions.hasInstallPermission(perm);
11737            }
11738            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11739                    && pkg.packageName.equals(mSetupWizardPackage)) {
11740                // If this permission is to be granted to the system setup wizard and
11741                // this app is a setup wizard, then it gets the permission.
11742                allowed = true;
11743            }
11744        }
11745        return allowed;
11746    }
11747
11748    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11749        final int permCount = pkg.requestedPermissions.size();
11750        for (int j = 0; j < permCount; j++) {
11751            String requestedPermission = pkg.requestedPermissions.get(j);
11752            if (permission.equals(requestedPermission)) {
11753                return true;
11754            }
11755        }
11756        return false;
11757    }
11758
11759    final class ActivityIntentResolver
11760            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11761        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11762                boolean defaultOnly, int userId) {
11763            if (!sUserManager.exists(userId)) return null;
11764            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11765            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11766        }
11767
11768        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11769                int userId) {
11770            if (!sUserManager.exists(userId)) return null;
11771            mFlags = flags;
11772            return super.queryIntent(intent, resolvedType,
11773                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11774                    userId);
11775        }
11776
11777        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11778                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11779            if (!sUserManager.exists(userId)) return null;
11780            if (packageActivities == null) {
11781                return null;
11782            }
11783            mFlags = flags;
11784            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11785            final int N = packageActivities.size();
11786            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11787                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11788
11789            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11790            for (int i = 0; i < N; ++i) {
11791                intentFilters = packageActivities.get(i).intents;
11792                if (intentFilters != null && intentFilters.size() > 0) {
11793                    PackageParser.ActivityIntentInfo[] array =
11794                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11795                    intentFilters.toArray(array);
11796                    listCut.add(array);
11797                }
11798            }
11799            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11800        }
11801
11802        /**
11803         * Finds a privileged activity that matches the specified activity names.
11804         */
11805        private PackageParser.Activity findMatchingActivity(
11806                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11807            for (PackageParser.Activity sysActivity : activityList) {
11808                if (sysActivity.info.name.equals(activityInfo.name)) {
11809                    return sysActivity;
11810                }
11811                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11812                    return sysActivity;
11813                }
11814                if (sysActivity.info.targetActivity != null) {
11815                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11816                        return sysActivity;
11817                    }
11818                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11819                        return sysActivity;
11820                    }
11821                }
11822            }
11823            return null;
11824        }
11825
11826        public class IterGenerator<E> {
11827            public Iterator<E> generate(ActivityIntentInfo info) {
11828                return null;
11829            }
11830        }
11831
11832        public class ActionIterGenerator extends IterGenerator<String> {
11833            @Override
11834            public Iterator<String> generate(ActivityIntentInfo info) {
11835                return info.actionsIterator();
11836            }
11837        }
11838
11839        public class CategoriesIterGenerator extends IterGenerator<String> {
11840            @Override
11841            public Iterator<String> generate(ActivityIntentInfo info) {
11842                return info.categoriesIterator();
11843            }
11844        }
11845
11846        public class SchemesIterGenerator extends IterGenerator<String> {
11847            @Override
11848            public Iterator<String> generate(ActivityIntentInfo info) {
11849                return info.schemesIterator();
11850            }
11851        }
11852
11853        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11854            @Override
11855            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11856                return info.authoritiesIterator();
11857            }
11858        }
11859
11860        /**
11861         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11862         * MODIFIED. Do not pass in a list that should not be changed.
11863         */
11864        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11865                IterGenerator<T> generator, Iterator<T> searchIterator) {
11866            // loop through the set of actions; every one must be found in the intent filter
11867            while (searchIterator.hasNext()) {
11868                // we must have at least one filter in the list to consider a match
11869                if (intentList.size() == 0) {
11870                    break;
11871                }
11872
11873                final T searchAction = searchIterator.next();
11874
11875                // loop through the set of intent filters
11876                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11877                while (intentIter.hasNext()) {
11878                    final ActivityIntentInfo intentInfo = intentIter.next();
11879                    boolean selectionFound = false;
11880
11881                    // loop through the intent filter's selection criteria; at least one
11882                    // of them must match the searched criteria
11883                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11884                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11885                        final T intentSelection = intentSelectionIter.next();
11886                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11887                            selectionFound = true;
11888                            break;
11889                        }
11890                    }
11891
11892                    // the selection criteria wasn't found in this filter's set; this filter
11893                    // is not a potential match
11894                    if (!selectionFound) {
11895                        intentIter.remove();
11896                    }
11897                }
11898            }
11899        }
11900
11901        private boolean isProtectedAction(ActivityIntentInfo filter) {
11902            final Iterator<String> actionsIter = filter.actionsIterator();
11903            while (actionsIter != null && actionsIter.hasNext()) {
11904                final String filterAction = actionsIter.next();
11905                if (PROTECTED_ACTIONS.contains(filterAction)) {
11906                    return true;
11907                }
11908            }
11909            return false;
11910        }
11911
11912        /**
11913         * Adjusts the priority of the given intent filter according to policy.
11914         * <p>
11915         * <ul>
11916         * <li>The priority for non privileged applications is capped to '0'</li>
11917         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11918         * <li>The priority for unbundled updates to privileged applications is capped to the
11919         *      priority defined on the system partition</li>
11920         * </ul>
11921         * <p>
11922         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11923         * allowed to obtain any priority on any action.
11924         */
11925        private void adjustPriority(
11926                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11927            // nothing to do; priority is fine as-is
11928            if (intent.getPriority() <= 0) {
11929                return;
11930            }
11931
11932            final ActivityInfo activityInfo = intent.activity.info;
11933            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11934
11935            final boolean privilegedApp =
11936                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11937            if (!privilegedApp) {
11938                // non-privileged applications can never define a priority >0
11939                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11940                        + " package: " + applicationInfo.packageName
11941                        + " activity: " + intent.activity.className
11942                        + " origPrio: " + intent.getPriority());
11943                intent.setPriority(0);
11944                return;
11945            }
11946
11947            if (systemActivities == null) {
11948                // the system package is not disabled; we're parsing the system partition
11949                if (isProtectedAction(intent)) {
11950                    if (mDeferProtectedFilters) {
11951                        // We can't deal with these just yet. No component should ever obtain a
11952                        // >0 priority for a protected actions, with ONE exception -- the setup
11953                        // wizard. The setup wizard, however, cannot be known until we're able to
11954                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11955                        // until all intent filters have been processed. Chicken, meet egg.
11956                        // Let the filter temporarily have a high priority and rectify the
11957                        // priorities after all system packages have been scanned.
11958                        mProtectedFilters.add(intent);
11959                        if (DEBUG_FILTERS) {
11960                            Slog.i(TAG, "Protected action; save for later;"
11961                                    + " package: " + applicationInfo.packageName
11962                                    + " activity: " + intent.activity.className
11963                                    + " origPrio: " + intent.getPriority());
11964                        }
11965                        return;
11966                    } else {
11967                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11968                            Slog.i(TAG, "No setup wizard;"
11969                                + " All protected intents capped to priority 0");
11970                        }
11971                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11972                            if (DEBUG_FILTERS) {
11973                                Slog.i(TAG, "Found setup wizard;"
11974                                    + " allow priority " + intent.getPriority() + ";"
11975                                    + " package: " + intent.activity.info.packageName
11976                                    + " activity: " + intent.activity.className
11977                                    + " priority: " + intent.getPriority());
11978                            }
11979                            // setup wizard gets whatever it wants
11980                            return;
11981                        }
11982                        Slog.w(TAG, "Protected action; cap priority to 0;"
11983                                + " package: " + intent.activity.info.packageName
11984                                + " activity: " + intent.activity.className
11985                                + " origPrio: " + intent.getPriority());
11986                        intent.setPriority(0);
11987                        return;
11988                    }
11989                }
11990                // privileged apps on the system image get whatever priority they request
11991                return;
11992            }
11993
11994            // privileged app unbundled update ... try to find the same activity
11995            final PackageParser.Activity foundActivity =
11996                    findMatchingActivity(systemActivities, activityInfo);
11997            if (foundActivity == null) {
11998                // this is a new activity; it cannot obtain >0 priority
11999                if (DEBUG_FILTERS) {
12000                    Slog.i(TAG, "New activity; cap priority to 0;"
12001                            + " package: " + applicationInfo.packageName
12002                            + " activity: " + intent.activity.className
12003                            + " origPrio: " + intent.getPriority());
12004                }
12005                intent.setPriority(0);
12006                return;
12007            }
12008
12009            // found activity, now check for filter equivalence
12010
12011            // a shallow copy is enough; we modify the list, not its contents
12012            final List<ActivityIntentInfo> intentListCopy =
12013                    new ArrayList<>(foundActivity.intents);
12014            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12015
12016            // find matching action subsets
12017            final Iterator<String> actionsIterator = intent.actionsIterator();
12018            if (actionsIterator != null) {
12019                getIntentListSubset(
12020                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12021                if (intentListCopy.size() == 0) {
12022                    // no more intents to match; we're not equivalent
12023                    if (DEBUG_FILTERS) {
12024                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12025                                + " package: " + applicationInfo.packageName
12026                                + " activity: " + intent.activity.className
12027                                + " origPrio: " + intent.getPriority());
12028                    }
12029                    intent.setPriority(0);
12030                    return;
12031                }
12032            }
12033
12034            // find matching category subsets
12035            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12036            if (categoriesIterator != null) {
12037                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12038                        categoriesIterator);
12039                if (intentListCopy.size() == 0) {
12040                    // no more intents to match; we're not equivalent
12041                    if (DEBUG_FILTERS) {
12042                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12043                                + " package: " + applicationInfo.packageName
12044                                + " activity: " + intent.activity.className
12045                                + " origPrio: " + intent.getPriority());
12046                    }
12047                    intent.setPriority(0);
12048                    return;
12049                }
12050            }
12051
12052            // find matching schemes subsets
12053            final Iterator<String> schemesIterator = intent.schemesIterator();
12054            if (schemesIterator != null) {
12055                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12056                        schemesIterator);
12057                if (intentListCopy.size() == 0) {
12058                    // no more intents to match; we're not equivalent
12059                    if (DEBUG_FILTERS) {
12060                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12061                                + " package: " + applicationInfo.packageName
12062                                + " activity: " + intent.activity.className
12063                                + " origPrio: " + intent.getPriority());
12064                    }
12065                    intent.setPriority(0);
12066                    return;
12067                }
12068            }
12069
12070            // find matching authorities subsets
12071            final Iterator<IntentFilter.AuthorityEntry>
12072                    authoritiesIterator = intent.authoritiesIterator();
12073            if (authoritiesIterator != null) {
12074                getIntentListSubset(intentListCopy,
12075                        new AuthoritiesIterGenerator(),
12076                        authoritiesIterator);
12077                if (intentListCopy.size() == 0) {
12078                    // no more intents to match; we're not equivalent
12079                    if (DEBUG_FILTERS) {
12080                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12081                                + " package: " + applicationInfo.packageName
12082                                + " activity: " + intent.activity.className
12083                                + " origPrio: " + intent.getPriority());
12084                    }
12085                    intent.setPriority(0);
12086                    return;
12087                }
12088            }
12089
12090            // we found matching filter(s); app gets the max priority of all intents
12091            int cappedPriority = 0;
12092            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12093                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12094            }
12095            if (intent.getPriority() > cappedPriority) {
12096                if (DEBUG_FILTERS) {
12097                    Slog.i(TAG, "Found matching filter(s);"
12098                            + " cap priority to " + cappedPriority + ";"
12099                            + " package: " + applicationInfo.packageName
12100                            + " activity: " + intent.activity.className
12101                            + " origPrio: " + intent.getPriority());
12102                }
12103                intent.setPriority(cappedPriority);
12104                return;
12105            }
12106            // all this for nothing; the requested priority was <= what was on the system
12107        }
12108
12109        public final void addActivity(PackageParser.Activity a, String type) {
12110            mActivities.put(a.getComponentName(), a);
12111            if (DEBUG_SHOW_INFO)
12112                Log.v(
12113                TAG, "  " + type + " " +
12114                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12115            if (DEBUG_SHOW_INFO)
12116                Log.v(TAG, "    Class=" + a.info.name);
12117            final int NI = a.intents.size();
12118            for (int j=0; j<NI; j++) {
12119                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12120                if ("activity".equals(type)) {
12121                    final PackageSetting ps =
12122                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12123                    final List<PackageParser.Activity> systemActivities =
12124                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12125                    adjustPriority(systemActivities, intent);
12126                }
12127                if (DEBUG_SHOW_INFO) {
12128                    Log.v(TAG, "    IntentFilter:");
12129                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12130                }
12131                if (!intent.debugCheck()) {
12132                    Log.w(TAG, "==> For Activity " + a.info.name);
12133                }
12134                addFilter(intent);
12135            }
12136        }
12137
12138        public final void removeActivity(PackageParser.Activity a, String type) {
12139            mActivities.remove(a.getComponentName());
12140            if (DEBUG_SHOW_INFO) {
12141                Log.v(TAG, "  " + type + " "
12142                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12143                                : a.info.name) + ":");
12144                Log.v(TAG, "    Class=" + a.info.name);
12145            }
12146            final int NI = a.intents.size();
12147            for (int j=0; j<NI; j++) {
12148                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12149                if (DEBUG_SHOW_INFO) {
12150                    Log.v(TAG, "    IntentFilter:");
12151                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12152                }
12153                removeFilter(intent);
12154            }
12155        }
12156
12157        @Override
12158        protected boolean allowFilterResult(
12159                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12160            ActivityInfo filterAi = filter.activity.info;
12161            for (int i=dest.size()-1; i>=0; i--) {
12162                ActivityInfo destAi = dest.get(i).activityInfo;
12163                if (destAi.name == filterAi.name
12164                        && destAi.packageName == filterAi.packageName) {
12165                    return false;
12166                }
12167            }
12168            return true;
12169        }
12170
12171        @Override
12172        protected ActivityIntentInfo[] newArray(int size) {
12173            return new ActivityIntentInfo[size];
12174        }
12175
12176        @Override
12177        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12178            if (!sUserManager.exists(userId)) return true;
12179            PackageParser.Package p = filter.activity.owner;
12180            if (p != null) {
12181                PackageSetting ps = (PackageSetting)p.mExtras;
12182                if (ps != null) {
12183                    // System apps are never considered stopped for purposes of
12184                    // filtering, because there may be no way for the user to
12185                    // actually re-launch them.
12186                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12187                            && ps.getStopped(userId);
12188                }
12189            }
12190            return false;
12191        }
12192
12193        @Override
12194        protected boolean isPackageForFilter(String packageName,
12195                PackageParser.ActivityIntentInfo info) {
12196            return packageName.equals(info.activity.owner.packageName);
12197        }
12198
12199        @Override
12200        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12201                int match, int userId) {
12202            if (!sUserManager.exists(userId)) return null;
12203            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12204                return null;
12205            }
12206            final PackageParser.Activity activity = info.activity;
12207            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12208            if (ps == null) {
12209                return null;
12210            }
12211            final PackageUserState userState = ps.readUserState(userId);
12212            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12213                    userState, userId);
12214            if (ai == null) {
12215                return null;
12216            }
12217            final boolean matchVisibleToInstantApp =
12218                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12219            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12220            // throw out filters that aren't visible to ephemeral apps
12221            if (matchVisibleToInstantApp
12222                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12223                return null;
12224            }
12225            // throw out ephemeral filters if we're not explicitly requesting them
12226            if (!isInstantApp && userState.instantApp) {
12227                return null;
12228            }
12229            // throw out instant app filters if updates are available; will trigger
12230            // instant app resolution
12231            if (userState.instantApp && ps.isUpdateAvailable()) {
12232                return null;
12233            }
12234            final ResolveInfo res = new ResolveInfo();
12235            res.activityInfo = ai;
12236            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12237                res.filter = info;
12238            }
12239            if (info != null) {
12240                res.handleAllWebDataURI = info.handleAllWebDataURI();
12241            }
12242            res.priority = info.getPriority();
12243            res.preferredOrder = activity.owner.mPreferredOrder;
12244            //System.out.println("Result: " + res.activityInfo.className +
12245            //                   " = " + res.priority);
12246            res.match = match;
12247            res.isDefault = info.hasDefault;
12248            res.labelRes = info.labelRes;
12249            res.nonLocalizedLabel = info.nonLocalizedLabel;
12250            if (userNeedsBadging(userId)) {
12251                res.noResourceId = true;
12252            } else {
12253                res.icon = info.icon;
12254            }
12255            res.iconResourceId = info.icon;
12256            res.system = res.activityInfo.applicationInfo.isSystemApp();
12257            res.instantAppAvailable = userState.instantApp;
12258            return res;
12259        }
12260
12261        @Override
12262        protected void sortResults(List<ResolveInfo> results) {
12263            Collections.sort(results, mResolvePrioritySorter);
12264        }
12265
12266        @Override
12267        protected void dumpFilter(PrintWriter out, String prefix,
12268                PackageParser.ActivityIntentInfo filter) {
12269            out.print(prefix); out.print(
12270                    Integer.toHexString(System.identityHashCode(filter.activity)));
12271                    out.print(' ');
12272                    filter.activity.printComponentShortName(out);
12273                    out.print(" filter ");
12274                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12275        }
12276
12277        @Override
12278        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12279            return filter.activity;
12280        }
12281
12282        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12283            PackageParser.Activity activity = (PackageParser.Activity)label;
12284            out.print(prefix); out.print(
12285                    Integer.toHexString(System.identityHashCode(activity)));
12286                    out.print(' ');
12287                    activity.printComponentShortName(out);
12288            if (count > 1) {
12289                out.print(" ("); out.print(count); out.print(" filters)");
12290            }
12291            out.println();
12292        }
12293
12294        // Keys are String (activity class name), values are Activity.
12295        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12296                = new ArrayMap<ComponentName, PackageParser.Activity>();
12297        private int mFlags;
12298    }
12299
12300    private final class ServiceIntentResolver
12301            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12302        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12303                boolean defaultOnly, int userId) {
12304            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12305            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12306        }
12307
12308        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12309                int userId) {
12310            if (!sUserManager.exists(userId)) return null;
12311            mFlags = flags;
12312            return super.queryIntent(intent, resolvedType,
12313                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12314                    userId);
12315        }
12316
12317        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12318                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12319            if (!sUserManager.exists(userId)) return null;
12320            if (packageServices == null) {
12321                return null;
12322            }
12323            mFlags = flags;
12324            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12325            final int N = packageServices.size();
12326            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12327                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12328
12329            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12330            for (int i = 0; i < N; ++i) {
12331                intentFilters = packageServices.get(i).intents;
12332                if (intentFilters != null && intentFilters.size() > 0) {
12333                    PackageParser.ServiceIntentInfo[] array =
12334                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12335                    intentFilters.toArray(array);
12336                    listCut.add(array);
12337                }
12338            }
12339            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12340        }
12341
12342        public final void addService(PackageParser.Service s) {
12343            mServices.put(s.getComponentName(), s);
12344            if (DEBUG_SHOW_INFO) {
12345                Log.v(TAG, "  "
12346                        + (s.info.nonLocalizedLabel != null
12347                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12348                Log.v(TAG, "    Class=" + s.info.name);
12349            }
12350            final int NI = s.intents.size();
12351            int j;
12352            for (j=0; j<NI; j++) {
12353                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12354                if (DEBUG_SHOW_INFO) {
12355                    Log.v(TAG, "    IntentFilter:");
12356                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12357                }
12358                if (!intent.debugCheck()) {
12359                    Log.w(TAG, "==> For Service " + s.info.name);
12360                }
12361                addFilter(intent);
12362            }
12363        }
12364
12365        public final void removeService(PackageParser.Service s) {
12366            mServices.remove(s.getComponentName());
12367            if (DEBUG_SHOW_INFO) {
12368                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12369                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12370                Log.v(TAG, "    Class=" + s.info.name);
12371            }
12372            final int NI = s.intents.size();
12373            int j;
12374            for (j=0; j<NI; j++) {
12375                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12376                if (DEBUG_SHOW_INFO) {
12377                    Log.v(TAG, "    IntentFilter:");
12378                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12379                }
12380                removeFilter(intent);
12381            }
12382        }
12383
12384        @Override
12385        protected boolean allowFilterResult(
12386                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12387            ServiceInfo filterSi = filter.service.info;
12388            for (int i=dest.size()-1; i>=0; i--) {
12389                ServiceInfo destAi = dest.get(i).serviceInfo;
12390                if (destAi.name == filterSi.name
12391                        && destAi.packageName == filterSi.packageName) {
12392                    return false;
12393                }
12394            }
12395            return true;
12396        }
12397
12398        @Override
12399        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12400            return new PackageParser.ServiceIntentInfo[size];
12401        }
12402
12403        @Override
12404        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12405            if (!sUserManager.exists(userId)) return true;
12406            PackageParser.Package p = filter.service.owner;
12407            if (p != null) {
12408                PackageSetting ps = (PackageSetting)p.mExtras;
12409                if (ps != null) {
12410                    // System apps are never considered stopped for purposes of
12411                    // filtering, because there may be no way for the user to
12412                    // actually re-launch them.
12413                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12414                            && ps.getStopped(userId);
12415                }
12416            }
12417            return false;
12418        }
12419
12420        @Override
12421        protected boolean isPackageForFilter(String packageName,
12422                PackageParser.ServiceIntentInfo info) {
12423            return packageName.equals(info.service.owner.packageName);
12424        }
12425
12426        @Override
12427        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12428                int match, int userId) {
12429            if (!sUserManager.exists(userId)) return null;
12430            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12431            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12432                return null;
12433            }
12434            final PackageParser.Service service = info.service;
12435            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12436            if (ps == null) {
12437                return null;
12438            }
12439            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12440                    ps.readUserState(userId), userId);
12441            if (si == null) {
12442                return null;
12443            }
12444            final ResolveInfo res = new ResolveInfo();
12445            res.serviceInfo = si;
12446            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12447                res.filter = filter;
12448            }
12449            res.priority = info.getPriority();
12450            res.preferredOrder = service.owner.mPreferredOrder;
12451            res.match = match;
12452            res.isDefault = info.hasDefault;
12453            res.labelRes = info.labelRes;
12454            res.nonLocalizedLabel = info.nonLocalizedLabel;
12455            res.icon = info.icon;
12456            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12457            return res;
12458        }
12459
12460        @Override
12461        protected void sortResults(List<ResolveInfo> results) {
12462            Collections.sort(results, mResolvePrioritySorter);
12463        }
12464
12465        @Override
12466        protected void dumpFilter(PrintWriter out, String prefix,
12467                PackageParser.ServiceIntentInfo filter) {
12468            out.print(prefix); out.print(
12469                    Integer.toHexString(System.identityHashCode(filter.service)));
12470                    out.print(' ');
12471                    filter.service.printComponentShortName(out);
12472                    out.print(" filter ");
12473                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12474        }
12475
12476        @Override
12477        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12478            return filter.service;
12479        }
12480
12481        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12482            PackageParser.Service service = (PackageParser.Service)label;
12483            out.print(prefix); out.print(
12484                    Integer.toHexString(System.identityHashCode(service)));
12485                    out.print(' ');
12486                    service.printComponentShortName(out);
12487            if (count > 1) {
12488                out.print(" ("); out.print(count); out.print(" filters)");
12489            }
12490            out.println();
12491        }
12492
12493//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12494//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12495//            final List<ResolveInfo> retList = Lists.newArrayList();
12496//            while (i.hasNext()) {
12497//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12498//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12499//                    retList.add(resolveInfo);
12500//                }
12501//            }
12502//            return retList;
12503//        }
12504
12505        // Keys are String (activity class name), values are Activity.
12506        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12507                = new ArrayMap<ComponentName, PackageParser.Service>();
12508        private int mFlags;
12509    }
12510
12511    private final class ProviderIntentResolver
12512            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12513        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12514                boolean defaultOnly, int userId) {
12515            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12516            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12517        }
12518
12519        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12520                int userId) {
12521            if (!sUserManager.exists(userId))
12522                return null;
12523            mFlags = flags;
12524            return super.queryIntent(intent, resolvedType,
12525                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12526                    userId);
12527        }
12528
12529        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12530                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12531            if (!sUserManager.exists(userId))
12532                return null;
12533            if (packageProviders == null) {
12534                return null;
12535            }
12536            mFlags = flags;
12537            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12538            final int N = packageProviders.size();
12539            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12540                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12541
12542            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12543            for (int i = 0; i < N; ++i) {
12544                intentFilters = packageProviders.get(i).intents;
12545                if (intentFilters != null && intentFilters.size() > 0) {
12546                    PackageParser.ProviderIntentInfo[] array =
12547                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12548                    intentFilters.toArray(array);
12549                    listCut.add(array);
12550                }
12551            }
12552            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12553        }
12554
12555        public final void addProvider(PackageParser.Provider p) {
12556            if (mProviders.containsKey(p.getComponentName())) {
12557                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12558                return;
12559            }
12560
12561            mProviders.put(p.getComponentName(), p);
12562            if (DEBUG_SHOW_INFO) {
12563                Log.v(TAG, "  "
12564                        + (p.info.nonLocalizedLabel != null
12565                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12566                Log.v(TAG, "    Class=" + p.info.name);
12567            }
12568            final int NI = p.intents.size();
12569            int j;
12570            for (j = 0; j < NI; j++) {
12571                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12572                if (DEBUG_SHOW_INFO) {
12573                    Log.v(TAG, "    IntentFilter:");
12574                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12575                }
12576                if (!intent.debugCheck()) {
12577                    Log.w(TAG, "==> For Provider " + p.info.name);
12578                }
12579                addFilter(intent);
12580            }
12581        }
12582
12583        public final void removeProvider(PackageParser.Provider p) {
12584            mProviders.remove(p.getComponentName());
12585            if (DEBUG_SHOW_INFO) {
12586                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12587                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12588                Log.v(TAG, "    Class=" + p.info.name);
12589            }
12590            final int NI = p.intents.size();
12591            int j;
12592            for (j = 0; j < NI; j++) {
12593                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12594                if (DEBUG_SHOW_INFO) {
12595                    Log.v(TAG, "    IntentFilter:");
12596                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12597                }
12598                removeFilter(intent);
12599            }
12600        }
12601
12602        @Override
12603        protected boolean allowFilterResult(
12604                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12605            ProviderInfo filterPi = filter.provider.info;
12606            for (int i = dest.size() - 1; i >= 0; i--) {
12607                ProviderInfo destPi = dest.get(i).providerInfo;
12608                if (destPi.name == filterPi.name
12609                        && destPi.packageName == filterPi.packageName) {
12610                    return false;
12611                }
12612            }
12613            return true;
12614        }
12615
12616        @Override
12617        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12618            return new PackageParser.ProviderIntentInfo[size];
12619        }
12620
12621        @Override
12622        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12623            if (!sUserManager.exists(userId))
12624                return true;
12625            PackageParser.Package p = filter.provider.owner;
12626            if (p != null) {
12627                PackageSetting ps = (PackageSetting) p.mExtras;
12628                if (ps != null) {
12629                    // System apps are never considered stopped for purposes of
12630                    // filtering, because there may be no way for the user to
12631                    // actually re-launch them.
12632                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12633                            && ps.getStopped(userId);
12634                }
12635            }
12636            return false;
12637        }
12638
12639        @Override
12640        protected boolean isPackageForFilter(String packageName,
12641                PackageParser.ProviderIntentInfo info) {
12642            return packageName.equals(info.provider.owner.packageName);
12643        }
12644
12645        @Override
12646        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12647                int match, int userId) {
12648            if (!sUserManager.exists(userId))
12649                return null;
12650            final PackageParser.ProviderIntentInfo info = filter;
12651            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12652                return null;
12653            }
12654            final PackageParser.Provider provider = info.provider;
12655            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12656            if (ps == null) {
12657                return null;
12658            }
12659            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12660                    ps.readUserState(userId), userId);
12661            if (pi == null) {
12662                return null;
12663            }
12664            final ResolveInfo res = new ResolveInfo();
12665            res.providerInfo = pi;
12666            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12667                res.filter = filter;
12668            }
12669            res.priority = info.getPriority();
12670            res.preferredOrder = provider.owner.mPreferredOrder;
12671            res.match = match;
12672            res.isDefault = info.hasDefault;
12673            res.labelRes = info.labelRes;
12674            res.nonLocalizedLabel = info.nonLocalizedLabel;
12675            res.icon = info.icon;
12676            res.system = res.providerInfo.applicationInfo.isSystemApp();
12677            return res;
12678        }
12679
12680        @Override
12681        protected void sortResults(List<ResolveInfo> results) {
12682            Collections.sort(results, mResolvePrioritySorter);
12683        }
12684
12685        @Override
12686        protected void dumpFilter(PrintWriter out, String prefix,
12687                PackageParser.ProviderIntentInfo filter) {
12688            out.print(prefix);
12689            out.print(
12690                    Integer.toHexString(System.identityHashCode(filter.provider)));
12691            out.print(' ');
12692            filter.provider.printComponentShortName(out);
12693            out.print(" filter ");
12694            out.println(Integer.toHexString(System.identityHashCode(filter)));
12695        }
12696
12697        @Override
12698        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12699            return filter.provider;
12700        }
12701
12702        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12703            PackageParser.Provider provider = (PackageParser.Provider)label;
12704            out.print(prefix); out.print(
12705                    Integer.toHexString(System.identityHashCode(provider)));
12706                    out.print(' ');
12707                    provider.printComponentShortName(out);
12708            if (count > 1) {
12709                out.print(" ("); out.print(count); out.print(" filters)");
12710            }
12711            out.println();
12712        }
12713
12714        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12715                = new ArrayMap<ComponentName, PackageParser.Provider>();
12716        private int mFlags;
12717    }
12718
12719    static final class EphemeralIntentResolver
12720            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12721        /**
12722         * The result that has the highest defined order. Ordering applies on a
12723         * per-package basis. Mapping is from package name to Pair of order and
12724         * EphemeralResolveInfo.
12725         * <p>
12726         * NOTE: This is implemented as a field variable for convenience and efficiency.
12727         * By having a field variable, we're able to track filter ordering as soon as
12728         * a non-zero order is defined. Otherwise, multiple loops across the result set
12729         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12730         * this needs to be contained entirely within {@link #filterResults}.
12731         */
12732        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12733
12734        @Override
12735        protected AuxiliaryResolveInfo[] newArray(int size) {
12736            return new AuxiliaryResolveInfo[size];
12737        }
12738
12739        @Override
12740        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12741            return true;
12742        }
12743
12744        @Override
12745        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12746                int userId) {
12747            if (!sUserManager.exists(userId)) {
12748                return null;
12749            }
12750            final String packageName = responseObj.resolveInfo.getPackageName();
12751            final Integer order = responseObj.getOrder();
12752            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12753                    mOrderResult.get(packageName);
12754            // ordering is enabled and this item's order isn't high enough
12755            if (lastOrderResult != null && lastOrderResult.first >= order) {
12756                return null;
12757            }
12758            final InstantAppResolveInfo res = responseObj.resolveInfo;
12759            if (order > 0) {
12760                // non-zero order, enable ordering
12761                mOrderResult.put(packageName, new Pair<>(order, res));
12762            }
12763            return responseObj;
12764        }
12765
12766        @Override
12767        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12768            // only do work if ordering is enabled [most of the time it won't be]
12769            if (mOrderResult.size() == 0) {
12770                return;
12771            }
12772            int resultSize = results.size();
12773            for (int i = 0; i < resultSize; i++) {
12774                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12775                final String packageName = info.getPackageName();
12776                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12777                if (savedInfo == null) {
12778                    // package doesn't having ordering
12779                    continue;
12780                }
12781                if (savedInfo.second == info) {
12782                    // circled back to the highest ordered item; remove from order list
12783                    mOrderResult.remove(savedInfo);
12784                    if (mOrderResult.size() == 0) {
12785                        // no more ordered items
12786                        break;
12787                    }
12788                    continue;
12789                }
12790                // item has a worse order, remove it from the result list
12791                results.remove(i);
12792                resultSize--;
12793                i--;
12794            }
12795        }
12796    }
12797
12798    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12799            new Comparator<ResolveInfo>() {
12800        public int compare(ResolveInfo r1, ResolveInfo r2) {
12801            int v1 = r1.priority;
12802            int v2 = r2.priority;
12803            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12804            if (v1 != v2) {
12805                return (v1 > v2) ? -1 : 1;
12806            }
12807            v1 = r1.preferredOrder;
12808            v2 = r2.preferredOrder;
12809            if (v1 != v2) {
12810                return (v1 > v2) ? -1 : 1;
12811            }
12812            if (r1.isDefault != r2.isDefault) {
12813                return r1.isDefault ? -1 : 1;
12814            }
12815            v1 = r1.match;
12816            v2 = r2.match;
12817            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12818            if (v1 != v2) {
12819                return (v1 > v2) ? -1 : 1;
12820            }
12821            if (r1.system != r2.system) {
12822                return r1.system ? -1 : 1;
12823            }
12824            if (r1.activityInfo != null) {
12825                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12826            }
12827            if (r1.serviceInfo != null) {
12828                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12829            }
12830            if (r1.providerInfo != null) {
12831                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12832            }
12833            return 0;
12834        }
12835    };
12836
12837    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12838            new Comparator<ProviderInfo>() {
12839        public int compare(ProviderInfo p1, ProviderInfo p2) {
12840            final int v1 = p1.initOrder;
12841            final int v2 = p2.initOrder;
12842            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12843        }
12844    };
12845
12846    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12847            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12848            final int[] userIds) {
12849        mHandler.post(new Runnable() {
12850            @Override
12851            public void run() {
12852                try {
12853                    final IActivityManager am = ActivityManager.getService();
12854                    if (am == null) return;
12855                    final int[] resolvedUserIds;
12856                    if (userIds == null) {
12857                        resolvedUserIds = am.getRunningUserIds();
12858                    } else {
12859                        resolvedUserIds = userIds;
12860                    }
12861                    for (int id : resolvedUserIds) {
12862                        final Intent intent = new Intent(action,
12863                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12864                        if (extras != null) {
12865                            intent.putExtras(extras);
12866                        }
12867                        if (targetPkg != null) {
12868                            intent.setPackage(targetPkg);
12869                        }
12870                        // Modify the UID when posting to other users
12871                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12872                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12873                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12874                            intent.putExtra(Intent.EXTRA_UID, uid);
12875                        }
12876                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12877                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12878                        if (DEBUG_BROADCASTS) {
12879                            RuntimeException here = new RuntimeException("here");
12880                            here.fillInStackTrace();
12881                            Slog.d(TAG, "Sending to user " + id + ": "
12882                                    + intent.toShortString(false, true, false, false)
12883                                    + " " + intent.getExtras(), here);
12884                        }
12885                        am.broadcastIntent(null, intent, null, finishedReceiver,
12886                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12887                                null, finishedReceiver != null, false, id);
12888                    }
12889                } catch (RemoteException ex) {
12890                }
12891            }
12892        });
12893    }
12894
12895    /**
12896     * Check if the external storage media is available. This is true if there
12897     * is a mounted external storage medium or if the external storage is
12898     * emulated.
12899     */
12900    private boolean isExternalMediaAvailable() {
12901        return mMediaMounted || Environment.isExternalStorageEmulated();
12902    }
12903
12904    @Override
12905    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12906        // writer
12907        synchronized (mPackages) {
12908            if (!isExternalMediaAvailable()) {
12909                // If the external storage is no longer mounted at this point,
12910                // the caller may not have been able to delete all of this
12911                // packages files and can not delete any more.  Bail.
12912                return null;
12913            }
12914            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12915            if (lastPackage != null) {
12916                pkgs.remove(lastPackage);
12917            }
12918            if (pkgs.size() > 0) {
12919                return pkgs.get(0);
12920            }
12921        }
12922        return null;
12923    }
12924
12925    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12926        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12927                userId, andCode ? 1 : 0, packageName);
12928        if (mSystemReady) {
12929            msg.sendToTarget();
12930        } else {
12931            if (mPostSystemReadyMessages == null) {
12932                mPostSystemReadyMessages = new ArrayList<>();
12933            }
12934            mPostSystemReadyMessages.add(msg);
12935        }
12936    }
12937
12938    void startCleaningPackages() {
12939        // reader
12940        if (!isExternalMediaAvailable()) {
12941            return;
12942        }
12943        synchronized (mPackages) {
12944            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12945                return;
12946            }
12947        }
12948        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12949        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12950        IActivityManager am = ActivityManager.getService();
12951        if (am != null) {
12952            try {
12953                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12954                        UserHandle.USER_SYSTEM);
12955            } catch (RemoteException e) {
12956            }
12957        }
12958    }
12959
12960    @Override
12961    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12962            int installFlags, String installerPackageName, int userId) {
12963        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12964
12965        final int callingUid = Binder.getCallingUid();
12966        enforceCrossUserPermission(callingUid, userId,
12967                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12968
12969        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12970            try {
12971                if (observer != null) {
12972                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12973                }
12974            } catch (RemoteException re) {
12975            }
12976            return;
12977        }
12978
12979        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12980            installFlags |= PackageManager.INSTALL_FROM_ADB;
12981
12982        } else {
12983            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12984            // about installerPackageName.
12985
12986            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12987            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12988        }
12989
12990        UserHandle user;
12991        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12992            user = UserHandle.ALL;
12993        } else {
12994            user = new UserHandle(userId);
12995        }
12996
12997        // Only system components can circumvent runtime permissions when installing.
12998        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12999                && mContext.checkCallingOrSelfPermission(Manifest.permission
13000                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13001            throw new SecurityException("You need the "
13002                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13003                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13004        }
13005
13006        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13007                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13008            throw new IllegalArgumentException(
13009                    "New installs into ASEC containers no longer supported");
13010        }
13011
13012        final File originFile = new File(originPath);
13013        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13014
13015        final Message msg = mHandler.obtainMessage(INIT_COPY);
13016        final VerificationInfo verificationInfo = new VerificationInfo(
13017                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13018        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13019                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13020                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13021                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13022        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13023        msg.obj = params;
13024
13025        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13026                System.identityHashCode(msg.obj));
13027        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13028                System.identityHashCode(msg.obj));
13029
13030        mHandler.sendMessage(msg);
13031    }
13032
13033
13034    /**
13035     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13036     * it is acting on behalf on an enterprise or the user).
13037     *
13038     * Note that the ordering of the conditionals in this method is important. The checks we perform
13039     * are as follows, in this order:
13040     *
13041     * 1) If the install is being performed by a system app, we can trust the app to have set the
13042     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13043     *    what it is.
13044     * 2) If the install is being performed by a device or profile owner app, the install reason
13045     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13046     *    set the install reason correctly. If the app targets an older SDK version where install
13047     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13048     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13049     * 3) In all other cases, the install is being performed by a regular app that is neither part
13050     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13051     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13052     *    set to enterprise policy and if so, change it to unknown instead.
13053     */
13054    private int fixUpInstallReason(String installerPackageName, int installerUid,
13055            int installReason) {
13056        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13057                == PERMISSION_GRANTED) {
13058            // If the install is being performed by a system app, we trust that app to have set the
13059            // install reason correctly.
13060            return installReason;
13061        }
13062
13063        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13064            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13065        if (dpm != null) {
13066            ComponentName owner = null;
13067            try {
13068                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13069                if (owner == null) {
13070                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13071                }
13072            } catch (RemoteException e) {
13073            }
13074            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13075                // If the install is being performed by a device or profile owner, the install
13076                // reason should be enterprise policy.
13077                return PackageManager.INSTALL_REASON_POLICY;
13078            }
13079        }
13080
13081        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13082            // If the install is being performed by a regular app (i.e. neither system app nor
13083            // device or profile owner), we have no reason to believe that the app is acting on
13084            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13085            // change it to unknown instead.
13086            return PackageManager.INSTALL_REASON_UNKNOWN;
13087        }
13088
13089        // If the install is being performed by a regular app and the install reason was set to any
13090        // value but enterprise policy, leave the install reason unchanged.
13091        return installReason;
13092    }
13093
13094    void installStage(String packageName, File stagedDir, String stagedCid,
13095            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13096            String installerPackageName, int installerUid, UserHandle user,
13097            Certificate[][] certificates) {
13098        if (DEBUG_EPHEMERAL) {
13099            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13100                Slog.d(TAG, "Ephemeral install of " + packageName);
13101            }
13102        }
13103        final VerificationInfo verificationInfo = new VerificationInfo(
13104                sessionParams.originatingUri, sessionParams.referrerUri,
13105                sessionParams.originatingUid, installerUid);
13106
13107        final OriginInfo origin;
13108        if (stagedDir != null) {
13109            origin = OriginInfo.fromStagedFile(stagedDir);
13110        } else {
13111            origin = OriginInfo.fromStagedContainer(stagedCid);
13112        }
13113
13114        final Message msg = mHandler.obtainMessage(INIT_COPY);
13115        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13116                sessionParams.installReason);
13117        final InstallParams params = new InstallParams(origin, null, observer,
13118                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13119                verificationInfo, user, sessionParams.abiOverride,
13120                sessionParams.grantedRuntimePermissions, certificates, installReason);
13121        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13122        msg.obj = params;
13123
13124        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13125                System.identityHashCode(msg.obj));
13126        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13127                System.identityHashCode(msg.obj));
13128
13129        mHandler.sendMessage(msg);
13130    }
13131
13132    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13133            int userId) {
13134        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13135        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13136    }
13137
13138    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13139            int appId, int... userIds) {
13140        if (ArrayUtils.isEmpty(userIds)) {
13141            return;
13142        }
13143        Bundle extras = new Bundle(1);
13144        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13145        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13146
13147        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13148                packageName, extras, 0, null, null, userIds);
13149        if (isSystem) {
13150            mHandler.post(() -> {
13151                        for (int userId : userIds) {
13152                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13153                        }
13154                    }
13155            );
13156        }
13157    }
13158
13159    /**
13160     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13161     * automatically without needing an explicit launch.
13162     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13163     */
13164    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13165        // If user is not running, the app didn't miss any broadcast
13166        if (!mUserManagerInternal.isUserRunning(userId)) {
13167            return;
13168        }
13169        final IActivityManager am = ActivityManager.getService();
13170        try {
13171            // Deliver LOCKED_BOOT_COMPLETED first
13172            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13173                    .setPackage(packageName);
13174            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13175            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13176                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13177
13178            // Deliver BOOT_COMPLETED only if user is unlocked
13179            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13180                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13181                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13182                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13183            }
13184        } catch (RemoteException e) {
13185            throw e.rethrowFromSystemServer();
13186        }
13187    }
13188
13189    @Override
13190    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13191            int userId) {
13192        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13193        PackageSetting pkgSetting;
13194        final int uid = Binder.getCallingUid();
13195        enforceCrossUserPermission(uid, userId,
13196                true /* requireFullPermission */, true /* checkShell */,
13197                "setApplicationHiddenSetting for user " + userId);
13198
13199        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13200            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13201            return false;
13202        }
13203
13204        long callingId = Binder.clearCallingIdentity();
13205        try {
13206            boolean sendAdded = false;
13207            boolean sendRemoved = false;
13208            // writer
13209            synchronized (mPackages) {
13210                pkgSetting = mSettings.mPackages.get(packageName);
13211                if (pkgSetting == null) {
13212                    return false;
13213                }
13214                // Do not allow "android" is being disabled
13215                if ("android".equals(packageName)) {
13216                    Slog.w(TAG, "Cannot hide package: android");
13217                    return false;
13218                }
13219                // Cannot hide static shared libs as they are considered
13220                // a part of the using app (emulating static linking). Also
13221                // static libs are installed always on internal storage.
13222                PackageParser.Package pkg = mPackages.get(packageName);
13223                if (pkg != null && pkg.staticSharedLibName != null) {
13224                    Slog.w(TAG, "Cannot hide package: " + packageName
13225                            + " providing static shared library: "
13226                            + pkg.staticSharedLibName);
13227                    return false;
13228                }
13229                // Only allow protected packages to hide themselves.
13230                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13231                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13232                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13233                    return false;
13234                }
13235
13236                if (pkgSetting.getHidden(userId) != hidden) {
13237                    pkgSetting.setHidden(hidden, userId);
13238                    mSettings.writePackageRestrictionsLPr(userId);
13239                    if (hidden) {
13240                        sendRemoved = true;
13241                    } else {
13242                        sendAdded = true;
13243                    }
13244                }
13245            }
13246            if (sendAdded) {
13247                sendPackageAddedForUser(packageName, pkgSetting, userId);
13248                return true;
13249            }
13250            if (sendRemoved) {
13251                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13252                        "hiding pkg");
13253                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13254                return true;
13255            }
13256        } finally {
13257            Binder.restoreCallingIdentity(callingId);
13258        }
13259        return false;
13260    }
13261
13262    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13263            int userId) {
13264        final PackageRemovedInfo info = new PackageRemovedInfo();
13265        info.removedPackage = packageName;
13266        info.removedUsers = new int[] {userId};
13267        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13268        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13269    }
13270
13271    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13272        if (pkgList.length > 0) {
13273            Bundle extras = new Bundle(1);
13274            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13275
13276            sendPackageBroadcast(
13277                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13278                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13279                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13280                    new int[] {userId});
13281        }
13282    }
13283
13284    /**
13285     * Returns true if application is not found or there was an error. Otherwise it returns
13286     * the hidden state of the package for the given user.
13287     */
13288    @Override
13289    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13290        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13291        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13292                true /* requireFullPermission */, false /* checkShell */,
13293                "getApplicationHidden for user " + userId);
13294        PackageSetting pkgSetting;
13295        long callingId = Binder.clearCallingIdentity();
13296        try {
13297            // writer
13298            synchronized (mPackages) {
13299                pkgSetting = mSettings.mPackages.get(packageName);
13300                if (pkgSetting == null) {
13301                    return true;
13302                }
13303                return pkgSetting.getHidden(userId);
13304            }
13305        } finally {
13306            Binder.restoreCallingIdentity(callingId);
13307        }
13308    }
13309
13310    /**
13311     * @hide
13312     */
13313    @Override
13314    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13315            int installReason) {
13316        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13317                null);
13318        PackageSetting pkgSetting;
13319        final int uid = Binder.getCallingUid();
13320        enforceCrossUserPermission(uid, userId,
13321                true /* requireFullPermission */, true /* checkShell */,
13322                "installExistingPackage for user " + userId);
13323        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13324            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13325        }
13326
13327        long callingId = Binder.clearCallingIdentity();
13328        try {
13329            boolean installed = false;
13330            final boolean instantApp =
13331                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13332            final boolean fullApp =
13333                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13334
13335            // writer
13336            synchronized (mPackages) {
13337                pkgSetting = mSettings.mPackages.get(packageName);
13338                if (pkgSetting == null) {
13339                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13340                }
13341                if (!pkgSetting.getInstalled(userId)) {
13342                    pkgSetting.setInstalled(true, userId);
13343                    pkgSetting.setHidden(false, userId);
13344                    pkgSetting.setInstallReason(installReason, userId);
13345                    mSettings.writePackageRestrictionsLPr(userId);
13346                    mSettings.writeKernelMappingLPr(pkgSetting);
13347                    installed = true;
13348                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13349                    // upgrade app from instant to full; we don't allow app downgrade
13350                    installed = true;
13351                }
13352                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13353            }
13354
13355            if (installed) {
13356                if (pkgSetting.pkg != null) {
13357                    synchronized (mInstallLock) {
13358                        // We don't need to freeze for a brand new install
13359                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13360                    }
13361                }
13362                sendPackageAddedForUser(packageName, pkgSetting, userId);
13363                synchronized (mPackages) {
13364                    updateSequenceNumberLP(packageName, new int[]{ userId });
13365                }
13366            }
13367        } finally {
13368            Binder.restoreCallingIdentity(callingId);
13369        }
13370
13371        return PackageManager.INSTALL_SUCCEEDED;
13372    }
13373
13374    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13375            boolean instantApp, boolean fullApp) {
13376        // no state specified; do nothing
13377        if (!instantApp && !fullApp) {
13378            return;
13379        }
13380        if (userId != UserHandle.USER_ALL) {
13381            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13382                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13383            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13384                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13385            }
13386        } else {
13387            for (int currentUserId : sUserManager.getUserIds()) {
13388                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13389                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13390                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13391                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13392                }
13393            }
13394        }
13395    }
13396
13397    boolean isUserRestricted(int userId, String restrictionKey) {
13398        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13399        if (restrictions.getBoolean(restrictionKey, false)) {
13400            Log.w(TAG, "User is restricted: " + restrictionKey);
13401            return true;
13402        }
13403        return false;
13404    }
13405
13406    @Override
13407    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13408            int userId) {
13409        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13410        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13411                true /* requireFullPermission */, true /* checkShell */,
13412                "setPackagesSuspended for user " + userId);
13413
13414        if (ArrayUtils.isEmpty(packageNames)) {
13415            return packageNames;
13416        }
13417
13418        // List of package names for whom the suspended state has changed.
13419        List<String> changedPackages = new ArrayList<>(packageNames.length);
13420        // List of package names for whom the suspended state is not set as requested in this
13421        // method.
13422        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13423        long callingId = Binder.clearCallingIdentity();
13424        try {
13425            for (int i = 0; i < packageNames.length; i++) {
13426                String packageName = packageNames[i];
13427                boolean changed = false;
13428                final int appId;
13429                synchronized (mPackages) {
13430                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13431                    if (pkgSetting == null) {
13432                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13433                                + "\". Skipping suspending/un-suspending.");
13434                        unactionedPackages.add(packageName);
13435                        continue;
13436                    }
13437                    appId = pkgSetting.appId;
13438                    if (pkgSetting.getSuspended(userId) != suspended) {
13439                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13440                            unactionedPackages.add(packageName);
13441                            continue;
13442                        }
13443                        pkgSetting.setSuspended(suspended, userId);
13444                        mSettings.writePackageRestrictionsLPr(userId);
13445                        changed = true;
13446                        changedPackages.add(packageName);
13447                    }
13448                }
13449
13450                if (changed && suspended) {
13451                    killApplication(packageName, UserHandle.getUid(userId, appId),
13452                            "suspending package");
13453                }
13454            }
13455        } finally {
13456            Binder.restoreCallingIdentity(callingId);
13457        }
13458
13459        if (!changedPackages.isEmpty()) {
13460            sendPackagesSuspendedForUser(changedPackages.toArray(
13461                    new String[changedPackages.size()]), userId, suspended);
13462        }
13463
13464        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13465    }
13466
13467    @Override
13468    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13469        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13470                true /* requireFullPermission */, false /* checkShell */,
13471                "isPackageSuspendedForUser for user " + userId);
13472        synchronized (mPackages) {
13473            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13474            if (pkgSetting == null) {
13475                throw new IllegalArgumentException("Unknown target package: " + packageName);
13476            }
13477            return pkgSetting.getSuspended(userId);
13478        }
13479    }
13480
13481    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13482        if (isPackageDeviceAdmin(packageName, userId)) {
13483            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13484                    + "\": has an active device admin");
13485            return false;
13486        }
13487
13488        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13489        if (packageName.equals(activeLauncherPackageName)) {
13490            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13491                    + "\": contains the active launcher");
13492            return false;
13493        }
13494
13495        if (packageName.equals(mRequiredInstallerPackage)) {
13496            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13497                    + "\": required for package installation");
13498            return false;
13499        }
13500
13501        if (packageName.equals(mRequiredUninstallerPackage)) {
13502            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13503                    + "\": required for package uninstallation");
13504            return false;
13505        }
13506
13507        if (packageName.equals(mRequiredVerifierPackage)) {
13508            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13509                    + "\": required for package verification");
13510            return false;
13511        }
13512
13513        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13514            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13515                    + "\": is the default dialer");
13516            return false;
13517        }
13518
13519        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13520            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13521                    + "\": protected package");
13522            return false;
13523        }
13524
13525        // Cannot suspend static shared libs as they are considered
13526        // a part of the using app (emulating static linking). Also
13527        // static libs are installed always on internal storage.
13528        PackageParser.Package pkg = mPackages.get(packageName);
13529        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13530            Slog.w(TAG, "Cannot suspend package: " + packageName
13531                    + " providing static shared library: "
13532                    + pkg.staticSharedLibName);
13533            return false;
13534        }
13535
13536        return true;
13537    }
13538
13539    private String getActiveLauncherPackageName(int userId) {
13540        Intent intent = new Intent(Intent.ACTION_MAIN);
13541        intent.addCategory(Intent.CATEGORY_HOME);
13542        ResolveInfo resolveInfo = resolveIntent(
13543                intent,
13544                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13545                PackageManager.MATCH_DEFAULT_ONLY,
13546                userId);
13547
13548        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13549    }
13550
13551    private String getDefaultDialerPackageName(int userId) {
13552        synchronized (mPackages) {
13553            return mSettings.getDefaultDialerPackageNameLPw(userId);
13554        }
13555    }
13556
13557    @Override
13558    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13559        mContext.enforceCallingOrSelfPermission(
13560                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13561                "Only package verification agents can verify applications");
13562
13563        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13564        final PackageVerificationResponse response = new PackageVerificationResponse(
13565                verificationCode, Binder.getCallingUid());
13566        msg.arg1 = id;
13567        msg.obj = response;
13568        mHandler.sendMessage(msg);
13569    }
13570
13571    @Override
13572    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13573            long millisecondsToDelay) {
13574        mContext.enforceCallingOrSelfPermission(
13575                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13576                "Only package verification agents can extend verification timeouts");
13577
13578        final PackageVerificationState state = mPendingVerification.get(id);
13579        final PackageVerificationResponse response = new PackageVerificationResponse(
13580                verificationCodeAtTimeout, Binder.getCallingUid());
13581
13582        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13583            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13584        }
13585        if (millisecondsToDelay < 0) {
13586            millisecondsToDelay = 0;
13587        }
13588        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13589                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13590            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13591        }
13592
13593        if ((state != null) && !state.timeoutExtended()) {
13594            state.extendTimeout();
13595
13596            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13597            msg.arg1 = id;
13598            msg.obj = response;
13599            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13600        }
13601    }
13602
13603    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13604            int verificationCode, UserHandle user) {
13605        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13606        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13607        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13608        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13609        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13610
13611        mContext.sendBroadcastAsUser(intent, user,
13612                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13613    }
13614
13615    private ComponentName matchComponentForVerifier(String packageName,
13616            List<ResolveInfo> receivers) {
13617        ActivityInfo targetReceiver = null;
13618
13619        final int NR = receivers.size();
13620        for (int i = 0; i < NR; i++) {
13621            final ResolveInfo info = receivers.get(i);
13622            if (info.activityInfo == null) {
13623                continue;
13624            }
13625
13626            if (packageName.equals(info.activityInfo.packageName)) {
13627                targetReceiver = info.activityInfo;
13628                break;
13629            }
13630        }
13631
13632        if (targetReceiver == null) {
13633            return null;
13634        }
13635
13636        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13637    }
13638
13639    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13640            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13641        if (pkgInfo.verifiers.length == 0) {
13642            return null;
13643        }
13644
13645        final int N = pkgInfo.verifiers.length;
13646        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13647        for (int i = 0; i < N; i++) {
13648            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13649
13650            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13651                    receivers);
13652            if (comp == null) {
13653                continue;
13654            }
13655
13656            final int verifierUid = getUidForVerifier(verifierInfo);
13657            if (verifierUid == -1) {
13658                continue;
13659            }
13660
13661            if (DEBUG_VERIFY) {
13662                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13663                        + " with the correct signature");
13664            }
13665            sufficientVerifiers.add(comp);
13666            verificationState.addSufficientVerifier(verifierUid);
13667        }
13668
13669        return sufficientVerifiers;
13670    }
13671
13672    private int getUidForVerifier(VerifierInfo verifierInfo) {
13673        synchronized (mPackages) {
13674            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13675            if (pkg == null) {
13676                return -1;
13677            } else if (pkg.mSignatures.length != 1) {
13678                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13679                        + " has more than one signature; ignoring");
13680                return -1;
13681            }
13682
13683            /*
13684             * If the public key of the package's signature does not match
13685             * our expected public key, then this is a different package and
13686             * we should skip.
13687             */
13688
13689            final byte[] expectedPublicKey;
13690            try {
13691                final Signature verifierSig = pkg.mSignatures[0];
13692                final PublicKey publicKey = verifierSig.getPublicKey();
13693                expectedPublicKey = publicKey.getEncoded();
13694            } catch (CertificateException e) {
13695                return -1;
13696            }
13697
13698            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13699
13700            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13701                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13702                        + " does not have the expected public key; ignoring");
13703                return -1;
13704            }
13705
13706            return pkg.applicationInfo.uid;
13707        }
13708    }
13709
13710    @Override
13711    public void finishPackageInstall(int token, boolean didLaunch) {
13712        enforceSystemOrRoot("Only the system is allowed to finish installs");
13713
13714        if (DEBUG_INSTALL) {
13715            Slog.v(TAG, "BM finishing package install for " + token);
13716        }
13717        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13718
13719        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13720        mHandler.sendMessage(msg);
13721    }
13722
13723    /**
13724     * Get the verification agent timeout.
13725     *
13726     * @return verification timeout in milliseconds
13727     */
13728    private long getVerificationTimeout() {
13729        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13730                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13731                DEFAULT_VERIFICATION_TIMEOUT);
13732    }
13733
13734    /**
13735     * Get the default verification agent response code.
13736     *
13737     * @return default verification response code
13738     */
13739    private int getDefaultVerificationResponse() {
13740        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13741                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13742                DEFAULT_VERIFICATION_RESPONSE);
13743    }
13744
13745    /**
13746     * Check whether or not package verification has been enabled.
13747     *
13748     * @return true if verification should be performed
13749     */
13750    private boolean isVerificationEnabled(int userId, int installFlags) {
13751        if (!DEFAULT_VERIFY_ENABLE) {
13752            return false;
13753        }
13754
13755        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13756
13757        // Check if installing from ADB
13758        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13759            // Do not run verification in a test harness environment
13760            if (ActivityManager.isRunningInTestHarness()) {
13761                return false;
13762            }
13763            if (ensureVerifyAppsEnabled) {
13764                return true;
13765            }
13766            // Check if the developer does not want package verification for ADB installs
13767            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13768                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13769                return false;
13770            }
13771        }
13772
13773        if (ensureVerifyAppsEnabled) {
13774            return true;
13775        }
13776
13777        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13778                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13779    }
13780
13781    @Override
13782    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13783            throws RemoteException {
13784        mContext.enforceCallingOrSelfPermission(
13785                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13786                "Only intentfilter verification agents can verify applications");
13787
13788        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13789        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13790                Binder.getCallingUid(), verificationCode, failedDomains);
13791        msg.arg1 = id;
13792        msg.obj = response;
13793        mHandler.sendMessage(msg);
13794    }
13795
13796    @Override
13797    public int getIntentVerificationStatus(String packageName, int userId) {
13798        synchronized (mPackages) {
13799            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13800        }
13801    }
13802
13803    @Override
13804    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13805        mContext.enforceCallingOrSelfPermission(
13806                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13807
13808        boolean result = false;
13809        synchronized (mPackages) {
13810            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13811        }
13812        if (result) {
13813            scheduleWritePackageRestrictionsLocked(userId);
13814        }
13815        return result;
13816    }
13817
13818    @Override
13819    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13820            String packageName) {
13821        synchronized (mPackages) {
13822            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13823        }
13824    }
13825
13826    @Override
13827    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13828        if (TextUtils.isEmpty(packageName)) {
13829            return ParceledListSlice.emptyList();
13830        }
13831        synchronized (mPackages) {
13832            PackageParser.Package pkg = mPackages.get(packageName);
13833            if (pkg == null || pkg.activities == null) {
13834                return ParceledListSlice.emptyList();
13835            }
13836            final int count = pkg.activities.size();
13837            ArrayList<IntentFilter> result = new ArrayList<>();
13838            for (int n=0; n<count; n++) {
13839                PackageParser.Activity activity = pkg.activities.get(n);
13840                if (activity.intents != null && activity.intents.size() > 0) {
13841                    result.addAll(activity.intents);
13842                }
13843            }
13844            return new ParceledListSlice<>(result);
13845        }
13846    }
13847
13848    @Override
13849    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13850        mContext.enforceCallingOrSelfPermission(
13851                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13852
13853        synchronized (mPackages) {
13854            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13855            if (packageName != null) {
13856                result |= updateIntentVerificationStatus(packageName,
13857                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13858                        userId);
13859                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13860                        packageName, userId);
13861            }
13862            return result;
13863        }
13864    }
13865
13866    @Override
13867    public String getDefaultBrowserPackageName(int userId) {
13868        synchronized (mPackages) {
13869            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13870        }
13871    }
13872
13873    /**
13874     * Get the "allow unknown sources" setting.
13875     *
13876     * @return the current "allow unknown sources" setting
13877     */
13878    private int getUnknownSourcesSettings() {
13879        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13880                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13881                -1);
13882    }
13883
13884    @Override
13885    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13886        final int uid = Binder.getCallingUid();
13887        // writer
13888        synchronized (mPackages) {
13889            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13890            if (targetPackageSetting == null) {
13891                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13892            }
13893
13894            PackageSetting installerPackageSetting;
13895            if (installerPackageName != null) {
13896                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13897                if (installerPackageSetting == null) {
13898                    throw new IllegalArgumentException("Unknown installer package: "
13899                            + installerPackageName);
13900                }
13901            } else {
13902                installerPackageSetting = null;
13903            }
13904
13905            Signature[] callerSignature;
13906            Object obj = mSettings.getUserIdLPr(uid);
13907            if (obj != null) {
13908                if (obj instanceof SharedUserSetting) {
13909                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13910                } else if (obj instanceof PackageSetting) {
13911                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13912                } else {
13913                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13914                }
13915            } else {
13916                throw new SecurityException("Unknown calling UID: " + uid);
13917            }
13918
13919            // Verify: can't set installerPackageName to a package that is
13920            // not signed with the same cert as the caller.
13921            if (installerPackageSetting != null) {
13922                if (compareSignatures(callerSignature,
13923                        installerPackageSetting.signatures.mSignatures)
13924                        != PackageManager.SIGNATURE_MATCH) {
13925                    throw new SecurityException(
13926                            "Caller does not have same cert as new installer package "
13927                            + installerPackageName);
13928                }
13929            }
13930
13931            // Verify: if target already has an installer package, it must
13932            // be signed with the same cert as the caller.
13933            if (targetPackageSetting.installerPackageName != null) {
13934                PackageSetting setting = mSettings.mPackages.get(
13935                        targetPackageSetting.installerPackageName);
13936                // If the currently set package isn't valid, then it's always
13937                // okay to change it.
13938                if (setting != null) {
13939                    if (compareSignatures(callerSignature,
13940                            setting.signatures.mSignatures)
13941                            != PackageManager.SIGNATURE_MATCH) {
13942                        throw new SecurityException(
13943                                "Caller does not have same cert as old installer package "
13944                                + targetPackageSetting.installerPackageName);
13945                    }
13946                }
13947            }
13948
13949            // Okay!
13950            targetPackageSetting.installerPackageName = installerPackageName;
13951            if (installerPackageName != null) {
13952                mSettings.mInstallerPackages.add(installerPackageName);
13953            }
13954            scheduleWriteSettingsLocked();
13955        }
13956    }
13957
13958    @Override
13959    public void setApplicationCategoryHint(String packageName, int categoryHint,
13960            String callerPackageName) {
13961        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13962                callerPackageName);
13963        synchronized (mPackages) {
13964            PackageSetting ps = mSettings.mPackages.get(packageName);
13965            if (ps == null) {
13966                throw new IllegalArgumentException("Unknown target package " + packageName);
13967            }
13968
13969            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13970                throw new IllegalArgumentException("Calling package " + callerPackageName
13971                        + " is not installer for " + packageName);
13972            }
13973
13974            if (ps.categoryHint != categoryHint) {
13975                ps.categoryHint = categoryHint;
13976                scheduleWriteSettingsLocked();
13977            }
13978        }
13979    }
13980
13981    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13982        // Queue up an async operation since the package installation may take a little while.
13983        mHandler.post(new Runnable() {
13984            public void run() {
13985                mHandler.removeCallbacks(this);
13986                 // Result object to be returned
13987                PackageInstalledInfo res = new PackageInstalledInfo();
13988                res.setReturnCode(currentStatus);
13989                res.uid = -1;
13990                res.pkg = null;
13991                res.removedInfo = null;
13992                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13993                    args.doPreInstall(res.returnCode);
13994                    synchronized (mInstallLock) {
13995                        installPackageTracedLI(args, res);
13996                    }
13997                    args.doPostInstall(res.returnCode, res.uid);
13998                }
13999
14000                // A restore should be performed at this point if (a) the install
14001                // succeeded, (b) the operation is not an update, and (c) the new
14002                // package has not opted out of backup participation.
14003                final boolean update = res.removedInfo != null
14004                        && res.removedInfo.removedPackage != null;
14005                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14006                boolean doRestore = !update
14007                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14008
14009                // Set up the post-install work request bookkeeping.  This will be used
14010                // and cleaned up by the post-install event handling regardless of whether
14011                // there's a restore pass performed.  Token values are >= 1.
14012                int token;
14013                if (mNextInstallToken < 0) mNextInstallToken = 1;
14014                token = mNextInstallToken++;
14015
14016                PostInstallData data = new PostInstallData(args, res);
14017                mRunningInstalls.put(token, data);
14018                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14019
14020                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14021                    // Pass responsibility to the Backup Manager.  It will perform a
14022                    // restore if appropriate, then pass responsibility back to the
14023                    // Package Manager to run the post-install observer callbacks
14024                    // and broadcasts.
14025                    IBackupManager bm = IBackupManager.Stub.asInterface(
14026                            ServiceManager.getService(Context.BACKUP_SERVICE));
14027                    if (bm != null) {
14028                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14029                                + " to BM for possible restore");
14030                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14031                        try {
14032                            // TODO: http://b/22388012
14033                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14034                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14035                            } else {
14036                                doRestore = false;
14037                            }
14038                        } catch (RemoteException e) {
14039                            // can't happen; the backup manager is local
14040                        } catch (Exception e) {
14041                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14042                            doRestore = false;
14043                        }
14044                    } else {
14045                        Slog.e(TAG, "Backup Manager not found!");
14046                        doRestore = false;
14047                    }
14048                }
14049
14050                if (!doRestore) {
14051                    // No restore possible, or the Backup Manager was mysteriously not
14052                    // available -- just fire the post-install work request directly.
14053                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14054
14055                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14056
14057                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14058                    mHandler.sendMessage(msg);
14059                }
14060            }
14061        });
14062    }
14063
14064    /**
14065     * Callback from PackageSettings whenever an app is first transitioned out of the
14066     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14067     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14068     * here whether the app is the target of an ongoing install, and only send the
14069     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14070     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14071     * handling.
14072     */
14073    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14074        // Serialize this with the rest of the install-process message chain.  In the
14075        // restore-at-install case, this Runnable will necessarily run before the
14076        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14077        // are coherent.  In the non-restore case, the app has already completed install
14078        // and been launched through some other means, so it is not in a problematic
14079        // state for observers to see the FIRST_LAUNCH signal.
14080        mHandler.post(new Runnable() {
14081            @Override
14082            public void run() {
14083                for (int i = 0; i < mRunningInstalls.size(); i++) {
14084                    final PostInstallData data = mRunningInstalls.valueAt(i);
14085                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14086                        continue;
14087                    }
14088                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14089                        // right package; but is it for the right user?
14090                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14091                            if (userId == data.res.newUsers[uIndex]) {
14092                                if (DEBUG_BACKUP) {
14093                                    Slog.i(TAG, "Package " + pkgName
14094                                            + " being restored so deferring FIRST_LAUNCH");
14095                                }
14096                                return;
14097                            }
14098                        }
14099                    }
14100                }
14101                // didn't find it, so not being restored
14102                if (DEBUG_BACKUP) {
14103                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14104                }
14105                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14106            }
14107        });
14108    }
14109
14110    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14111        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14112                installerPkg, null, userIds);
14113    }
14114
14115    private abstract class HandlerParams {
14116        private static final int MAX_RETRIES = 4;
14117
14118        /**
14119         * Number of times startCopy() has been attempted and had a non-fatal
14120         * error.
14121         */
14122        private int mRetries = 0;
14123
14124        /** User handle for the user requesting the information or installation. */
14125        private final UserHandle mUser;
14126        String traceMethod;
14127        int traceCookie;
14128
14129        HandlerParams(UserHandle user) {
14130            mUser = user;
14131        }
14132
14133        UserHandle getUser() {
14134            return mUser;
14135        }
14136
14137        HandlerParams setTraceMethod(String traceMethod) {
14138            this.traceMethod = traceMethod;
14139            return this;
14140        }
14141
14142        HandlerParams setTraceCookie(int traceCookie) {
14143            this.traceCookie = traceCookie;
14144            return this;
14145        }
14146
14147        final boolean startCopy() {
14148            boolean res;
14149            try {
14150                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14151
14152                if (++mRetries > MAX_RETRIES) {
14153                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14154                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14155                    handleServiceError();
14156                    return false;
14157                } else {
14158                    handleStartCopy();
14159                    res = true;
14160                }
14161            } catch (RemoteException e) {
14162                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14163                mHandler.sendEmptyMessage(MCS_RECONNECT);
14164                res = false;
14165            }
14166            handleReturnCode();
14167            return res;
14168        }
14169
14170        final void serviceError() {
14171            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14172            handleServiceError();
14173            handleReturnCode();
14174        }
14175
14176        abstract void handleStartCopy() throws RemoteException;
14177        abstract void handleServiceError();
14178        abstract void handleReturnCode();
14179    }
14180
14181    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14182        for (File path : paths) {
14183            try {
14184                mcs.clearDirectory(path.getAbsolutePath());
14185            } catch (RemoteException e) {
14186            }
14187        }
14188    }
14189
14190    static class OriginInfo {
14191        /**
14192         * Location where install is coming from, before it has been
14193         * copied/renamed into place. This could be a single monolithic APK
14194         * file, or a cluster directory. This location may be untrusted.
14195         */
14196        final File file;
14197        final String cid;
14198
14199        /**
14200         * Flag indicating that {@link #file} or {@link #cid} has already been
14201         * staged, meaning downstream users don't need to defensively copy the
14202         * contents.
14203         */
14204        final boolean staged;
14205
14206        /**
14207         * Flag indicating that {@link #file} or {@link #cid} is an already
14208         * installed app that is being moved.
14209         */
14210        final boolean existing;
14211
14212        final String resolvedPath;
14213        final File resolvedFile;
14214
14215        static OriginInfo fromNothing() {
14216            return new OriginInfo(null, null, false, false);
14217        }
14218
14219        static OriginInfo fromUntrustedFile(File file) {
14220            return new OriginInfo(file, null, false, false);
14221        }
14222
14223        static OriginInfo fromExistingFile(File file) {
14224            return new OriginInfo(file, null, false, true);
14225        }
14226
14227        static OriginInfo fromStagedFile(File file) {
14228            return new OriginInfo(file, null, true, false);
14229        }
14230
14231        static OriginInfo fromStagedContainer(String cid) {
14232            return new OriginInfo(null, cid, true, false);
14233        }
14234
14235        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14236            this.file = file;
14237            this.cid = cid;
14238            this.staged = staged;
14239            this.existing = existing;
14240
14241            if (cid != null) {
14242                resolvedPath = PackageHelper.getSdDir(cid);
14243                resolvedFile = new File(resolvedPath);
14244            } else if (file != null) {
14245                resolvedPath = file.getAbsolutePath();
14246                resolvedFile = file;
14247            } else {
14248                resolvedPath = null;
14249                resolvedFile = null;
14250            }
14251        }
14252    }
14253
14254    static class MoveInfo {
14255        final int moveId;
14256        final String fromUuid;
14257        final String toUuid;
14258        final String packageName;
14259        final String dataAppName;
14260        final int appId;
14261        final String seinfo;
14262        final int targetSdkVersion;
14263
14264        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14265                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14266            this.moveId = moveId;
14267            this.fromUuid = fromUuid;
14268            this.toUuid = toUuid;
14269            this.packageName = packageName;
14270            this.dataAppName = dataAppName;
14271            this.appId = appId;
14272            this.seinfo = seinfo;
14273            this.targetSdkVersion = targetSdkVersion;
14274        }
14275    }
14276
14277    static class VerificationInfo {
14278        /** A constant used to indicate that a uid value is not present. */
14279        public static final int NO_UID = -1;
14280
14281        /** URI referencing where the package was downloaded from. */
14282        final Uri originatingUri;
14283
14284        /** HTTP referrer URI associated with the originatingURI. */
14285        final Uri referrer;
14286
14287        /** UID of the application that the install request originated from. */
14288        final int originatingUid;
14289
14290        /** UID of application requesting the install */
14291        final int installerUid;
14292
14293        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14294            this.originatingUri = originatingUri;
14295            this.referrer = referrer;
14296            this.originatingUid = originatingUid;
14297            this.installerUid = installerUid;
14298        }
14299    }
14300
14301    class InstallParams extends HandlerParams {
14302        final OriginInfo origin;
14303        final MoveInfo move;
14304        final IPackageInstallObserver2 observer;
14305        int installFlags;
14306        final String installerPackageName;
14307        final String volumeUuid;
14308        private InstallArgs mArgs;
14309        private int mRet;
14310        final String packageAbiOverride;
14311        final String[] grantedRuntimePermissions;
14312        final VerificationInfo verificationInfo;
14313        final Certificate[][] certificates;
14314        final int installReason;
14315
14316        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14317                int installFlags, String installerPackageName, String volumeUuid,
14318                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14319                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14320            super(user);
14321            this.origin = origin;
14322            this.move = move;
14323            this.observer = observer;
14324            this.installFlags = installFlags;
14325            this.installerPackageName = installerPackageName;
14326            this.volumeUuid = volumeUuid;
14327            this.verificationInfo = verificationInfo;
14328            this.packageAbiOverride = packageAbiOverride;
14329            this.grantedRuntimePermissions = grantedPermissions;
14330            this.certificates = certificates;
14331            this.installReason = installReason;
14332        }
14333
14334        @Override
14335        public String toString() {
14336            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14337                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14338        }
14339
14340        private int installLocationPolicy(PackageInfoLite pkgLite) {
14341            String packageName = pkgLite.packageName;
14342            int installLocation = pkgLite.installLocation;
14343            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14344            // reader
14345            synchronized (mPackages) {
14346                // Currently installed package which the new package is attempting to replace or
14347                // null if no such package is installed.
14348                PackageParser.Package installedPkg = mPackages.get(packageName);
14349                // Package which currently owns the data which the new package will own if installed.
14350                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14351                // will be null whereas dataOwnerPkg will contain information about the package
14352                // which was uninstalled while keeping its data.
14353                PackageParser.Package dataOwnerPkg = installedPkg;
14354                if (dataOwnerPkg  == null) {
14355                    PackageSetting ps = mSettings.mPackages.get(packageName);
14356                    if (ps != null) {
14357                        dataOwnerPkg = ps.pkg;
14358                    }
14359                }
14360
14361                if (dataOwnerPkg != null) {
14362                    // If installed, the package will get access to data left on the device by its
14363                    // predecessor. As a security measure, this is permited only if this is not a
14364                    // version downgrade or if the predecessor package is marked as debuggable and
14365                    // a downgrade is explicitly requested.
14366                    //
14367                    // On debuggable platform builds, downgrades are permitted even for
14368                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14369                    // not offer security guarantees and thus it's OK to disable some security
14370                    // mechanisms to make debugging/testing easier on those builds. However, even on
14371                    // debuggable builds downgrades of packages are permitted only if requested via
14372                    // installFlags. This is because we aim to keep the behavior of debuggable
14373                    // platform builds as close as possible to the behavior of non-debuggable
14374                    // platform builds.
14375                    final boolean downgradeRequested =
14376                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14377                    final boolean packageDebuggable =
14378                                (dataOwnerPkg.applicationInfo.flags
14379                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14380                    final boolean downgradePermitted =
14381                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14382                    if (!downgradePermitted) {
14383                        try {
14384                            checkDowngrade(dataOwnerPkg, pkgLite);
14385                        } catch (PackageManagerException e) {
14386                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14387                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14388                        }
14389                    }
14390                }
14391
14392                if (installedPkg != null) {
14393                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14394                        // Check for updated system application.
14395                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14396                            if (onSd) {
14397                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14398                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14399                            }
14400                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14401                        } else {
14402                            if (onSd) {
14403                                // Install flag overrides everything.
14404                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14405                            }
14406                            // If current upgrade specifies particular preference
14407                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14408                                // Application explicitly specified internal.
14409                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14410                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14411                                // App explictly prefers external. Let policy decide
14412                            } else {
14413                                // Prefer previous location
14414                                if (isExternal(installedPkg)) {
14415                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14416                                }
14417                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14418                            }
14419                        }
14420                    } else {
14421                        // Invalid install. Return error code
14422                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14423                    }
14424                }
14425            }
14426            // All the special cases have been taken care of.
14427            // Return result based on recommended install location.
14428            if (onSd) {
14429                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14430            }
14431            return pkgLite.recommendedInstallLocation;
14432        }
14433
14434        /*
14435         * Invoke remote method to get package information and install
14436         * location values. Override install location based on default
14437         * policy if needed and then create install arguments based
14438         * on the install location.
14439         */
14440        public void handleStartCopy() throws RemoteException {
14441            int ret = PackageManager.INSTALL_SUCCEEDED;
14442
14443            // If we're already staged, we've firmly committed to an install location
14444            if (origin.staged) {
14445                if (origin.file != null) {
14446                    installFlags |= PackageManager.INSTALL_INTERNAL;
14447                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14448                } else if (origin.cid != null) {
14449                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14450                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14451                } else {
14452                    throw new IllegalStateException("Invalid stage location");
14453                }
14454            }
14455
14456            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14457            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14458            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14459            PackageInfoLite pkgLite = null;
14460
14461            if (onInt && onSd) {
14462                // Check if both bits are set.
14463                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14464                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14465            } else if (onSd && ephemeral) {
14466                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14467                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14468            } else {
14469                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14470                        packageAbiOverride);
14471
14472                if (DEBUG_EPHEMERAL && ephemeral) {
14473                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14474                }
14475
14476                /*
14477                 * If we have too little free space, try to free cache
14478                 * before giving up.
14479                 */
14480                if (!origin.staged && pkgLite.recommendedInstallLocation
14481                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14482                    // TODO: focus freeing disk space on the target device
14483                    final StorageManager storage = StorageManager.from(mContext);
14484                    final long lowThreshold = storage.getStorageLowBytes(
14485                            Environment.getDataDirectory());
14486
14487                    final long sizeBytes = mContainerService.calculateInstalledSize(
14488                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14489
14490                    try {
14491                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14492                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14493                                installFlags, packageAbiOverride);
14494                    } catch (InstallerException e) {
14495                        Slog.w(TAG, "Failed to free cache", e);
14496                    }
14497
14498                    /*
14499                     * The cache free must have deleted the file we
14500                     * downloaded to install.
14501                     *
14502                     * TODO: fix the "freeCache" call to not delete
14503                     *       the file we care about.
14504                     */
14505                    if (pkgLite.recommendedInstallLocation
14506                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14507                        pkgLite.recommendedInstallLocation
14508                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14509                    }
14510                }
14511            }
14512
14513            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14514                int loc = pkgLite.recommendedInstallLocation;
14515                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14516                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14517                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14518                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14519                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14520                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14521                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14522                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14523                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14524                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14525                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14526                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14527                } else {
14528                    // Override with defaults if needed.
14529                    loc = installLocationPolicy(pkgLite);
14530                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14531                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14532                    } else if (!onSd && !onInt) {
14533                        // Override install location with flags
14534                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14535                            // Set the flag to install on external media.
14536                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14537                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14538                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14539                            if (DEBUG_EPHEMERAL) {
14540                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14541                            }
14542                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14543                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14544                                    |PackageManager.INSTALL_INTERNAL);
14545                        } else {
14546                            // Make sure the flag for installing on external
14547                            // media is unset
14548                            installFlags |= PackageManager.INSTALL_INTERNAL;
14549                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14550                        }
14551                    }
14552                }
14553            }
14554
14555            final InstallArgs args = createInstallArgs(this);
14556            mArgs = args;
14557
14558            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14559                // TODO: http://b/22976637
14560                // Apps installed for "all" users use the device owner to verify the app
14561                UserHandle verifierUser = getUser();
14562                if (verifierUser == UserHandle.ALL) {
14563                    verifierUser = UserHandle.SYSTEM;
14564                }
14565
14566                /*
14567                 * Determine if we have any installed package verifiers. If we
14568                 * do, then we'll defer to them to verify the packages.
14569                 */
14570                final int requiredUid = mRequiredVerifierPackage == null ? -1
14571                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14572                                verifierUser.getIdentifier());
14573                if (!origin.existing && requiredUid != -1
14574                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14575                    final Intent verification = new Intent(
14576                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14577                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14578                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14579                            PACKAGE_MIME_TYPE);
14580                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14581
14582                    // Query all live verifiers based on current user state
14583                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14584                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14585
14586                    if (DEBUG_VERIFY) {
14587                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14588                                + verification.toString() + " with " + pkgLite.verifiers.length
14589                                + " optional verifiers");
14590                    }
14591
14592                    final int verificationId = mPendingVerificationToken++;
14593
14594                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14595
14596                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14597                            installerPackageName);
14598
14599                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14600                            installFlags);
14601
14602                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14603                            pkgLite.packageName);
14604
14605                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14606                            pkgLite.versionCode);
14607
14608                    if (verificationInfo != null) {
14609                        if (verificationInfo.originatingUri != null) {
14610                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14611                                    verificationInfo.originatingUri);
14612                        }
14613                        if (verificationInfo.referrer != null) {
14614                            verification.putExtra(Intent.EXTRA_REFERRER,
14615                                    verificationInfo.referrer);
14616                        }
14617                        if (verificationInfo.originatingUid >= 0) {
14618                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14619                                    verificationInfo.originatingUid);
14620                        }
14621                        if (verificationInfo.installerUid >= 0) {
14622                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14623                                    verificationInfo.installerUid);
14624                        }
14625                    }
14626
14627                    final PackageVerificationState verificationState = new PackageVerificationState(
14628                            requiredUid, args);
14629
14630                    mPendingVerification.append(verificationId, verificationState);
14631
14632                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14633                            receivers, verificationState);
14634
14635                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14636                    final long idleDuration = getVerificationTimeout();
14637
14638                    /*
14639                     * If any sufficient verifiers were listed in the package
14640                     * manifest, attempt to ask them.
14641                     */
14642                    if (sufficientVerifiers != null) {
14643                        final int N = sufficientVerifiers.size();
14644                        if (N == 0) {
14645                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14646                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14647                        } else {
14648                            for (int i = 0; i < N; i++) {
14649                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14650                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14651                                        verifierComponent.getPackageName(), idleDuration,
14652                                        verifierUser.getIdentifier(), false, "package verifier");
14653
14654                                final Intent sufficientIntent = new Intent(verification);
14655                                sufficientIntent.setComponent(verifierComponent);
14656                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14657                            }
14658                        }
14659                    }
14660
14661                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14662                            mRequiredVerifierPackage, receivers);
14663                    if (ret == PackageManager.INSTALL_SUCCEEDED
14664                            && mRequiredVerifierPackage != null) {
14665                        Trace.asyncTraceBegin(
14666                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14667                        /*
14668                         * Send the intent to the required verification agent,
14669                         * but only start the verification timeout after the
14670                         * target BroadcastReceivers have run.
14671                         */
14672                        verification.setComponent(requiredVerifierComponent);
14673                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14674                                mRequiredVerifierPackage, idleDuration,
14675                                verifierUser.getIdentifier(), false, "package verifier");
14676                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14677                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14678                                new BroadcastReceiver() {
14679                                    @Override
14680                                    public void onReceive(Context context, Intent intent) {
14681                                        final Message msg = mHandler
14682                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14683                                        msg.arg1 = verificationId;
14684                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14685                                    }
14686                                }, null, 0, null, null);
14687
14688                        /*
14689                         * We don't want the copy to proceed until verification
14690                         * succeeds, so null out this field.
14691                         */
14692                        mArgs = null;
14693                    }
14694                } else {
14695                    /*
14696                     * No package verification is enabled, so immediately start
14697                     * the remote call to initiate copy using temporary file.
14698                     */
14699                    ret = args.copyApk(mContainerService, true);
14700                }
14701            }
14702
14703            mRet = ret;
14704        }
14705
14706        @Override
14707        void handleReturnCode() {
14708            // If mArgs is null, then MCS couldn't be reached. When it
14709            // reconnects, it will try again to install. At that point, this
14710            // will succeed.
14711            if (mArgs != null) {
14712                processPendingInstall(mArgs, mRet);
14713            }
14714        }
14715
14716        @Override
14717        void handleServiceError() {
14718            mArgs = createInstallArgs(this);
14719            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14720        }
14721
14722        public boolean isForwardLocked() {
14723            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14724        }
14725    }
14726
14727    /**
14728     * Used during creation of InstallArgs
14729     *
14730     * @param installFlags package installation flags
14731     * @return true if should be installed on external storage
14732     */
14733    private static boolean installOnExternalAsec(int installFlags) {
14734        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14735            return false;
14736        }
14737        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14738            return true;
14739        }
14740        return false;
14741    }
14742
14743    /**
14744     * Used during creation of InstallArgs
14745     *
14746     * @param installFlags package installation flags
14747     * @return true if should be installed as forward locked
14748     */
14749    private static boolean installForwardLocked(int installFlags) {
14750        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14751    }
14752
14753    private InstallArgs createInstallArgs(InstallParams params) {
14754        if (params.move != null) {
14755            return new MoveInstallArgs(params);
14756        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14757            return new AsecInstallArgs(params);
14758        } else {
14759            return new FileInstallArgs(params);
14760        }
14761    }
14762
14763    /**
14764     * Create args that describe an existing installed package. Typically used
14765     * when cleaning up old installs, or used as a move source.
14766     */
14767    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14768            String resourcePath, String[] instructionSets) {
14769        final boolean isInAsec;
14770        if (installOnExternalAsec(installFlags)) {
14771            /* Apps on SD card are always in ASEC containers. */
14772            isInAsec = true;
14773        } else if (installForwardLocked(installFlags)
14774                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14775            /*
14776             * Forward-locked apps are only in ASEC containers if they're the
14777             * new style
14778             */
14779            isInAsec = true;
14780        } else {
14781            isInAsec = false;
14782        }
14783
14784        if (isInAsec) {
14785            return new AsecInstallArgs(codePath, instructionSets,
14786                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14787        } else {
14788            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14789        }
14790    }
14791
14792    static abstract class InstallArgs {
14793        /** @see InstallParams#origin */
14794        final OriginInfo origin;
14795        /** @see InstallParams#move */
14796        final MoveInfo move;
14797
14798        final IPackageInstallObserver2 observer;
14799        // Always refers to PackageManager flags only
14800        final int installFlags;
14801        final String installerPackageName;
14802        final String volumeUuid;
14803        final UserHandle user;
14804        final String abiOverride;
14805        final String[] installGrantPermissions;
14806        /** If non-null, drop an async trace when the install completes */
14807        final String traceMethod;
14808        final int traceCookie;
14809        final Certificate[][] certificates;
14810        final int installReason;
14811
14812        // The list of instruction sets supported by this app. This is currently
14813        // only used during the rmdex() phase to clean up resources. We can get rid of this
14814        // if we move dex files under the common app path.
14815        /* nullable */ String[] instructionSets;
14816
14817        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14818                int installFlags, String installerPackageName, String volumeUuid,
14819                UserHandle user, String[] instructionSets,
14820                String abiOverride, String[] installGrantPermissions,
14821                String traceMethod, int traceCookie, Certificate[][] certificates,
14822                int installReason) {
14823            this.origin = origin;
14824            this.move = move;
14825            this.installFlags = installFlags;
14826            this.observer = observer;
14827            this.installerPackageName = installerPackageName;
14828            this.volumeUuid = volumeUuid;
14829            this.user = user;
14830            this.instructionSets = instructionSets;
14831            this.abiOverride = abiOverride;
14832            this.installGrantPermissions = installGrantPermissions;
14833            this.traceMethod = traceMethod;
14834            this.traceCookie = traceCookie;
14835            this.certificates = certificates;
14836            this.installReason = installReason;
14837        }
14838
14839        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14840        abstract int doPreInstall(int status);
14841
14842        /**
14843         * Rename package into final resting place. All paths on the given
14844         * scanned package should be updated to reflect the rename.
14845         */
14846        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14847        abstract int doPostInstall(int status, int uid);
14848
14849        /** @see PackageSettingBase#codePathString */
14850        abstract String getCodePath();
14851        /** @see PackageSettingBase#resourcePathString */
14852        abstract String getResourcePath();
14853
14854        // Need installer lock especially for dex file removal.
14855        abstract void cleanUpResourcesLI();
14856        abstract boolean doPostDeleteLI(boolean delete);
14857
14858        /**
14859         * Called before the source arguments are copied. This is used mostly
14860         * for MoveParams when it needs to read the source file to put it in the
14861         * destination.
14862         */
14863        int doPreCopy() {
14864            return PackageManager.INSTALL_SUCCEEDED;
14865        }
14866
14867        /**
14868         * Called after the source arguments are copied. This is used mostly for
14869         * MoveParams when it needs to read the source file to put it in the
14870         * destination.
14871         */
14872        int doPostCopy(int uid) {
14873            return PackageManager.INSTALL_SUCCEEDED;
14874        }
14875
14876        protected boolean isFwdLocked() {
14877            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14878        }
14879
14880        protected boolean isExternalAsec() {
14881            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14882        }
14883
14884        protected boolean isEphemeral() {
14885            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14886        }
14887
14888        UserHandle getUser() {
14889            return user;
14890        }
14891    }
14892
14893    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14894        if (!allCodePaths.isEmpty()) {
14895            if (instructionSets == null) {
14896                throw new IllegalStateException("instructionSet == null");
14897            }
14898            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14899            for (String codePath : allCodePaths) {
14900                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14901                    try {
14902                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14903                    } catch (InstallerException ignored) {
14904                    }
14905                }
14906            }
14907        }
14908    }
14909
14910    /**
14911     * Logic to handle installation of non-ASEC applications, including copying
14912     * and renaming logic.
14913     */
14914    class FileInstallArgs extends InstallArgs {
14915        private File codeFile;
14916        private File resourceFile;
14917
14918        // Example topology:
14919        // /data/app/com.example/base.apk
14920        // /data/app/com.example/split_foo.apk
14921        // /data/app/com.example/lib/arm/libfoo.so
14922        // /data/app/com.example/lib/arm64/libfoo.so
14923        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14924
14925        /** New install */
14926        FileInstallArgs(InstallParams params) {
14927            super(params.origin, params.move, params.observer, params.installFlags,
14928                    params.installerPackageName, params.volumeUuid,
14929                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14930                    params.grantedRuntimePermissions,
14931                    params.traceMethod, params.traceCookie, params.certificates,
14932                    params.installReason);
14933            if (isFwdLocked()) {
14934                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14935            }
14936        }
14937
14938        /** Existing install */
14939        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14940            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14941                    null, null, null, 0, null /*certificates*/,
14942                    PackageManager.INSTALL_REASON_UNKNOWN);
14943            this.codeFile = (codePath != null) ? new File(codePath) : null;
14944            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14945        }
14946
14947        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14948            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14949            try {
14950                return doCopyApk(imcs, temp);
14951            } finally {
14952                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14953            }
14954        }
14955
14956        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14957            if (origin.staged) {
14958                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14959                codeFile = origin.file;
14960                resourceFile = origin.file;
14961                return PackageManager.INSTALL_SUCCEEDED;
14962            }
14963
14964            try {
14965                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14966                final File tempDir =
14967                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14968                codeFile = tempDir;
14969                resourceFile = tempDir;
14970            } catch (IOException e) {
14971                Slog.w(TAG, "Failed to create copy file: " + e);
14972                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14973            }
14974
14975            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14976                @Override
14977                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14978                    if (!FileUtils.isValidExtFilename(name)) {
14979                        throw new IllegalArgumentException("Invalid filename: " + name);
14980                    }
14981                    try {
14982                        final File file = new File(codeFile, name);
14983                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14984                                O_RDWR | O_CREAT, 0644);
14985                        Os.chmod(file.getAbsolutePath(), 0644);
14986                        return new ParcelFileDescriptor(fd);
14987                    } catch (ErrnoException e) {
14988                        throw new RemoteException("Failed to open: " + e.getMessage());
14989                    }
14990                }
14991            };
14992
14993            int ret = PackageManager.INSTALL_SUCCEEDED;
14994            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14995            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14996                Slog.e(TAG, "Failed to copy package");
14997                return ret;
14998            }
14999
15000            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15001            NativeLibraryHelper.Handle handle = null;
15002            try {
15003                handle = NativeLibraryHelper.Handle.create(codeFile);
15004                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15005                        abiOverride);
15006            } catch (IOException e) {
15007                Slog.e(TAG, "Copying native libraries failed", e);
15008                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15009            } finally {
15010                IoUtils.closeQuietly(handle);
15011            }
15012
15013            return ret;
15014        }
15015
15016        int doPreInstall(int status) {
15017            if (status != PackageManager.INSTALL_SUCCEEDED) {
15018                cleanUp();
15019            }
15020            return status;
15021        }
15022
15023        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15024            if (status != PackageManager.INSTALL_SUCCEEDED) {
15025                cleanUp();
15026                return false;
15027            }
15028
15029            final File targetDir = codeFile.getParentFile();
15030            final File beforeCodeFile = codeFile;
15031            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15032
15033            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15034            try {
15035                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15036            } catch (ErrnoException e) {
15037                Slog.w(TAG, "Failed to rename", e);
15038                return false;
15039            }
15040
15041            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15042                Slog.w(TAG, "Failed to restorecon");
15043                return false;
15044            }
15045
15046            // Reflect the rename internally
15047            codeFile = afterCodeFile;
15048            resourceFile = afterCodeFile;
15049
15050            // Reflect the rename in scanned details
15051            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15052            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15053                    afterCodeFile, pkg.baseCodePath));
15054            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15055                    afterCodeFile, pkg.splitCodePaths));
15056
15057            // Reflect the rename in app info
15058            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15059            pkg.setApplicationInfoCodePath(pkg.codePath);
15060            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15061            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15062            pkg.setApplicationInfoResourcePath(pkg.codePath);
15063            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15064            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15065
15066            return true;
15067        }
15068
15069        int doPostInstall(int status, int uid) {
15070            if (status != PackageManager.INSTALL_SUCCEEDED) {
15071                cleanUp();
15072            }
15073            return status;
15074        }
15075
15076        @Override
15077        String getCodePath() {
15078            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15079        }
15080
15081        @Override
15082        String getResourcePath() {
15083            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15084        }
15085
15086        private boolean cleanUp() {
15087            if (codeFile == null || !codeFile.exists()) {
15088                return false;
15089            }
15090
15091            removeCodePathLI(codeFile);
15092
15093            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15094                resourceFile.delete();
15095            }
15096
15097            return true;
15098        }
15099
15100        void cleanUpResourcesLI() {
15101            // Try enumerating all code paths before deleting
15102            List<String> allCodePaths = Collections.EMPTY_LIST;
15103            if (codeFile != null && codeFile.exists()) {
15104                try {
15105                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15106                    allCodePaths = pkg.getAllCodePaths();
15107                } catch (PackageParserException e) {
15108                    // Ignored; we tried our best
15109                }
15110            }
15111
15112            cleanUp();
15113            removeDexFiles(allCodePaths, instructionSets);
15114        }
15115
15116        boolean doPostDeleteLI(boolean delete) {
15117            // XXX err, shouldn't we respect the delete flag?
15118            cleanUpResourcesLI();
15119            return true;
15120        }
15121    }
15122
15123    private boolean isAsecExternal(String cid) {
15124        final String asecPath = PackageHelper.getSdFilesystem(cid);
15125        return !asecPath.startsWith(mAsecInternalPath);
15126    }
15127
15128    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15129            PackageManagerException {
15130        if (copyRet < 0) {
15131            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15132                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15133                throw new PackageManagerException(copyRet, message);
15134            }
15135        }
15136    }
15137
15138    /**
15139     * Extract the StorageManagerService "container ID" from the full code path of an
15140     * .apk.
15141     */
15142    static String cidFromCodePath(String fullCodePath) {
15143        int eidx = fullCodePath.lastIndexOf("/");
15144        String subStr1 = fullCodePath.substring(0, eidx);
15145        int sidx = subStr1.lastIndexOf("/");
15146        return subStr1.substring(sidx+1, eidx);
15147    }
15148
15149    /**
15150     * Logic to handle installation of ASEC applications, including copying and
15151     * renaming logic.
15152     */
15153    class AsecInstallArgs extends InstallArgs {
15154        static final String RES_FILE_NAME = "pkg.apk";
15155        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15156
15157        String cid;
15158        String packagePath;
15159        String resourcePath;
15160
15161        /** New install */
15162        AsecInstallArgs(InstallParams params) {
15163            super(params.origin, params.move, params.observer, params.installFlags,
15164                    params.installerPackageName, params.volumeUuid,
15165                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15166                    params.grantedRuntimePermissions,
15167                    params.traceMethod, params.traceCookie, params.certificates,
15168                    params.installReason);
15169        }
15170
15171        /** Existing install */
15172        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15173                        boolean isExternal, boolean isForwardLocked) {
15174            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15175                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15176                    instructionSets, null, null, null, 0, null /*certificates*/,
15177                    PackageManager.INSTALL_REASON_UNKNOWN);
15178            // Hackily pretend we're still looking at a full code path
15179            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15180                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15181            }
15182
15183            // Extract cid from fullCodePath
15184            int eidx = fullCodePath.lastIndexOf("/");
15185            String subStr1 = fullCodePath.substring(0, eidx);
15186            int sidx = subStr1.lastIndexOf("/");
15187            cid = subStr1.substring(sidx+1, eidx);
15188            setMountPath(subStr1);
15189        }
15190
15191        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15192            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15193                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15194                    instructionSets, null, null, null, 0, null /*certificates*/,
15195                    PackageManager.INSTALL_REASON_UNKNOWN);
15196            this.cid = cid;
15197            setMountPath(PackageHelper.getSdDir(cid));
15198        }
15199
15200        void createCopyFile() {
15201            cid = mInstallerService.allocateExternalStageCidLegacy();
15202        }
15203
15204        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15205            if (origin.staged && origin.cid != null) {
15206                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15207                cid = origin.cid;
15208                setMountPath(PackageHelper.getSdDir(cid));
15209                return PackageManager.INSTALL_SUCCEEDED;
15210            }
15211
15212            if (temp) {
15213                createCopyFile();
15214            } else {
15215                /*
15216                 * Pre-emptively destroy the container since it's destroyed if
15217                 * copying fails due to it existing anyway.
15218                 */
15219                PackageHelper.destroySdDir(cid);
15220            }
15221
15222            final String newMountPath = imcs.copyPackageToContainer(
15223                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15224                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15225
15226            if (newMountPath != null) {
15227                setMountPath(newMountPath);
15228                return PackageManager.INSTALL_SUCCEEDED;
15229            } else {
15230                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15231            }
15232        }
15233
15234        @Override
15235        String getCodePath() {
15236            return packagePath;
15237        }
15238
15239        @Override
15240        String getResourcePath() {
15241            return resourcePath;
15242        }
15243
15244        int doPreInstall(int status) {
15245            if (status != PackageManager.INSTALL_SUCCEEDED) {
15246                // Destroy container
15247                PackageHelper.destroySdDir(cid);
15248            } else {
15249                boolean mounted = PackageHelper.isContainerMounted(cid);
15250                if (!mounted) {
15251                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15252                            Process.SYSTEM_UID);
15253                    if (newMountPath != null) {
15254                        setMountPath(newMountPath);
15255                    } else {
15256                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15257                    }
15258                }
15259            }
15260            return status;
15261        }
15262
15263        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15264            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15265            String newMountPath = null;
15266            if (PackageHelper.isContainerMounted(cid)) {
15267                // Unmount the container
15268                if (!PackageHelper.unMountSdDir(cid)) {
15269                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15270                    return false;
15271                }
15272            }
15273            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15274                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15275                        " which might be stale. Will try to clean up.");
15276                // Clean up the stale container and proceed to recreate.
15277                if (!PackageHelper.destroySdDir(newCacheId)) {
15278                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15279                    return false;
15280                }
15281                // Successfully cleaned up stale container. Try to rename again.
15282                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15283                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15284                            + " inspite of cleaning it up.");
15285                    return false;
15286                }
15287            }
15288            if (!PackageHelper.isContainerMounted(newCacheId)) {
15289                Slog.w(TAG, "Mounting container " + newCacheId);
15290                newMountPath = PackageHelper.mountSdDir(newCacheId,
15291                        getEncryptKey(), Process.SYSTEM_UID);
15292            } else {
15293                newMountPath = PackageHelper.getSdDir(newCacheId);
15294            }
15295            if (newMountPath == null) {
15296                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15297                return false;
15298            }
15299            Log.i(TAG, "Succesfully renamed " + cid +
15300                    " to " + newCacheId +
15301                    " at new path: " + newMountPath);
15302            cid = newCacheId;
15303
15304            final File beforeCodeFile = new File(packagePath);
15305            setMountPath(newMountPath);
15306            final File afterCodeFile = new File(packagePath);
15307
15308            // Reflect the rename in scanned details
15309            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15310            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15311                    afterCodeFile, pkg.baseCodePath));
15312            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15313                    afterCodeFile, pkg.splitCodePaths));
15314
15315            // Reflect the rename in app info
15316            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15317            pkg.setApplicationInfoCodePath(pkg.codePath);
15318            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15319            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15320            pkg.setApplicationInfoResourcePath(pkg.codePath);
15321            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15322            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15323
15324            return true;
15325        }
15326
15327        private void setMountPath(String mountPath) {
15328            final File mountFile = new File(mountPath);
15329
15330            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15331            if (monolithicFile.exists()) {
15332                packagePath = monolithicFile.getAbsolutePath();
15333                if (isFwdLocked()) {
15334                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15335                } else {
15336                    resourcePath = packagePath;
15337                }
15338            } else {
15339                packagePath = mountFile.getAbsolutePath();
15340                resourcePath = packagePath;
15341            }
15342        }
15343
15344        int doPostInstall(int status, int uid) {
15345            if (status != PackageManager.INSTALL_SUCCEEDED) {
15346                cleanUp();
15347            } else {
15348                final int groupOwner;
15349                final String protectedFile;
15350                if (isFwdLocked()) {
15351                    groupOwner = UserHandle.getSharedAppGid(uid);
15352                    protectedFile = RES_FILE_NAME;
15353                } else {
15354                    groupOwner = -1;
15355                    protectedFile = null;
15356                }
15357
15358                if (uid < Process.FIRST_APPLICATION_UID
15359                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15360                    Slog.e(TAG, "Failed to finalize " + cid);
15361                    PackageHelper.destroySdDir(cid);
15362                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15363                }
15364
15365                boolean mounted = PackageHelper.isContainerMounted(cid);
15366                if (!mounted) {
15367                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15368                }
15369            }
15370            return status;
15371        }
15372
15373        private void cleanUp() {
15374            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15375
15376            // Destroy secure container
15377            PackageHelper.destroySdDir(cid);
15378        }
15379
15380        private List<String> getAllCodePaths() {
15381            final File codeFile = new File(getCodePath());
15382            if (codeFile != null && codeFile.exists()) {
15383                try {
15384                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15385                    return pkg.getAllCodePaths();
15386                } catch (PackageParserException e) {
15387                    // Ignored; we tried our best
15388                }
15389            }
15390            return Collections.EMPTY_LIST;
15391        }
15392
15393        void cleanUpResourcesLI() {
15394            // Enumerate all code paths before deleting
15395            cleanUpResourcesLI(getAllCodePaths());
15396        }
15397
15398        private void cleanUpResourcesLI(List<String> allCodePaths) {
15399            cleanUp();
15400            removeDexFiles(allCodePaths, instructionSets);
15401        }
15402
15403        String getPackageName() {
15404            return getAsecPackageName(cid);
15405        }
15406
15407        boolean doPostDeleteLI(boolean delete) {
15408            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15409            final List<String> allCodePaths = getAllCodePaths();
15410            boolean mounted = PackageHelper.isContainerMounted(cid);
15411            if (mounted) {
15412                // Unmount first
15413                if (PackageHelper.unMountSdDir(cid)) {
15414                    mounted = false;
15415                }
15416            }
15417            if (!mounted && delete) {
15418                cleanUpResourcesLI(allCodePaths);
15419            }
15420            return !mounted;
15421        }
15422
15423        @Override
15424        int doPreCopy() {
15425            if (isFwdLocked()) {
15426                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15427                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15428                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15429                }
15430            }
15431
15432            return PackageManager.INSTALL_SUCCEEDED;
15433        }
15434
15435        @Override
15436        int doPostCopy(int uid) {
15437            if (isFwdLocked()) {
15438                if (uid < Process.FIRST_APPLICATION_UID
15439                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15440                                RES_FILE_NAME)) {
15441                    Slog.e(TAG, "Failed to finalize " + cid);
15442                    PackageHelper.destroySdDir(cid);
15443                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15444                }
15445            }
15446
15447            return PackageManager.INSTALL_SUCCEEDED;
15448        }
15449    }
15450
15451    /**
15452     * Logic to handle movement of existing installed applications.
15453     */
15454    class MoveInstallArgs extends InstallArgs {
15455        private File codeFile;
15456        private File resourceFile;
15457
15458        /** New install */
15459        MoveInstallArgs(InstallParams params) {
15460            super(params.origin, params.move, params.observer, params.installFlags,
15461                    params.installerPackageName, params.volumeUuid,
15462                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15463                    params.grantedRuntimePermissions,
15464                    params.traceMethod, params.traceCookie, params.certificates,
15465                    params.installReason);
15466        }
15467
15468        int copyApk(IMediaContainerService imcs, boolean temp) {
15469            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15470                    + move.fromUuid + " to " + move.toUuid);
15471            synchronized (mInstaller) {
15472                try {
15473                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15474                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15475                } catch (InstallerException e) {
15476                    Slog.w(TAG, "Failed to move app", e);
15477                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15478                }
15479            }
15480
15481            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15482            resourceFile = codeFile;
15483            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15484
15485            return PackageManager.INSTALL_SUCCEEDED;
15486        }
15487
15488        int doPreInstall(int status) {
15489            if (status != PackageManager.INSTALL_SUCCEEDED) {
15490                cleanUp(move.toUuid);
15491            }
15492            return status;
15493        }
15494
15495        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15496            if (status != PackageManager.INSTALL_SUCCEEDED) {
15497                cleanUp(move.toUuid);
15498                return false;
15499            }
15500
15501            // Reflect the move in app info
15502            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15503            pkg.setApplicationInfoCodePath(pkg.codePath);
15504            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15505            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15506            pkg.setApplicationInfoResourcePath(pkg.codePath);
15507            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15508            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15509
15510            return true;
15511        }
15512
15513        int doPostInstall(int status, int uid) {
15514            if (status == PackageManager.INSTALL_SUCCEEDED) {
15515                cleanUp(move.fromUuid);
15516            } else {
15517                cleanUp(move.toUuid);
15518            }
15519            return status;
15520        }
15521
15522        @Override
15523        String getCodePath() {
15524            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15525        }
15526
15527        @Override
15528        String getResourcePath() {
15529            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15530        }
15531
15532        private boolean cleanUp(String volumeUuid) {
15533            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15534                    move.dataAppName);
15535            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15536            final int[] userIds = sUserManager.getUserIds();
15537            synchronized (mInstallLock) {
15538                // Clean up both app data and code
15539                // All package moves are frozen until finished
15540                for (int userId : userIds) {
15541                    try {
15542                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15543                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15544                    } catch (InstallerException e) {
15545                        Slog.w(TAG, String.valueOf(e));
15546                    }
15547                }
15548                removeCodePathLI(codeFile);
15549            }
15550            return true;
15551        }
15552
15553        void cleanUpResourcesLI() {
15554            throw new UnsupportedOperationException();
15555        }
15556
15557        boolean doPostDeleteLI(boolean delete) {
15558            throw new UnsupportedOperationException();
15559        }
15560    }
15561
15562    static String getAsecPackageName(String packageCid) {
15563        int idx = packageCid.lastIndexOf("-");
15564        if (idx == -1) {
15565            return packageCid;
15566        }
15567        return packageCid.substring(0, idx);
15568    }
15569
15570    // Utility method used to create code paths based on package name and available index.
15571    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15572        String idxStr = "";
15573        int idx = 1;
15574        // Fall back to default value of idx=1 if prefix is not
15575        // part of oldCodePath
15576        if (oldCodePath != null) {
15577            String subStr = oldCodePath;
15578            // Drop the suffix right away
15579            if (suffix != null && subStr.endsWith(suffix)) {
15580                subStr = subStr.substring(0, subStr.length() - suffix.length());
15581            }
15582            // If oldCodePath already contains prefix find out the
15583            // ending index to either increment or decrement.
15584            int sidx = subStr.lastIndexOf(prefix);
15585            if (sidx != -1) {
15586                subStr = subStr.substring(sidx + prefix.length());
15587                if (subStr != null) {
15588                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15589                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15590                    }
15591                    try {
15592                        idx = Integer.parseInt(subStr);
15593                        if (idx <= 1) {
15594                            idx++;
15595                        } else {
15596                            idx--;
15597                        }
15598                    } catch(NumberFormatException e) {
15599                    }
15600                }
15601            }
15602        }
15603        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15604        return prefix + idxStr;
15605    }
15606
15607    private File getNextCodePath(File targetDir, String packageName) {
15608        File result;
15609        SecureRandom random = new SecureRandom();
15610        byte[] bytes = new byte[16];
15611        do {
15612            random.nextBytes(bytes);
15613            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15614            result = new File(targetDir, packageName + "-" + suffix);
15615        } while (result.exists());
15616        return result;
15617    }
15618
15619    // Utility method that returns the relative package path with respect
15620    // to the installation directory. Like say for /data/data/com.test-1.apk
15621    // string com.test-1 is returned.
15622    static String deriveCodePathName(String codePath) {
15623        if (codePath == null) {
15624            return null;
15625        }
15626        final File codeFile = new File(codePath);
15627        final String name = codeFile.getName();
15628        if (codeFile.isDirectory()) {
15629            return name;
15630        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15631            final int lastDot = name.lastIndexOf('.');
15632            return name.substring(0, lastDot);
15633        } else {
15634            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15635            return null;
15636        }
15637    }
15638
15639    static class PackageInstalledInfo {
15640        String name;
15641        int uid;
15642        // The set of users that originally had this package installed.
15643        int[] origUsers;
15644        // The set of users that now have this package installed.
15645        int[] newUsers;
15646        PackageParser.Package pkg;
15647        int returnCode;
15648        String returnMsg;
15649        PackageRemovedInfo removedInfo;
15650        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15651
15652        public void setError(int code, String msg) {
15653            setReturnCode(code);
15654            setReturnMessage(msg);
15655            Slog.w(TAG, msg);
15656        }
15657
15658        public void setError(String msg, PackageParserException e) {
15659            setReturnCode(e.error);
15660            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15661            Slog.w(TAG, msg, e);
15662        }
15663
15664        public void setError(String msg, PackageManagerException e) {
15665            returnCode = e.error;
15666            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15667            Slog.w(TAG, msg, e);
15668        }
15669
15670        public void setReturnCode(int returnCode) {
15671            this.returnCode = returnCode;
15672            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15673            for (int i = 0; i < childCount; i++) {
15674                addedChildPackages.valueAt(i).returnCode = returnCode;
15675            }
15676        }
15677
15678        private void setReturnMessage(String returnMsg) {
15679            this.returnMsg = returnMsg;
15680            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15681            for (int i = 0; i < childCount; i++) {
15682                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15683            }
15684        }
15685
15686        // In some error cases we want to convey more info back to the observer
15687        String origPackage;
15688        String origPermission;
15689    }
15690
15691    /*
15692     * Install a non-existing package.
15693     */
15694    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15695            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15696            PackageInstalledInfo res, int installReason) {
15697        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15698
15699        // Remember this for later, in case we need to rollback this install
15700        String pkgName = pkg.packageName;
15701
15702        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15703
15704        synchronized(mPackages) {
15705            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15706            if (renamedPackage != null) {
15707                // A package with the same name is already installed, though
15708                // it has been renamed to an older name.  The package we
15709                // are trying to install should be installed as an update to
15710                // the existing one, but that has not been requested, so bail.
15711                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15712                        + " without first uninstalling package running as "
15713                        + renamedPackage);
15714                return;
15715            }
15716            if (mPackages.containsKey(pkgName)) {
15717                // Don't allow installation over an existing package with the same name.
15718                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15719                        + " without first uninstalling.");
15720                return;
15721            }
15722        }
15723
15724        try {
15725            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15726                    System.currentTimeMillis(), user);
15727
15728            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15729
15730            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15731                prepareAppDataAfterInstallLIF(newPackage);
15732
15733            } else {
15734                // Remove package from internal structures, but keep around any
15735                // data that might have already existed
15736                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15737                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15738            }
15739        } catch (PackageManagerException e) {
15740            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15741        }
15742
15743        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15744    }
15745
15746    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15747        // Can't rotate keys during boot or if sharedUser.
15748        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15749                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15750            return false;
15751        }
15752        // app is using upgradeKeySets; make sure all are valid
15753        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15754        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15755        for (int i = 0; i < upgradeKeySets.length; i++) {
15756            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15757                Slog.wtf(TAG, "Package "
15758                         + (oldPs.name != null ? oldPs.name : "<null>")
15759                         + " contains upgrade-key-set reference to unknown key-set: "
15760                         + upgradeKeySets[i]
15761                         + " reverting to signatures check.");
15762                return false;
15763            }
15764        }
15765        return true;
15766    }
15767
15768    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15769        // Upgrade keysets are being used.  Determine if new package has a superset of the
15770        // required keys.
15771        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15772        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15773        for (int i = 0; i < upgradeKeySets.length; i++) {
15774            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15775            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15776                return true;
15777            }
15778        }
15779        return false;
15780    }
15781
15782    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15783        try (DigestInputStream digestStream =
15784                new DigestInputStream(new FileInputStream(file), digest)) {
15785            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15786        }
15787    }
15788
15789    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15790            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15791            int installReason) {
15792        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15793
15794        final PackageParser.Package oldPackage;
15795        final String pkgName = pkg.packageName;
15796        final int[] allUsers;
15797        final int[] installedUsers;
15798
15799        synchronized(mPackages) {
15800            oldPackage = mPackages.get(pkgName);
15801            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15802
15803            // don't allow upgrade to target a release SDK from a pre-release SDK
15804            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15805                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15806            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15807                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15808            if (oldTargetsPreRelease
15809                    && !newTargetsPreRelease
15810                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15811                Slog.w(TAG, "Can't install package targeting released sdk");
15812                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15813                return;
15814            }
15815
15816            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15817
15818            // verify signatures are valid
15819            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15820                if (!checkUpgradeKeySetLP(ps, pkg)) {
15821                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15822                            "New package not signed by keys specified by upgrade-keysets: "
15823                                    + pkgName);
15824                    return;
15825                }
15826            } else {
15827                // default to original signature matching
15828                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15829                        != PackageManager.SIGNATURE_MATCH) {
15830                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15831                            "New package has a different signature: " + pkgName);
15832                    return;
15833                }
15834            }
15835
15836            // don't allow a system upgrade unless the upgrade hash matches
15837            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15838                byte[] digestBytes = null;
15839                try {
15840                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15841                    updateDigest(digest, new File(pkg.baseCodePath));
15842                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15843                        for (String path : pkg.splitCodePaths) {
15844                            updateDigest(digest, new File(path));
15845                        }
15846                    }
15847                    digestBytes = digest.digest();
15848                } catch (NoSuchAlgorithmException | IOException e) {
15849                    res.setError(INSTALL_FAILED_INVALID_APK,
15850                            "Could not compute hash: " + pkgName);
15851                    return;
15852                }
15853                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15854                    res.setError(INSTALL_FAILED_INVALID_APK,
15855                            "New package fails restrict-update check: " + pkgName);
15856                    return;
15857                }
15858                // retain upgrade restriction
15859                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15860            }
15861
15862            // Check for shared user id changes
15863            String invalidPackageName =
15864                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15865            if (invalidPackageName != null) {
15866                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15867                        "Package " + invalidPackageName + " tried to change user "
15868                                + oldPackage.mSharedUserId);
15869                return;
15870            }
15871
15872            // In case of rollback, remember per-user/profile install state
15873            allUsers = sUserManager.getUserIds();
15874            installedUsers = ps.queryInstalledUsers(allUsers, true);
15875
15876            // don't allow an upgrade from full to ephemeral
15877            if (isInstantApp) {
15878                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15879                    for (int currentUser : allUsers) {
15880                        if (!ps.getInstantApp(currentUser)) {
15881                            // can't downgrade from full to instant
15882                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15883                                    + " for user: " + currentUser);
15884                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15885                            return;
15886                        }
15887                    }
15888                } else if (!ps.getInstantApp(user.getIdentifier())) {
15889                    // can't downgrade from full to instant
15890                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15891                            + " for user: " + user.getIdentifier());
15892                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15893                    return;
15894                }
15895            }
15896        }
15897
15898        // Update what is removed
15899        res.removedInfo = new PackageRemovedInfo();
15900        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15901        res.removedInfo.removedPackage = oldPackage.packageName;
15902        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15903        res.removedInfo.isUpdate = true;
15904        res.removedInfo.origUsers = installedUsers;
15905        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15906        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15907        for (int i = 0; i < installedUsers.length; i++) {
15908            final int userId = installedUsers[i];
15909            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15910        }
15911
15912        final int childCount = (oldPackage.childPackages != null)
15913                ? oldPackage.childPackages.size() : 0;
15914        for (int i = 0; i < childCount; i++) {
15915            boolean childPackageUpdated = false;
15916            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15917            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15918            if (res.addedChildPackages != null) {
15919                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15920                if (childRes != null) {
15921                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15922                    childRes.removedInfo.removedPackage = childPkg.packageName;
15923                    childRes.removedInfo.isUpdate = true;
15924                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15925                    childPackageUpdated = true;
15926                }
15927            }
15928            if (!childPackageUpdated) {
15929                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15930                childRemovedRes.removedPackage = childPkg.packageName;
15931                childRemovedRes.isUpdate = false;
15932                childRemovedRes.dataRemoved = true;
15933                synchronized (mPackages) {
15934                    if (childPs != null) {
15935                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15936                    }
15937                }
15938                if (res.removedInfo.removedChildPackages == null) {
15939                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15940                }
15941                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15942            }
15943        }
15944
15945        boolean sysPkg = (isSystemApp(oldPackage));
15946        if (sysPkg) {
15947            // Set the system/privileged flags as needed
15948            final boolean privileged =
15949                    (oldPackage.applicationInfo.privateFlags
15950                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15951            final int systemPolicyFlags = policyFlags
15952                    | PackageParser.PARSE_IS_SYSTEM
15953                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15954
15955            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15956                    user, allUsers, installerPackageName, res, installReason);
15957        } else {
15958            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15959                    user, allUsers, installerPackageName, res, installReason);
15960        }
15961    }
15962
15963    public List<String> getPreviousCodePaths(String packageName) {
15964        final PackageSetting ps = mSettings.mPackages.get(packageName);
15965        final List<String> result = new ArrayList<String>();
15966        if (ps != null && ps.oldCodePaths != null) {
15967            result.addAll(ps.oldCodePaths);
15968        }
15969        return result;
15970    }
15971
15972    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15973            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15974            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15975            int installReason) {
15976        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15977                + deletedPackage);
15978
15979        String pkgName = deletedPackage.packageName;
15980        boolean deletedPkg = true;
15981        boolean addedPkg = false;
15982        boolean updatedSettings = false;
15983        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15984        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15985                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15986
15987        final long origUpdateTime = (pkg.mExtras != null)
15988                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15989
15990        // First delete the existing package while retaining the data directory
15991        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15992                res.removedInfo, true, pkg)) {
15993            // If the existing package wasn't successfully deleted
15994            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15995            deletedPkg = false;
15996        } else {
15997            // Successfully deleted the old package; proceed with replace.
15998
15999            // If deleted package lived in a container, give users a chance to
16000            // relinquish resources before killing.
16001            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16002                if (DEBUG_INSTALL) {
16003                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16004                }
16005                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16006                final ArrayList<String> pkgList = new ArrayList<String>(1);
16007                pkgList.add(deletedPackage.applicationInfo.packageName);
16008                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16009            }
16010
16011            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16012                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16013            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16014
16015            try {
16016                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16017                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16018                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16019                        installReason);
16020
16021                // Update the in-memory copy of the previous code paths.
16022                PackageSetting ps = mSettings.mPackages.get(pkgName);
16023                if (!killApp) {
16024                    if (ps.oldCodePaths == null) {
16025                        ps.oldCodePaths = new ArraySet<>();
16026                    }
16027                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16028                    if (deletedPackage.splitCodePaths != null) {
16029                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16030                    }
16031                } else {
16032                    ps.oldCodePaths = null;
16033                }
16034                if (ps.childPackageNames != null) {
16035                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16036                        final String childPkgName = ps.childPackageNames.get(i);
16037                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16038                        childPs.oldCodePaths = ps.oldCodePaths;
16039                    }
16040                }
16041                // set instant app status, but, only if it's explicitly specified
16042                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16043                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16044                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16045                prepareAppDataAfterInstallLIF(newPackage);
16046                addedPkg = true;
16047                mDexManager.notifyPackageUpdated(newPackage.packageName,
16048                        newPackage.baseCodePath, newPackage.splitCodePaths);
16049            } catch (PackageManagerException e) {
16050                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16051            }
16052        }
16053
16054        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16055            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16056
16057            // Revert all internal state mutations and added folders for the failed install
16058            if (addedPkg) {
16059                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16060                        res.removedInfo, true, null);
16061            }
16062
16063            // Restore the old package
16064            if (deletedPkg) {
16065                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16066                File restoreFile = new File(deletedPackage.codePath);
16067                // Parse old package
16068                boolean oldExternal = isExternal(deletedPackage);
16069                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16070                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16071                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16072                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16073                try {
16074                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16075                            null);
16076                } catch (PackageManagerException e) {
16077                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16078                            + e.getMessage());
16079                    return;
16080                }
16081
16082                synchronized (mPackages) {
16083                    // Ensure the installer package name up to date
16084                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16085
16086                    // Update permissions for restored package
16087                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16088
16089                    mSettings.writeLPr();
16090                }
16091
16092                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16093            }
16094        } else {
16095            synchronized (mPackages) {
16096                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16097                if (ps != null) {
16098                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16099                    if (res.removedInfo.removedChildPackages != null) {
16100                        final int childCount = res.removedInfo.removedChildPackages.size();
16101                        // Iterate in reverse as we may modify the collection
16102                        for (int i = childCount - 1; i >= 0; i--) {
16103                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16104                            if (res.addedChildPackages.containsKey(childPackageName)) {
16105                                res.removedInfo.removedChildPackages.removeAt(i);
16106                            } else {
16107                                PackageRemovedInfo childInfo = res.removedInfo
16108                                        .removedChildPackages.valueAt(i);
16109                                childInfo.removedForAllUsers = mPackages.get(
16110                                        childInfo.removedPackage) == null;
16111                            }
16112                        }
16113                    }
16114                }
16115            }
16116        }
16117    }
16118
16119    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16120            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16121            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16122            int installReason) {
16123        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16124                + ", old=" + deletedPackage);
16125
16126        final boolean disabledSystem;
16127
16128        // Remove existing system package
16129        removePackageLI(deletedPackage, true);
16130
16131        synchronized (mPackages) {
16132            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16133        }
16134        if (!disabledSystem) {
16135            // We didn't need to disable the .apk as a current system package,
16136            // which means we are replacing another update that is already
16137            // installed.  We need to make sure to delete the older one's .apk.
16138            res.removedInfo.args = createInstallArgsForExisting(0,
16139                    deletedPackage.applicationInfo.getCodePath(),
16140                    deletedPackage.applicationInfo.getResourcePath(),
16141                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16142        } else {
16143            res.removedInfo.args = null;
16144        }
16145
16146        // Successfully disabled the old package. Now proceed with re-installation
16147        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16148                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16149        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16150
16151        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16152        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16153                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16154
16155        PackageParser.Package newPackage = null;
16156        try {
16157            // Add the package to the internal data structures
16158            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16159
16160            // Set the update and install times
16161            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16162            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16163                    System.currentTimeMillis());
16164
16165            // Update the package dynamic state if succeeded
16166            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16167                // Now that the install succeeded make sure we remove data
16168                // directories for any child package the update removed.
16169                final int deletedChildCount = (deletedPackage.childPackages != null)
16170                        ? deletedPackage.childPackages.size() : 0;
16171                final int newChildCount = (newPackage.childPackages != null)
16172                        ? newPackage.childPackages.size() : 0;
16173                for (int i = 0; i < deletedChildCount; i++) {
16174                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16175                    boolean childPackageDeleted = true;
16176                    for (int j = 0; j < newChildCount; j++) {
16177                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16178                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16179                            childPackageDeleted = false;
16180                            break;
16181                        }
16182                    }
16183                    if (childPackageDeleted) {
16184                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16185                                deletedChildPkg.packageName);
16186                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16187                            PackageRemovedInfo removedChildRes = res.removedInfo
16188                                    .removedChildPackages.get(deletedChildPkg.packageName);
16189                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16190                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16191                        }
16192                    }
16193                }
16194
16195                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16196                        installReason);
16197                prepareAppDataAfterInstallLIF(newPackage);
16198
16199                mDexManager.notifyPackageUpdated(newPackage.packageName,
16200                            newPackage.baseCodePath, newPackage.splitCodePaths);
16201            }
16202        } catch (PackageManagerException e) {
16203            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16204            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16205        }
16206
16207        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16208            // Re installation failed. Restore old information
16209            // Remove new pkg information
16210            if (newPackage != null) {
16211                removeInstalledPackageLI(newPackage, true);
16212            }
16213            // Add back the old system package
16214            try {
16215                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16216            } catch (PackageManagerException e) {
16217                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16218            }
16219
16220            synchronized (mPackages) {
16221                if (disabledSystem) {
16222                    enableSystemPackageLPw(deletedPackage);
16223                }
16224
16225                // Ensure the installer package name up to date
16226                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16227
16228                // Update permissions for restored package
16229                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16230
16231                mSettings.writeLPr();
16232            }
16233
16234            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16235                    + " after failed upgrade");
16236        }
16237    }
16238
16239    /**
16240     * Checks whether the parent or any of the child packages have a change shared
16241     * user. For a package to be a valid update the shred users of the parent and
16242     * the children should match. We may later support changing child shared users.
16243     * @param oldPkg The updated package.
16244     * @param newPkg The update package.
16245     * @return The shared user that change between the versions.
16246     */
16247    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16248            PackageParser.Package newPkg) {
16249        // Check parent shared user
16250        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16251            return newPkg.packageName;
16252        }
16253        // Check child shared users
16254        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16255        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16256        for (int i = 0; i < newChildCount; i++) {
16257            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16258            // If this child was present, did it have the same shared user?
16259            for (int j = 0; j < oldChildCount; j++) {
16260                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16261                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16262                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16263                    return newChildPkg.packageName;
16264                }
16265            }
16266        }
16267        return null;
16268    }
16269
16270    private void removeNativeBinariesLI(PackageSetting ps) {
16271        // Remove the lib path for the parent package
16272        if (ps != null) {
16273            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16274            // Remove the lib path for the child packages
16275            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16276            for (int i = 0; i < childCount; i++) {
16277                PackageSetting childPs = null;
16278                synchronized (mPackages) {
16279                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16280                }
16281                if (childPs != null) {
16282                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16283                            .legacyNativeLibraryPathString);
16284                }
16285            }
16286        }
16287    }
16288
16289    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16290        // Enable the parent package
16291        mSettings.enableSystemPackageLPw(pkg.packageName);
16292        // Enable the child packages
16293        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16294        for (int i = 0; i < childCount; i++) {
16295            PackageParser.Package childPkg = pkg.childPackages.get(i);
16296            mSettings.enableSystemPackageLPw(childPkg.packageName);
16297        }
16298    }
16299
16300    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16301            PackageParser.Package newPkg) {
16302        // Disable the parent package (parent always replaced)
16303        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16304        // Disable the child packages
16305        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16306        for (int i = 0; i < childCount; i++) {
16307            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16308            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16309            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16310        }
16311        return disabled;
16312    }
16313
16314    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16315            String installerPackageName) {
16316        // Enable the parent package
16317        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16318        // Enable the child packages
16319        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16320        for (int i = 0; i < childCount; i++) {
16321            PackageParser.Package childPkg = pkg.childPackages.get(i);
16322            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16323        }
16324    }
16325
16326    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16327        // Collect all used permissions in the UID
16328        ArraySet<String> usedPermissions = new ArraySet<>();
16329        final int packageCount = su.packages.size();
16330        for (int i = 0; i < packageCount; i++) {
16331            PackageSetting ps = su.packages.valueAt(i);
16332            if (ps.pkg == null) {
16333                continue;
16334            }
16335            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16336            for (int j = 0; j < requestedPermCount; j++) {
16337                String permission = ps.pkg.requestedPermissions.get(j);
16338                BasePermission bp = mSettings.mPermissions.get(permission);
16339                if (bp != null) {
16340                    usedPermissions.add(permission);
16341                }
16342            }
16343        }
16344
16345        PermissionsState permissionsState = su.getPermissionsState();
16346        // Prune install permissions
16347        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16348        final int installPermCount = installPermStates.size();
16349        for (int i = installPermCount - 1; i >= 0;  i--) {
16350            PermissionState permissionState = installPermStates.get(i);
16351            if (!usedPermissions.contains(permissionState.getName())) {
16352                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16353                if (bp != null) {
16354                    permissionsState.revokeInstallPermission(bp);
16355                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16356                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16357                }
16358            }
16359        }
16360
16361        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16362
16363        // Prune runtime permissions
16364        for (int userId : allUserIds) {
16365            List<PermissionState> runtimePermStates = permissionsState
16366                    .getRuntimePermissionStates(userId);
16367            final int runtimePermCount = runtimePermStates.size();
16368            for (int i = runtimePermCount - 1; i >= 0; i--) {
16369                PermissionState permissionState = runtimePermStates.get(i);
16370                if (!usedPermissions.contains(permissionState.getName())) {
16371                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16372                    if (bp != null) {
16373                        permissionsState.revokeRuntimePermission(bp, userId);
16374                        permissionsState.updatePermissionFlags(bp, userId,
16375                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16376                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16377                                runtimePermissionChangedUserIds, userId);
16378                    }
16379                }
16380            }
16381        }
16382
16383        return runtimePermissionChangedUserIds;
16384    }
16385
16386    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16387            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16388        // Update the parent package setting
16389        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16390                res, user, installReason);
16391        // Update the child packages setting
16392        final int childCount = (newPackage.childPackages != null)
16393                ? newPackage.childPackages.size() : 0;
16394        for (int i = 0; i < childCount; i++) {
16395            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16396            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16397            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16398                    childRes.origUsers, childRes, user, installReason);
16399        }
16400    }
16401
16402    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16403            String installerPackageName, int[] allUsers, int[] installedForUsers,
16404            PackageInstalledInfo res, UserHandle user, int installReason) {
16405        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16406
16407        String pkgName = newPackage.packageName;
16408        synchronized (mPackages) {
16409            //write settings. the installStatus will be incomplete at this stage.
16410            //note that the new package setting would have already been
16411            //added to mPackages. It hasn't been persisted yet.
16412            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16413            // TODO: Remove this write? It's also written at the end of this method
16414            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16415            mSettings.writeLPr();
16416            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16417        }
16418
16419        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16420        synchronized (mPackages) {
16421            updatePermissionsLPw(newPackage.packageName, newPackage,
16422                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16423                            ? UPDATE_PERMISSIONS_ALL : 0));
16424            // For system-bundled packages, we assume that installing an upgraded version
16425            // of the package implies that the user actually wants to run that new code,
16426            // so we enable the package.
16427            PackageSetting ps = mSettings.mPackages.get(pkgName);
16428            final int userId = user.getIdentifier();
16429            if (ps != null) {
16430                if (isSystemApp(newPackage)) {
16431                    if (DEBUG_INSTALL) {
16432                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16433                    }
16434                    // Enable system package for requested users
16435                    if (res.origUsers != null) {
16436                        for (int origUserId : res.origUsers) {
16437                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16438                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16439                                        origUserId, installerPackageName);
16440                            }
16441                        }
16442                    }
16443                    // Also convey the prior install/uninstall state
16444                    if (allUsers != null && installedForUsers != null) {
16445                        for (int currentUserId : allUsers) {
16446                            final boolean installed = ArrayUtils.contains(
16447                                    installedForUsers, currentUserId);
16448                            if (DEBUG_INSTALL) {
16449                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16450                            }
16451                            ps.setInstalled(installed, currentUserId);
16452                        }
16453                        // these install state changes will be persisted in the
16454                        // upcoming call to mSettings.writeLPr().
16455                    }
16456                }
16457                // It's implied that when a user requests installation, they want the app to be
16458                // installed and enabled.
16459                if (userId != UserHandle.USER_ALL) {
16460                    ps.setInstalled(true, userId);
16461                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16462                }
16463
16464                // When replacing an existing package, preserve the original install reason for all
16465                // users that had the package installed before.
16466                final Set<Integer> previousUserIds = new ArraySet<>();
16467                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16468                    final int installReasonCount = res.removedInfo.installReasons.size();
16469                    for (int i = 0; i < installReasonCount; i++) {
16470                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16471                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16472                        ps.setInstallReason(previousInstallReason, previousUserId);
16473                        previousUserIds.add(previousUserId);
16474                    }
16475                }
16476
16477                // Set install reason for users that are having the package newly installed.
16478                if (userId == UserHandle.USER_ALL) {
16479                    for (int currentUserId : sUserManager.getUserIds()) {
16480                        if (!previousUserIds.contains(currentUserId)) {
16481                            ps.setInstallReason(installReason, currentUserId);
16482                        }
16483                    }
16484                } else if (!previousUserIds.contains(userId)) {
16485                    ps.setInstallReason(installReason, userId);
16486                }
16487                mSettings.writeKernelMappingLPr(ps);
16488            }
16489            res.name = pkgName;
16490            res.uid = newPackage.applicationInfo.uid;
16491            res.pkg = newPackage;
16492            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16493            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16494            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16495            //to update install status
16496            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16497            mSettings.writeLPr();
16498            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16499        }
16500
16501        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16502    }
16503
16504    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16505        try {
16506            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16507            installPackageLI(args, res);
16508        } finally {
16509            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16510        }
16511    }
16512
16513    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16514        final int installFlags = args.installFlags;
16515        final String installerPackageName = args.installerPackageName;
16516        final String volumeUuid = args.volumeUuid;
16517        final File tmpPackageFile = new File(args.getCodePath());
16518        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16519        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16520                || (args.volumeUuid != null));
16521        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16522        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16523        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16524        boolean replace = false;
16525        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16526        if (args.move != null) {
16527            // moving a complete application; perform an initial scan on the new install location
16528            scanFlags |= SCAN_INITIAL;
16529        }
16530        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16531            scanFlags |= SCAN_DONT_KILL_APP;
16532        }
16533        if (instantApp) {
16534            scanFlags |= SCAN_AS_INSTANT_APP;
16535        }
16536        if (fullApp) {
16537            scanFlags |= SCAN_AS_FULL_APP;
16538        }
16539
16540        // Result object to be returned
16541        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16542
16543        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16544
16545        // Sanity check
16546        if (instantApp && (forwardLocked || onExternal)) {
16547            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16548                    + " external=" + onExternal);
16549            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16550            return;
16551        }
16552
16553        // Retrieve PackageSettings and parse package
16554        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16555                | PackageParser.PARSE_ENFORCE_CODE
16556                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16557                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16558                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16559                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16560        PackageParser pp = new PackageParser();
16561        pp.setSeparateProcesses(mSeparateProcesses);
16562        pp.setDisplayMetrics(mMetrics);
16563        pp.setCallback(mPackageParserCallback);
16564
16565        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16566        final PackageParser.Package pkg;
16567        try {
16568            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16569        } catch (PackageParserException e) {
16570            res.setError("Failed parse during installPackageLI", e);
16571            return;
16572        } finally {
16573            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16574        }
16575
16576        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16577        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16578            Slog.w(TAG, "Instant app package " + pkg.packageName
16579                    + " does not target O, this will be a fatal error.");
16580            // STOPSHIP: Make this a fatal error
16581            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16582        }
16583        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16584            Slog.w(TAG, "Instant app package " + pkg.packageName
16585                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16586            // STOPSHIP: Make this a fatal error
16587            pkg.applicationInfo.targetSandboxVersion = 2;
16588        }
16589
16590        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16591            // Static shared libraries have synthetic package names
16592            renameStaticSharedLibraryPackage(pkg);
16593
16594            // No static shared libs on external storage
16595            if (onExternal) {
16596                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16597                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16598                        "Packages declaring static-shared libs cannot be updated");
16599                return;
16600            }
16601        }
16602
16603        // If we are installing a clustered package add results for the children
16604        if (pkg.childPackages != null) {
16605            synchronized (mPackages) {
16606                final int childCount = pkg.childPackages.size();
16607                for (int i = 0; i < childCount; i++) {
16608                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16609                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16610                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16611                    childRes.pkg = childPkg;
16612                    childRes.name = childPkg.packageName;
16613                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16614                    if (childPs != null) {
16615                        childRes.origUsers = childPs.queryInstalledUsers(
16616                                sUserManager.getUserIds(), true);
16617                    }
16618                    if ((mPackages.containsKey(childPkg.packageName))) {
16619                        childRes.removedInfo = new PackageRemovedInfo();
16620                        childRes.removedInfo.removedPackage = childPkg.packageName;
16621                    }
16622                    if (res.addedChildPackages == null) {
16623                        res.addedChildPackages = new ArrayMap<>();
16624                    }
16625                    res.addedChildPackages.put(childPkg.packageName, childRes);
16626                }
16627            }
16628        }
16629
16630        // If package doesn't declare API override, mark that we have an install
16631        // time CPU ABI override.
16632        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16633            pkg.cpuAbiOverride = args.abiOverride;
16634        }
16635
16636        String pkgName = res.name = pkg.packageName;
16637        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16638            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16639                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16640                return;
16641            }
16642        }
16643
16644        try {
16645            // either use what we've been given or parse directly from the APK
16646            if (args.certificates != null) {
16647                try {
16648                    PackageParser.populateCertificates(pkg, args.certificates);
16649                } catch (PackageParserException e) {
16650                    // there was something wrong with the certificates we were given;
16651                    // try to pull them from the APK
16652                    PackageParser.collectCertificates(pkg, parseFlags);
16653                }
16654            } else {
16655                PackageParser.collectCertificates(pkg, parseFlags);
16656            }
16657        } catch (PackageParserException e) {
16658            res.setError("Failed collect during installPackageLI", e);
16659            return;
16660        }
16661
16662        // Get rid of all references to package scan path via parser.
16663        pp = null;
16664        String oldCodePath = null;
16665        boolean systemApp = false;
16666        synchronized (mPackages) {
16667            // Check if installing already existing package
16668            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16669                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16670                if (pkg.mOriginalPackages != null
16671                        && pkg.mOriginalPackages.contains(oldName)
16672                        && mPackages.containsKey(oldName)) {
16673                    // This package is derived from an original package,
16674                    // and this device has been updating from that original
16675                    // name.  We must continue using the original name, so
16676                    // rename the new package here.
16677                    pkg.setPackageName(oldName);
16678                    pkgName = pkg.packageName;
16679                    replace = true;
16680                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16681                            + oldName + " pkgName=" + pkgName);
16682                } else if (mPackages.containsKey(pkgName)) {
16683                    // This package, under its official name, already exists
16684                    // on the device; we should replace it.
16685                    replace = true;
16686                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16687                }
16688
16689                // Child packages are installed through the parent package
16690                if (pkg.parentPackage != null) {
16691                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16692                            "Package " + pkg.packageName + " is child of package "
16693                                    + pkg.parentPackage.parentPackage + ". Child packages "
16694                                    + "can be updated only through the parent package.");
16695                    return;
16696                }
16697
16698                if (replace) {
16699                    // Prevent apps opting out from runtime permissions
16700                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16701                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16702                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16703                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16704                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16705                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16706                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16707                                        + " doesn't support runtime permissions but the old"
16708                                        + " target SDK " + oldTargetSdk + " does.");
16709                        return;
16710                    }
16711                    // Prevent apps from downgrading their targetSandbox.
16712                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16713                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16714                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16715                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16716                                "Package " + pkg.packageName + " new target sandbox "
16717                                + newTargetSandbox + " is incompatible with the previous value of"
16718                                + oldTargetSandbox + ".");
16719                        return;
16720                    }
16721
16722                    // Prevent installing of child packages
16723                    if (oldPackage.parentPackage != null) {
16724                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16725                                "Package " + pkg.packageName + " is child of package "
16726                                        + oldPackage.parentPackage + ". Child packages "
16727                                        + "can be updated only through the parent package.");
16728                        return;
16729                    }
16730                }
16731            }
16732
16733            PackageSetting ps = mSettings.mPackages.get(pkgName);
16734            if (ps != null) {
16735                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16736
16737                // Static shared libs have same package with different versions where
16738                // we internally use a synthetic package name to allow multiple versions
16739                // of the same package, therefore we need to compare signatures against
16740                // the package setting for the latest library version.
16741                PackageSetting signatureCheckPs = ps;
16742                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16743                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16744                    if (libraryEntry != null) {
16745                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16746                    }
16747                }
16748
16749                // Quick sanity check that we're signed correctly if updating;
16750                // we'll check this again later when scanning, but we want to
16751                // bail early here before tripping over redefined permissions.
16752                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16753                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16754                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16755                                + pkg.packageName + " upgrade keys do not match the "
16756                                + "previously installed version");
16757                        return;
16758                    }
16759                } else {
16760                    try {
16761                        verifySignaturesLP(signatureCheckPs, pkg);
16762                    } catch (PackageManagerException e) {
16763                        res.setError(e.error, e.getMessage());
16764                        return;
16765                    }
16766                }
16767
16768                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16769                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16770                    systemApp = (ps.pkg.applicationInfo.flags &
16771                            ApplicationInfo.FLAG_SYSTEM) != 0;
16772                }
16773                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16774            }
16775
16776            int N = pkg.permissions.size();
16777            for (int i = N-1; i >= 0; i--) {
16778                PackageParser.Permission perm = pkg.permissions.get(i);
16779                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16780
16781                // Don't allow anyone but the platform to define ephemeral permissions.
16782                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16783                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16784                    Slog.w(TAG, "Package " + pkg.packageName
16785                            + " attempting to delcare ephemeral permission "
16786                            + perm.info.name + "; Removing ephemeral.");
16787                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16788                }
16789                // Check whether the newly-scanned package wants to define an already-defined perm
16790                if (bp != null) {
16791                    // If the defining package is signed with our cert, it's okay.  This
16792                    // also includes the "updating the same package" case, of course.
16793                    // "updating same package" could also involve key-rotation.
16794                    final boolean sigsOk;
16795                    if (bp.sourcePackage.equals(pkg.packageName)
16796                            && (bp.packageSetting instanceof PackageSetting)
16797                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16798                                    scanFlags))) {
16799                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16800                    } else {
16801                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16802                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16803                    }
16804                    if (!sigsOk) {
16805                        // If the owning package is the system itself, we log but allow
16806                        // install to proceed; we fail the install on all other permission
16807                        // redefinitions.
16808                        if (!bp.sourcePackage.equals("android")) {
16809                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16810                                    + pkg.packageName + " attempting to redeclare permission "
16811                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16812                            res.origPermission = perm.info.name;
16813                            res.origPackage = bp.sourcePackage;
16814                            return;
16815                        } else {
16816                            Slog.w(TAG, "Package " + pkg.packageName
16817                                    + " attempting to redeclare system permission "
16818                                    + perm.info.name + "; ignoring new declaration");
16819                            pkg.permissions.remove(i);
16820                        }
16821                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16822                        // Prevent apps to change protection level to dangerous from any other
16823                        // type as this would allow a privilege escalation where an app adds a
16824                        // normal/signature permission in other app's group and later redefines
16825                        // it as dangerous leading to the group auto-grant.
16826                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16827                                == PermissionInfo.PROTECTION_DANGEROUS) {
16828                            if (bp != null && !bp.isRuntime()) {
16829                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16830                                        + "non-runtime permission " + perm.info.name
16831                                        + " to runtime; keeping old protection level");
16832                                perm.info.protectionLevel = bp.protectionLevel;
16833                            }
16834                        }
16835                    }
16836                }
16837            }
16838        }
16839
16840        if (systemApp) {
16841            if (onExternal) {
16842                // Abort update; system app can't be replaced with app on sdcard
16843                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16844                        "Cannot install updates to system apps on sdcard");
16845                return;
16846            } else if (instantApp) {
16847                // Abort update; system app can't be replaced with an instant app
16848                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16849                        "Cannot update a system app with an instant app");
16850                return;
16851            }
16852        }
16853
16854        if (args.move != null) {
16855            // We did an in-place move, so dex is ready to roll
16856            scanFlags |= SCAN_NO_DEX;
16857            scanFlags |= SCAN_MOVE;
16858
16859            synchronized (mPackages) {
16860                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16861                if (ps == null) {
16862                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16863                            "Missing settings for moved package " + pkgName);
16864                }
16865
16866                // We moved the entire application as-is, so bring over the
16867                // previously derived ABI information.
16868                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16869                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16870            }
16871
16872        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16873            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16874            scanFlags |= SCAN_NO_DEX;
16875
16876            try {
16877                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16878                    args.abiOverride : pkg.cpuAbiOverride);
16879                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16880                        true /*extractLibs*/, mAppLib32InstallDir);
16881            } catch (PackageManagerException pme) {
16882                Slog.e(TAG, "Error deriving application ABI", pme);
16883                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16884                return;
16885            }
16886
16887            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16888            // Do not run PackageDexOptimizer through the local performDexOpt
16889            // method because `pkg` may not be in `mPackages` yet.
16890            //
16891            // Also, don't fail application installs if the dexopt step fails.
16892            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16893                    null /* instructionSets */, false /* checkProfiles */,
16894                    getCompilerFilterForReason(REASON_INSTALL),
16895                    getOrCreateCompilerPackageStats(pkg),
16896                    mDexManager.isUsedByOtherApps(pkg.packageName));
16897            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16898
16899            // Notify BackgroundDexOptService that the package has been changed.
16900            // If this is an update of a package which used to fail to compile,
16901            // BDOS will remove it from its blacklist.
16902            // TODO: Layering violation
16903            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16904        }
16905
16906        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16907            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16908            return;
16909        }
16910
16911        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16912
16913        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16914                "installPackageLI")) {
16915            if (replace) {
16916                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16917                    // Static libs have a synthetic package name containing the version
16918                    // and cannot be updated as an update would get a new package name,
16919                    // unless this is the exact same version code which is useful for
16920                    // development.
16921                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16922                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16923                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16924                                + "static-shared libs cannot be updated");
16925                        return;
16926                    }
16927                }
16928                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16929                        installerPackageName, res, args.installReason);
16930            } else {
16931                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16932                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16933            }
16934        }
16935        synchronized (mPackages) {
16936            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16937            if (ps != null) {
16938                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16939                ps.setUpdateAvailable(false /*updateAvailable*/);
16940            }
16941
16942            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16943            for (int i = 0; i < childCount; i++) {
16944                PackageParser.Package childPkg = pkg.childPackages.get(i);
16945                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16946                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16947                if (childPs != null) {
16948                    childRes.newUsers = childPs.queryInstalledUsers(
16949                            sUserManager.getUserIds(), true);
16950                }
16951            }
16952
16953            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16954                updateSequenceNumberLP(pkgName, res.newUsers);
16955                updateInstantAppInstallerLocked();
16956            }
16957        }
16958    }
16959
16960    private void startIntentFilterVerifications(int userId, boolean replacing,
16961            PackageParser.Package pkg) {
16962        if (mIntentFilterVerifierComponent == null) {
16963            Slog.w(TAG, "No IntentFilter verification will not be done as "
16964                    + "there is no IntentFilterVerifier available!");
16965            return;
16966        }
16967
16968        final int verifierUid = getPackageUid(
16969                mIntentFilterVerifierComponent.getPackageName(),
16970                MATCH_DEBUG_TRIAGED_MISSING,
16971                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16972
16973        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16974        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16975        mHandler.sendMessage(msg);
16976
16977        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16978        for (int i = 0; i < childCount; i++) {
16979            PackageParser.Package childPkg = pkg.childPackages.get(i);
16980            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16981            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16982            mHandler.sendMessage(msg);
16983        }
16984    }
16985
16986    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16987            PackageParser.Package pkg) {
16988        int size = pkg.activities.size();
16989        if (size == 0) {
16990            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16991                    "No activity, so no need to verify any IntentFilter!");
16992            return;
16993        }
16994
16995        final boolean hasDomainURLs = hasDomainURLs(pkg);
16996        if (!hasDomainURLs) {
16997            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16998                    "No domain URLs, so no need to verify any IntentFilter!");
16999            return;
17000        }
17001
17002        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17003                + " if any IntentFilter from the " + size
17004                + " Activities needs verification ...");
17005
17006        int count = 0;
17007        final String packageName = pkg.packageName;
17008
17009        synchronized (mPackages) {
17010            // If this is a new install and we see that we've already run verification for this
17011            // package, we have nothing to do: it means the state was restored from backup.
17012            if (!replacing) {
17013                IntentFilterVerificationInfo ivi =
17014                        mSettings.getIntentFilterVerificationLPr(packageName);
17015                if (ivi != null) {
17016                    if (DEBUG_DOMAIN_VERIFICATION) {
17017                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17018                                + ivi.getStatusString());
17019                    }
17020                    return;
17021                }
17022            }
17023
17024            // If any filters need to be verified, then all need to be.
17025            boolean needToVerify = false;
17026            for (PackageParser.Activity a : pkg.activities) {
17027                for (ActivityIntentInfo filter : a.intents) {
17028                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17029                        if (DEBUG_DOMAIN_VERIFICATION) {
17030                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17031                        }
17032                        needToVerify = true;
17033                        break;
17034                    }
17035                }
17036            }
17037
17038            if (needToVerify) {
17039                final int verificationId = mIntentFilterVerificationToken++;
17040                for (PackageParser.Activity a : pkg.activities) {
17041                    for (ActivityIntentInfo filter : a.intents) {
17042                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17043                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17044                                    "Verification needed for IntentFilter:" + filter.toString());
17045                            mIntentFilterVerifier.addOneIntentFilterVerification(
17046                                    verifierUid, userId, verificationId, filter, packageName);
17047                            count++;
17048                        }
17049                    }
17050                }
17051            }
17052        }
17053
17054        if (count > 0) {
17055            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17056                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17057                    +  " for userId:" + userId);
17058            mIntentFilterVerifier.startVerifications(userId);
17059        } else {
17060            if (DEBUG_DOMAIN_VERIFICATION) {
17061                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17062            }
17063        }
17064    }
17065
17066    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17067        final ComponentName cn  = filter.activity.getComponentName();
17068        final String packageName = cn.getPackageName();
17069
17070        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17071                packageName);
17072        if (ivi == null) {
17073            return true;
17074        }
17075        int status = ivi.getStatus();
17076        switch (status) {
17077            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17078            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17079                return true;
17080
17081            default:
17082                // Nothing to do
17083                return false;
17084        }
17085    }
17086
17087    private static boolean isMultiArch(ApplicationInfo info) {
17088        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17089    }
17090
17091    private static boolean isExternal(PackageParser.Package pkg) {
17092        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17093    }
17094
17095    private static boolean isExternal(PackageSetting ps) {
17096        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17097    }
17098
17099    private static boolean isSystemApp(PackageParser.Package pkg) {
17100        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17101    }
17102
17103    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17104        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17105    }
17106
17107    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17108        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17109    }
17110
17111    private static boolean isSystemApp(PackageSetting ps) {
17112        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17113    }
17114
17115    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17116        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17117    }
17118
17119    private int packageFlagsToInstallFlags(PackageSetting ps) {
17120        int installFlags = 0;
17121        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17122            // This existing package was an external ASEC install when we have
17123            // the external flag without a UUID
17124            installFlags |= PackageManager.INSTALL_EXTERNAL;
17125        }
17126        if (ps.isForwardLocked()) {
17127            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17128        }
17129        return installFlags;
17130    }
17131
17132    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17133        if (isExternal(pkg)) {
17134            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17135                return StorageManager.UUID_PRIMARY_PHYSICAL;
17136            } else {
17137                return pkg.volumeUuid;
17138            }
17139        } else {
17140            return StorageManager.UUID_PRIVATE_INTERNAL;
17141        }
17142    }
17143
17144    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17145        if (isExternal(pkg)) {
17146            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17147                return mSettings.getExternalVersion();
17148            } else {
17149                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17150            }
17151        } else {
17152            return mSettings.getInternalVersion();
17153        }
17154    }
17155
17156    private void deleteTempPackageFiles() {
17157        final FilenameFilter filter = new FilenameFilter() {
17158            public boolean accept(File dir, String name) {
17159                return name.startsWith("vmdl") && name.endsWith(".tmp");
17160            }
17161        };
17162        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17163            file.delete();
17164        }
17165    }
17166
17167    @Override
17168    public void deletePackageAsUser(String packageName, int versionCode,
17169            IPackageDeleteObserver observer, int userId, int flags) {
17170        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17171                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17172    }
17173
17174    @Override
17175    public void deletePackageVersioned(VersionedPackage versionedPackage,
17176            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17177        mContext.enforceCallingOrSelfPermission(
17178                android.Manifest.permission.DELETE_PACKAGES, null);
17179        Preconditions.checkNotNull(versionedPackage);
17180        Preconditions.checkNotNull(observer);
17181        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17182                PackageManager.VERSION_CODE_HIGHEST,
17183                Integer.MAX_VALUE, "versionCode must be >= -1");
17184
17185        final String packageName = versionedPackage.getPackageName();
17186        // TODO: We will change version code to long, so in the new API it is long
17187        final int versionCode = (int) versionedPackage.getVersionCode();
17188        final String internalPackageName;
17189        synchronized (mPackages) {
17190            // Normalize package name to handle renamed packages and static libs
17191            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17192                    // TODO: We will change version code to long, so in the new API it is long
17193                    (int) versionedPackage.getVersionCode());
17194        }
17195
17196        final int uid = Binder.getCallingUid();
17197        if (!isOrphaned(internalPackageName)
17198                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17199            try {
17200                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17201                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17202                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17203                observer.onUserActionRequired(intent);
17204            } catch (RemoteException re) {
17205            }
17206            return;
17207        }
17208        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17209        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17210        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17211            mContext.enforceCallingOrSelfPermission(
17212                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17213                    "deletePackage for user " + userId);
17214        }
17215
17216        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17217            try {
17218                observer.onPackageDeleted(packageName,
17219                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17220            } catch (RemoteException re) {
17221            }
17222            return;
17223        }
17224
17225        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17226            try {
17227                observer.onPackageDeleted(packageName,
17228                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17229            } catch (RemoteException re) {
17230            }
17231            return;
17232        }
17233
17234        if (DEBUG_REMOVE) {
17235            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17236                    + " deleteAllUsers: " + deleteAllUsers + " version="
17237                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17238                    ? "VERSION_CODE_HIGHEST" : versionCode));
17239        }
17240        // Queue up an async operation since the package deletion may take a little while.
17241        mHandler.post(new Runnable() {
17242            public void run() {
17243                mHandler.removeCallbacks(this);
17244                int returnCode;
17245                if (!deleteAllUsers) {
17246                    returnCode = deletePackageX(internalPackageName, versionCode,
17247                            userId, deleteFlags);
17248                } else {
17249                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17250                            internalPackageName, users);
17251                    // If nobody is blocking uninstall, proceed with delete for all users
17252                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17253                        returnCode = deletePackageX(internalPackageName, versionCode,
17254                                userId, deleteFlags);
17255                    } else {
17256                        // Otherwise uninstall individually for users with blockUninstalls=false
17257                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17258                        for (int userId : users) {
17259                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17260                                returnCode = deletePackageX(internalPackageName, versionCode,
17261                                        userId, userFlags);
17262                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17263                                    Slog.w(TAG, "Package delete failed for user " + userId
17264                                            + ", returnCode " + returnCode);
17265                                }
17266                            }
17267                        }
17268                        // The app has only been marked uninstalled for certain users.
17269                        // We still need to report that delete was blocked
17270                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17271                    }
17272                }
17273                try {
17274                    observer.onPackageDeleted(packageName, returnCode, null);
17275                } catch (RemoteException e) {
17276                    Log.i(TAG, "Observer no longer exists.");
17277                } //end catch
17278            } //end run
17279        });
17280    }
17281
17282    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17283        if (pkg.staticSharedLibName != null) {
17284            return pkg.manifestPackageName;
17285        }
17286        return pkg.packageName;
17287    }
17288
17289    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17290        // Handle renamed packages
17291        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17292        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17293
17294        // Is this a static library?
17295        SparseArray<SharedLibraryEntry> versionedLib =
17296                mStaticLibsByDeclaringPackage.get(packageName);
17297        if (versionedLib == null || versionedLib.size() <= 0) {
17298            return packageName;
17299        }
17300
17301        // Figure out which lib versions the caller can see
17302        SparseIntArray versionsCallerCanSee = null;
17303        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17304        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17305                && callingAppId != Process.ROOT_UID) {
17306            versionsCallerCanSee = new SparseIntArray();
17307            String libName = versionedLib.valueAt(0).info.getName();
17308            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17309            if (uidPackages != null) {
17310                for (String uidPackage : uidPackages) {
17311                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17312                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17313                    if (libIdx >= 0) {
17314                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17315                        versionsCallerCanSee.append(libVersion, libVersion);
17316                    }
17317                }
17318            }
17319        }
17320
17321        // Caller can see nothing - done
17322        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17323            return packageName;
17324        }
17325
17326        // Find the version the caller can see and the app version code
17327        SharedLibraryEntry highestVersion = null;
17328        final int versionCount = versionedLib.size();
17329        for (int i = 0; i < versionCount; i++) {
17330            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17331            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17332                    libEntry.info.getVersion()) < 0) {
17333                continue;
17334            }
17335            // TODO: We will change version code to long, so in the new API it is long
17336            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17337            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17338                if (libVersionCode == versionCode) {
17339                    return libEntry.apk;
17340                }
17341            } else if (highestVersion == null) {
17342                highestVersion = libEntry;
17343            } else if (libVersionCode  > highestVersion.info
17344                    .getDeclaringPackage().getVersionCode()) {
17345                highestVersion = libEntry;
17346            }
17347        }
17348
17349        if (highestVersion != null) {
17350            return highestVersion.apk;
17351        }
17352
17353        return packageName;
17354    }
17355
17356    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17357        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17358              || callingUid == Process.SYSTEM_UID) {
17359            return true;
17360        }
17361        final int callingUserId = UserHandle.getUserId(callingUid);
17362        // If the caller installed the pkgName, then allow it to silently uninstall.
17363        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17364            return true;
17365        }
17366
17367        // Allow package verifier to silently uninstall.
17368        if (mRequiredVerifierPackage != null &&
17369                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17370            return true;
17371        }
17372
17373        // Allow package uninstaller to silently uninstall.
17374        if (mRequiredUninstallerPackage != null &&
17375                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17376            return true;
17377        }
17378
17379        // Allow storage manager to silently uninstall.
17380        if (mStorageManagerPackage != null &&
17381                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17382            return true;
17383        }
17384        return false;
17385    }
17386
17387    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17388        int[] result = EMPTY_INT_ARRAY;
17389        for (int userId : userIds) {
17390            if (getBlockUninstallForUser(packageName, userId)) {
17391                result = ArrayUtils.appendInt(result, userId);
17392            }
17393        }
17394        return result;
17395    }
17396
17397    @Override
17398    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17399        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17400    }
17401
17402    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17403        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17404                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17405        try {
17406            if (dpm != null) {
17407                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17408                        /* callingUserOnly =*/ false);
17409                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17410                        : deviceOwnerComponentName.getPackageName();
17411                // Does the package contains the device owner?
17412                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17413                // this check is probably not needed, since DO should be registered as a device
17414                // admin on some user too. (Original bug for this: b/17657954)
17415                if (packageName.equals(deviceOwnerPackageName)) {
17416                    return true;
17417                }
17418                // Does it contain a device admin for any user?
17419                int[] users;
17420                if (userId == UserHandle.USER_ALL) {
17421                    users = sUserManager.getUserIds();
17422                } else {
17423                    users = new int[]{userId};
17424                }
17425                for (int i = 0; i < users.length; ++i) {
17426                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17427                        return true;
17428                    }
17429                }
17430            }
17431        } catch (RemoteException e) {
17432        }
17433        return false;
17434    }
17435
17436    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17437        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17438    }
17439
17440    /**
17441     *  This method is an internal method that could be get invoked either
17442     *  to delete an installed package or to clean up a failed installation.
17443     *  After deleting an installed package, a broadcast is sent to notify any
17444     *  listeners that the package has been removed. For cleaning up a failed
17445     *  installation, the broadcast is not necessary since the package's
17446     *  installation wouldn't have sent the initial broadcast either
17447     *  The key steps in deleting a package are
17448     *  deleting the package information in internal structures like mPackages,
17449     *  deleting the packages base directories through installd
17450     *  updating mSettings to reflect current status
17451     *  persisting settings for later use
17452     *  sending a broadcast if necessary
17453     */
17454    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17455        final PackageRemovedInfo info = new PackageRemovedInfo();
17456        final boolean res;
17457
17458        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17459                ? UserHandle.USER_ALL : userId;
17460
17461        if (isPackageDeviceAdmin(packageName, removeUser)) {
17462            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17463            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17464        }
17465
17466        PackageSetting uninstalledPs = null;
17467        PackageParser.Package pkg = null;
17468
17469        // for the uninstall-updates case and restricted profiles, remember the per-
17470        // user handle installed state
17471        int[] allUsers;
17472        synchronized (mPackages) {
17473            uninstalledPs = mSettings.mPackages.get(packageName);
17474            if (uninstalledPs == null) {
17475                Slog.w(TAG, "Not removing non-existent package " + packageName);
17476                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17477            }
17478
17479            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17480                    && uninstalledPs.versionCode != versionCode) {
17481                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17482                        + uninstalledPs.versionCode + " != " + versionCode);
17483                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17484            }
17485
17486            // Static shared libs can be declared by any package, so let us not
17487            // allow removing a package if it provides a lib others depend on.
17488            pkg = mPackages.get(packageName);
17489            if (pkg != null && pkg.staticSharedLibName != null) {
17490                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17491                        pkg.staticSharedLibVersion);
17492                if (libEntry != null) {
17493                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17494                            libEntry.info, 0, userId);
17495                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17496                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17497                                + " hosting lib " + libEntry.info.getName() + " version "
17498                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17499                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17500                    }
17501                }
17502            }
17503
17504            allUsers = sUserManager.getUserIds();
17505            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17506        }
17507
17508        final int freezeUser;
17509        if (isUpdatedSystemApp(uninstalledPs)
17510                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17511            // We're downgrading a system app, which will apply to all users, so
17512            // freeze them all during the downgrade
17513            freezeUser = UserHandle.USER_ALL;
17514        } else {
17515            freezeUser = removeUser;
17516        }
17517
17518        synchronized (mInstallLock) {
17519            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17520            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17521                    deleteFlags, "deletePackageX")) {
17522                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17523                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17524            }
17525            synchronized (mPackages) {
17526                if (res) {
17527                    if (pkg != null) {
17528                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17529                    }
17530                    updateSequenceNumberLP(packageName, info.removedUsers);
17531                    updateInstantAppInstallerLocked();
17532                }
17533            }
17534        }
17535
17536        if (res) {
17537            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17538            info.sendPackageRemovedBroadcasts(killApp);
17539            info.sendSystemPackageUpdatedBroadcasts();
17540            info.sendSystemPackageAppearedBroadcasts();
17541        }
17542        // Force a gc here.
17543        Runtime.getRuntime().gc();
17544        // Delete the resources here after sending the broadcast to let
17545        // other processes clean up before deleting resources.
17546        if (info.args != null) {
17547            synchronized (mInstallLock) {
17548                info.args.doPostDeleteLI(true);
17549            }
17550        }
17551
17552        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17553    }
17554
17555    class PackageRemovedInfo {
17556        String removedPackage;
17557        int uid = -1;
17558        int removedAppId = -1;
17559        int[] origUsers;
17560        int[] removedUsers = null;
17561        SparseArray<Integer> installReasons;
17562        boolean isRemovedPackageSystemUpdate = false;
17563        boolean isUpdate;
17564        boolean dataRemoved;
17565        boolean removedForAllUsers;
17566        boolean isStaticSharedLib;
17567        // Clean up resources deleted packages.
17568        InstallArgs args = null;
17569        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17570        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17571
17572        void sendPackageRemovedBroadcasts(boolean killApp) {
17573            sendPackageRemovedBroadcastInternal(killApp);
17574            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17575            for (int i = 0; i < childCount; i++) {
17576                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17577                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17578            }
17579        }
17580
17581        void sendSystemPackageUpdatedBroadcasts() {
17582            if (isRemovedPackageSystemUpdate) {
17583                sendSystemPackageUpdatedBroadcastsInternal();
17584                final int childCount = (removedChildPackages != null)
17585                        ? removedChildPackages.size() : 0;
17586                for (int i = 0; i < childCount; i++) {
17587                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17588                    if (childInfo.isRemovedPackageSystemUpdate) {
17589                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17590                    }
17591                }
17592            }
17593        }
17594
17595        void sendSystemPackageAppearedBroadcasts() {
17596            final int packageCount = (appearedChildPackages != null)
17597                    ? appearedChildPackages.size() : 0;
17598            for (int i = 0; i < packageCount; i++) {
17599                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17600                sendPackageAddedForNewUsers(installedInfo.name, true,
17601                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17602            }
17603        }
17604
17605        private void sendSystemPackageUpdatedBroadcastsInternal() {
17606            Bundle extras = new Bundle(2);
17607            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17608            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17609            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17610                    extras, 0, null, null, null);
17611            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17612                    extras, 0, null, null, null);
17613            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17614                    null, 0, removedPackage, null, null);
17615        }
17616
17617        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17618            // Don't send static shared library removal broadcasts as these
17619            // libs are visible only the the apps that depend on them an one
17620            // cannot remove the library if it has a dependency.
17621            if (isStaticSharedLib) {
17622                return;
17623            }
17624            Bundle extras = new Bundle(2);
17625            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17626            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17627            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17628            if (isUpdate || isRemovedPackageSystemUpdate) {
17629                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17630            }
17631            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17632            if (removedPackage != null) {
17633                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17634                        extras, 0, null, null, removedUsers);
17635                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17636                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17637                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17638                            null, null, removedUsers);
17639                }
17640            }
17641            if (removedAppId >= 0) {
17642                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17643                        removedUsers);
17644            }
17645        }
17646    }
17647
17648    /*
17649     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17650     * flag is not set, the data directory is removed as well.
17651     * make sure this flag is set for partially installed apps. If not its meaningless to
17652     * delete a partially installed application.
17653     */
17654    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17655            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17656        String packageName = ps.name;
17657        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17658        // Retrieve object to delete permissions for shared user later on
17659        final PackageParser.Package deletedPkg;
17660        final PackageSetting deletedPs;
17661        // reader
17662        synchronized (mPackages) {
17663            deletedPkg = mPackages.get(packageName);
17664            deletedPs = mSettings.mPackages.get(packageName);
17665            if (outInfo != null) {
17666                outInfo.removedPackage = packageName;
17667                outInfo.isStaticSharedLib = deletedPkg != null
17668                        && deletedPkg.staticSharedLibName != null;
17669                outInfo.removedUsers = deletedPs != null
17670                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17671                        : null;
17672            }
17673        }
17674
17675        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17676
17677        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17678            final PackageParser.Package resolvedPkg;
17679            if (deletedPkg != null) {
17680                resolvedPkg = deletedPkg;
17681            } else {
17682                // We don't have a parsed package when it lives on an ejected
17683                // adopted storage device, so fake something together
17684                resolvedPkg = new PackageParser.Package(ps.name);
17685                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17686            }
17687            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17688                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17689            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17690            if (outInfo != null) {
17691                outInfo.dataRemoved = true;
17692            }
17693            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17694        }
17695
17696        int removedAppId = -1;
17697
17698        // writer
17699        synchronized (mPackages) {
17700            boolean installedStateChanged = false;
17701            if (deletedPs != null) {
17702                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17703                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17704                    clearDefaultBrowserIfNeeded(packageName);
17705                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17706                    removedAppId = mSettings.removePackageLPw(packageName);
17707                    if (outInfo != null) {
17708                        outInfo.removedAppId = removedAppId;
17709                    }
17710                    updatePermissionsLPw(deletedPs.name, null, 0);
17711                    if (deletedPs.sharedUser != null) {
17712                        // Remove permissions associated with package. Since runtime
17713                        // permissions are per user we have to kill the removed package
17714                        // or packages running under the shared user of the removed
17715                        // package if revoking the permissions requested only by the removed
17716                        // package is successful and this causes a change in gids.
17717                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17718                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17719                                    userId);
17720                            if (userIdToKill == UserHandle.USER_ALL
17721                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17722                                // If gids changed for this user, kill all affected packages.
17723                                mHandler.post(new Runnable() {
17724                                    @Override
17725                                    public void run() {
17726                                        // This has to happen with no lock held.
17727                                        killApplication(deletedPs.name, deletedPs.appId,
17728                                                KILL_APP_REASON_GIDS_CHANGED);
17729                                    }
17730                                });
17731                                break;
17732                            }
17733                        }
17734                    }
17735                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17736                }
17737                // make sure to preserve per-user disabled state if this removal was just
17738                // a downgrade of a system app to the factory package
17739                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17740                    if (DEBUG_REMOVE) {
17741                        Slog.d(TAG, "Propagating install state across downgrade");
17742                    }
17743                    for (int userId : allUserHandles) {
17744                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17745                        if (DEBUG_REMOVE) {
17746                            Slog.d(TAG, "    user " + userId + " => " + installed);
17747                        }
17748                        if (installed != ps.getInstalled(userId)) {
17749                            installedStateChanged = true;
17750                        }
17751                        ps.setInstalled(installed, userId);
17752                    }
17753                }
17754            }
17755            // can downgrade to reader
17756            if (writeSettings) {
17757                // Save settings now
17758                mSettings.writeLPr();
17759            }
17760            if (installedStateChanged) {
17761                mSettings.writeKernelMappingLPr(ps);
17762            }
17763        }
17764        if (removedAppId != -1) {
17765            // A user ID was deleted here. Go through all users and remove it
17766            // from KeyStore.
17767            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17768        }
17769    }
17770
17771    static boolean locationIsPrivileged(File path) {
17772        try {
17773            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17774                    .getCanonicalPath();
17775            return path.getCanonicalPath().startsWith(privilegedAppDir);
17776        } catch (IOException e) {
17777            Slog.e(TAG, "Unable to access code path " + path);
17778        }
17779        return false;
17780    }
17781
17782    /*
17783     * Tries to delete system package.
17784     */
17785    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17786            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17787            boolean writeSettings) {
17788        if (deletedPs.parentPackageName != null) {
17789            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17790            return false;
17791        }
17792
17793        final boolean applyUserRestrictions
17794                = (allUserHandles != null) && (outInfo.origUsers != null);
17795        final PackageSetting disabledPs;
17796        // Confirm if the system package has been updated
17797        // An updated system app can be deleted. This will also have to restore
17798        // the system pkg from system partition
17799        // reader
17800        synchronized (mPackages) {
17801            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17802        }
17803
17804        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17805                + " disabledPs=" + disabledPs);
17806
17807        if (disabledPs == null) {
17808            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17809            return false;
17810        } else if (DEBUG_REMOVE) {
17811            Slog.d(TAG, "Deleting system pkg from data partition");
17812        }
17813
17814        if (DEBUG_REMOVE) {
17815            if (applyUserRestrictions) {
17816                Slog.d(TAG, "Remembering install states:");
17817                for (int userId : allUserHandles) {
17818                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17819                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17820                }
17821            }
17822        }
17823
17824        // Delete the updated package
17825        outInfo.isRemovedPackageSystemUpdate = true;
17826        if (outInfo.removedChildPackages != null) {
17827            final int childCount = (deletedPs.childPackageNames != null)
17828                    ? deletedPs.childPackageNames.size() : 0;
17829            for (int i = 0; i < childCount; i++) {
17830                String childPackageName = deletedPs.childPackageNames.get(i);
17831                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17832                        .contains(childPackageName)) {
17833                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17834                            childPackageName);
17835                    if (childInfo != null) {
17836                        childInfo.isRemovedPackageSystemUpdate = true;
17837                    }
17838                }
17839            }
17840        }
17841
17842        if (disabledPs.versionCode < deletedPs.versionCode) {
17843            // Delete data for downgrades
17844            flags &= ~PackageManager.DELETE_KEEP_DATA;
17845        } else {
17846            // Preserve data by setting flag
17847            flags |= PackageManager.DELETE_KEEP_DATA;
17848        }
17849
17850        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17851                outInfo, writeSettings, disabledPs.pkg);
17852        if (!ret) {
17853            return false;
17854        }
17855
17856        // writer
17857        synchronized (mPackages) {
17858            // Reinstate the old system package
17859            enableSystemPackageLPw(disabledPs.pkg);
17860            // Remove any native libraries from the upgraded package.
17861            removeNativeBinariesLI(deletedPs);
17862        }
17863
17864        // Install the system package
17865        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17866        int parseFlags = mDefParseFlags
17867                | PackageParser.PARSE_MUST_BE_APK
17868                | PackageParser.PARSE_IS_SYSTEM
17869                | PackageParser.PARSE_IS_SYSTEM_DIR;
17870        if (locationIsPrivileged(disabledPs.codePath)) {
17871            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17872        }
17873
17874        final PackageParser.Package newPkg;
17875        try {
17876            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17877                0 /* currentTime */, null);
17878        } catch (PackageManagerException e) {
17879            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17880                    + e.getMessage());
17881            return false;
17882        }
17883
17884        try {
17885            // update shared libraries for the newly re-installed system package
17886            updateSharedLibrariesLPr(newPkg, null);
17887        } catch (PackageManagerException e) {
17888            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17889        }
17890
17891        prepareAppDataAfterInstallLIF(newPkg);
17892
17893        // writer
17894        synchronized (mPackages) {
17895            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17896
17897            // Propagate the permissions state as we do not want to drop on the floor
17898            // runtime permissions. The update permissions method below will take
17899            // care of removing obsolete permissions and grant install permissions.
17900            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17901            updatePermissionsLPw(newPkg.packageName, newPkg,
17902                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17903
17904            if (applyUserRestrictions) {
17905                boolean installedStateChanged = false;
17906                if (DEBUG_REMOVE) {
17907                    Slog.d(TAG, "Propagating install state across reinstall");
17908                }
17909                for (int userId : allUserHandles) {
17910                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17911                    if (DEBUG_REMOVE) {
17912                        Slog.d(TAG, "    user " + userId + " => " + installed);
17913                    }
17914                    if (installed != ps.getInstalled(userId)) {
17915                        installedStateChanged = true;
17916                    }
17917                    ps.setInstalled(installed, userId);
17918
17919                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17920                }
17921                // Regardless of writeSettings we need to ensure that this restriction
17922                // state propagation is persisted
17923                mSettings.writeAllUsersPackageRestrictionsLPr();
17924                if (installedStateChanged) {
17925                    mSettings.writeKernelMappingLPr(ps);
17926                }
17927            }
17928            // can downgrade to reader here
17929            if (writeSettings) {
17930                mSettings.writeLPr();
17931            }
17932        }
17933        return true;
17934    }
17935
17936    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17937            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17938            PackageRemovedInfo outInfo, boolean writeSettings,
17939            PackageParser.Package replacingPackage) {
17940        synchronized (mPackages) {
17941            if (outInfo != null) {
17942                outInfo.uid = ps.appId;
17943            }
17944
17945            if (outInfo != null && outInfo.removedChildPackages != null) {
17946                final int childCount = (ps.childPackageNames != null)
17947                        ? ps.childPackageNames.size() : 0;
17948                for (int i = 0; i < childCount; i++) {
17949                    String childPackageName = ps.childPackageNames.get(i);
17950                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17951                    if (childPs == null) {
17952                        return false;
17953                    }
17954                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17955                            childPackageName);
17956                    if (childInfo != null) {
17957                        childInfo.uid = childPs.appId;
17958                    }
17959                }
17960            }
17961        }
17962
17963        // Delete package data from internal structures and also remove data if flag is set
17964        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17965
17966        // Delete the child packages data
17967        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17968        for (int i = 0; i < childCount; i++) {
17969            PackageSetting childPs;
17970            synchronized (mPackages) {
17971                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17972            }
17973            if (childPs != null) {
17974                PackageRemovedInfo childOutInfo = (outInfo != null
17975                        && outInfo.removedChildPackages != null)
17976                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17977                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17978                        && (replacingPackage != null
17979                        && !replacingPackage.hasChildPackage(childPs.name))
17980                        ? flags & ~DELETE_KEEP_DATA : flags;
17981                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17982                        deleteFlags, writeSettings);
17983            }
17984        }
17985
17986        // Delete application code and resources only for parent packages
17987        if (ps.parentPackageName == null) {
17988            if (deleteCodeAndResources && (outInfo != null)) {
17989                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17990                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17991                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17992            }
17993        }
17994
17995        return true;
17996    }
17997
17998    @Override
17999    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18000            int userId) {
18001        mContext.enforceCallingOrSelfPermission(
18002                android.Manifest.permission.DELETE_PACKAGES, null);
18003        synchronized (mPackages) {
18004            PackageSetting ps = mSettings.mPackages.get(packageName);
18005            if (ps == null) {
18006                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18007                return false;
18008            }
18009            // Cannot block uninstall of static shared libs as they are
18010            // considered a part of the using app (emulating static linking).
18011            // Also static libs are installed always on internal storage.
18012            PackageParser.Package pkg = mPackages.get(packageName);
18013            if (pkg != null && pkg.staticSharedLibName != null) {
18014                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18015                        + " providing static shared library: " + pkg.staticSharedLibName);
18016                return false;
18017            }
18018            if (!ps.getInstalled(userId)) {
18019                // Can't block uninstall for an app that is not installed or enabled.
18020                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18021                return false;
18022            }
18023            ps.setBlockUninstall(blockUninstall, userId);
18024            mSettings.writePackageRestrictionsLPr(userId);
18025        }
18026        return true;
18027    }
18028
18029    @Override
18030    public boolean getBlockUninstallForUser(String packageName, int userId) {
18031        synchronized (mPackages) {
18032            PackageSetting ps = mSettings.mPackages.get(packageName);
18033            if (ps == null) {
18034                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18035                return false;
18036            }
18037            return ps.getBlockUninstall(userId);
18038        }
18039    }
18040
18041    @Override
18042    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18043        int callingUid = Binder.getCallingUid();
18044        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18045            throw new SecurityException(
18046                    "setRequiredForSystemUser can only be run by the system or root");
18047        }
18048        synchronized (mPackages) {
18049            PackageSetting ps = mSettings.mPackages.get(packageName);
18050            if (ps == null) {
18051                Log.w(TAG, "Package doesn't exist: " + packageName);
18052                return false;
18053            }
18054            if (systemUserApp) {
18055                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18056            } else {
18057                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18058            }
18059            mSettings.writeLPr();
18060        }
18061        return true;
18062    }
18063
18064    /*
18065     * This method handles package deletion in general
18066     */
18067    private boolean deletePackageLIF(String packageName, UserHandle user,
18068            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18069            PackageRemovedInfo outInfo, boolean writeSettings,
18070            PackageParser.Package replacingPackage) {
18071        if (packageName == null) {
18072            Slog.w(TAG, "Attempt to delete null packageName.");
18073            return false;
18074        }
18075
18076        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18077
18078        PackageSetting ps;
18079        synchronized (mPackages) {
18080            ps = mSettings.mPackages.get(packageName);
18081            if (ps == null) {
18082                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18083                return false;
18084            }
18085
18086            if (ps.parentPackageName != null && (!isSystemApp(ps)
18087                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18088                if (DEBUG_REMOVE) {
18089                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18090                            + ((user == null) ? UserHandle.USER_ALL : user));
18091                }
18092                final int removedUserId = (user != null) ? user.getIdentifier()
18093                        : UserHandle.USER_ALL;
18094                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18095                    return false;
18096                }
18097                markPackageUninstalledForUserLPw(ps, user);
18098                scheduleWritePackageRestrictionsLocked(user);
18099                return true;
18100            }
18101        }
18102
18103        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18104                && user.getIdentifier() != UserHandle.USER_ALL)) {
18105            // The caller is asking that the package only be deleted for a single
18106            // user.  To do this, we just mark its uninstalled state and delete
18107            // its data. If this is a system app, we only allow this to happen if
18108            // they have set the special DELETE_SYSTEM_APP which requests different
18109            // semantics than normal for uninstalling system apps.
18110            markPackageUninstalledForUserLPw(ps, user);
18111
18112            if (!isSystemApp(ps)) {
18113                // Do not uninstall the APK if an app should be cached
18114                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18115                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18116                    // Other user still have this package installed, so all
18117                    // we need to do is clear this user's data and save that
18118                    // it is uninstalled.
18119                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18120                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18121                        return false;
18122                    }
18123                    scheduleWritePackageRestrictionsLocked(user);
18124                    return true;
18125                } else {
18126                    // We need to set it back to 'installed' so the uninstall
18127                    // broadcasts will be sent correctly.
18128                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18129                    ps.setInstalled(true, user.getIdentifier());
18130                    mSettings.writeKernelMappingLPr(ps);
18131                }
18132            } else {
18133                // This is a system app, so we assume that the
18134                // other users still have this package installed, so all
18135                // we need to do is clear this user's data and save that
18136                // it is uninstalled.
18137                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18138                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18139                    return false;
18140                }
18141                scheduleWritePackageRestrictionsLocked(user);
18142                return true;
18143            }
18144        }
18145
18146        // If we are deleting a composite package for all users, keep track
18147        // of result for each child.
18148        if (ps.childPackageNames != null && outInfo != null) {
18149            synchronized (mPackages) {
18150                final int childCount = ps.childPackageNames.size();
18151                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18152                for (int i = 0; i < childCount; i++) {
18153                    String childPackageName = ps.childPackageNames.get(i);
18154                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18155                    childInfo.removedPackage = childPackageName;
18156                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18157                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18158                    if (childPs != null) {
18159                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18160                    }
18161                }
18162            }
18163        }
18164
18165        boolean ret = false;
18166        if (isSystemApp(ps)) {
18167            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18168            // When an updated system application is deleted we delete the existing resources
18169            // as well and fall back to existing code in system partition
18170            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18171        } else {
18172            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18173            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18174                    outInfo, writeSettings, replacingPackage);
18175        }
18176
18177        // Take a note whether we deleted the package for all users
18178        if (outInfo != null) {
18179            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18180            if (outInfo.removedChildPackages != null) {
18181                synchronized (mPackages) {
18182                    final int childCount = outInfo.removedChildPackages.size();
18183                    for (int i = 0; i < childCount; i++) {
18184                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18185                        if (childInfo != null) {
18186                            childInfo.removedForAllUsers = mPackages.get(
18187                                    childInfo.removedPackage) == null;
18188                        }
18189                    }
18190                }
18191            }
18192            // If we uninstalled an update to a system app there may be some
18193            // child packages that appeared as they are declared in the system
18194            // app but were not declared in the update.
18195            if (isSystemApp(ps)) {
18196                synchronized (mPackages) {
18197                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18198                    final int childCount = (updatedPs.childPackageNames != null)
18199                            ? updatedPs.childPackageNames.size() : 0;
18200                    for (int i = 0; i < childCount; i++) {
18201                        String childPackageName = updatedPs.childPackageNames.get(i);
18202                        if (outInfo.removedChildPackages == null
18203                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18204                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18205                            if (childPs == null) {
18206                                continue;
18207                            }
18208                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18209                            installRes.name = childPackageName;
18210                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18211                            installRes.pkg = mPackages.get(childPackageName);
18212                            installRes.uid = childPs.pkg.applicationInfo.uid;
18213                            if (outInfo.appearedChildPackages == null) {
18214                                outInfo.appearedChildPackages = new ArrayMap<>();
18215                            }
18216                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18217                        }
18218                    }
18219                }
18220            }
18221        }
18222
18223        return ret;
18224    }
18225
18226    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18227        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18228                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18229        for (int nextUserId : userIds) {
18230            if (DEBUG_REMOVE) {
18231                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18232            }
18233            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18234                    false /*installed*/,
18235                    true /*stopped*/,
18236                    true /*notLaunched*/,
18237                    false /*hidden*/,
18238                    false /*suspended*/,
18239                    false /*instantApp*/,
18240                    null /*lastDisableAppCaller*/,
18241                    null /*enabledComponents*/,
18242                    null /*disabledComponents*/,
18243                    false /*blockUninstall*/,
18244                    ps.readUserState(nextUserId).domainVerificationStatus,
18245                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18246        }
18247        mSettings.writeKernelMappingLPr(ps);
18248    }
18249
18250    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18251            PackageRemovedInfo outInfo) {
18252        final PackageParser.Package pkg;
18253        synchronized (mPackages) {
18254            pkg = mPackages.get(ps.name);
18255        }
18256
18257        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18258                : new int[] {userId};
18259        for (int nextUserId : userIds) {
18260            if (DEBUG_REMOVE) {
18261                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18262                        + nextUserId);
18263            }
18264
18265            destroyAppDataLIF(pkg, userId,
18266                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18267            destroyAppProfilesLIF(pkg, userId);
18268            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18269            schedulePackageCleaning(ps.name, nextUserId, false);
18270            synchronized (mPackages) {
18271                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18272                    scheduleWritePackageRestrictionsLocked(nextUserId);
18273                }
18274                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18275            }
18276        }
18277
18278        if (outInfo != null) {
18279            outInfo.removedPackage = ps.name;
18280            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18281            outInfo.removedAppId = ps.appId;
18282            outInfo.removedUsers = userIds;
18283        }
18284
18285        return true;
18286    }
18287
18288    private final class ClearStorageConnection implements ServiceConnection {
18289        IMediaContainerService mContainerService;
18290
18291        @Override
18292        public void onServiceConnected(ComponentName name, IBinder service) {
18293            synchronized (this) {
18294                mContainerService = IMediaContainerService.Stub
18295                        .asInterface(Binder.allowBlocking(service));
18296                notifyAll();
18297            }
18298        }
18299
18300        @Override
18301        public void onServiceDisconnected(ComponentName name) {
18302        }
18303    }
18304
18305    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18306        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18307
18308        final boolean mounted;
18309        if (Environment.isExternalStorageEmulated()) {
18310            mounted = true;
18311        } else {
18312            final String status = Environment.getExternalStorageState();
18313
18314            mounted = status.equals(Environment.MEDIA_MOUNTED)
18315                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18316        }
18317
18318        if (!mounted) {
18319            return;
18320        }
18321
18322        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18323        int[] users;
18324        if (userId == UserHandle.USER_ALL) {
18325            users = sUserManager.getUserIds();
18326        } else {
18327            users = new int[] { userId };
18328        }
18329        final ClearStorageConnection conn = new ClearStorageConnection();
18330        if (mContext.bindServiceAsUser(
18331                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18332            try {
18333                for (int curUser : users) {
18334                    long timeout = SystemClock.uptimeMillis() + 5000;
18335                    synchronized (conn) {
18336                        long now;
18337                        while (conn.mContainerService == null &&
18338                                (now = SystemClock.uptimeMillis()) < timeout) {
18339                            try {
18340                                conn.wait(timeout - now);
18341                            } catch (InterruptedException e) {
18342                            }
18343                        }
18344                    }
18345                    if (conn.mContainerService == null) {
18346                        return;
18347                    }
18348
18349                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18350                    clearDirectory(conn.mContainerService,
18351                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18352                    if (allData) {
18353                        clearDirectory(conn.mContainerService,
18354                                userEnv.buildExternalStorageAppDataDirs(packageName));
18355                        clearDirectory(conn.mContainerService,
18356                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18357                    }
18358                }
18359            } finally {
18360                mContext.unbindService(conn);
18361            }
18362        }
18363    }
18364
18365    @Override
18366    public void clearApplicationProfileData(String packageName) {
18367        enforceSystemOrRoot("Only the system can clear all profile data");
18368
18369        final PackageParser.Package pkg;
18370        synchronized (mPackages) {
18371            pkg = mPackages.get(packageName);
18372        }
18373
18374        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18375            synchronized (mInstallLock) {
18376                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18377            }
18378        }
18379    }
18380
18381    @Override
18382    public void clearApplicationUserData(final String packageName,
18383            final IPackageDataObserver observer, final int userId) {
18384        mContext.enforceCallingOrSelfPermission(
18385                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18386
18387        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18388                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18389
18390        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18391            throw new SecurityException("Cannot clear data for a protected package: "
18392                    + packageName);
18393        }
18394        // Queue up an async operation since the package deletion may take a little while.
18395        mHandler.post(new Runnable() {
18396            public void run() {
18397                mHandler.removeCallbacks(this);
18398                final boolean succeeded;
18399                try (PackageFreezer freezer = freezePackage(packageName,
18400                        "clearApplicationUserData")) {
18401                    synchronized (mInstallLock) {
18402                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18403                    }
18404                    clearExternalStorageDataSync(packageName, userId, true);
18405                    synchronized (mPackages) {
18406                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18407                                packageName, userId);
18408                    }
18409                }
18410                if (succeeded) {
18411                    // invoke DeviceStorageMonitor's update method to clear any notifications
18412                    DeviceStorageMonitorInternal dsm = LocalServices
18413                            .getService(DeviceStorageMonitorInternal.class);
18414                    if (dsm != null) {
18415                        dsm.checkMemory();
18416                    }
18417                }
18418                if(observer != null) {
18419                    try {
18420                        observer.onRemoveCompleted(packageName, succeeded);
18421                    } catch (RemoteException e) {
18422                        Log.i(TAG, "Observer no longer exists.");
18423                    }
18424                } //end if observer
18425            } //end run
18426        });
18427    }
18428
18429    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18430        if (packageName == null) {
18431            Slog.w(TAG, "Attempt to delete null packageName.");
18432            return false;
18433        }
18434
18435        // Try finding details about the requested package
18436        PackageParser.Package pkg;
18437        synchronized (mPackages) {
18438            pkg = mPackages.get(packageName);
18439            if (pkg == null) {
18440                final PackageSetting ps = mSettings.mPackages.get(packageName);
18441                if (ps != null) {
18442                    pkg = ps.pkg;
18443                }
18444            }
18445
18446            if (pkg == null) {
18447                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18448                return false;
18449            }
18450
18451            PackageSetting ps = (PackageSetting) pkg.mExtras;
18452            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18453        }
18454
18455        clearAppDataLIF(pkg, userId,
18456                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18457
18458        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18459        removeKeystoreDataIfNeeded(userId, appId);
18460
18461        UserManagerInternal umInternal = getUserManagerInternal();
18462        final int flags;
18463        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18464            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18465        } else if (umInternal.isUserRunning(userId)) {
18466            flags = StorageManager.FLAG_STORAGE_DE;
18467        } else {
18468            flags = 0;
18469        }
18470        prepareAppDataContentsLIF(pkg, userId, flags);
18471
18472        return true;
18473    }
18474
18475    /**
18476     * Reverts user permission state changes (permissions and flags) in
18477     * all packages for a given user.
18478     *
18479     * @param userId The device user for which to do a reset.
18480     */
18481    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18482        final int packageCount = mPackages.size();
18483        for (int i = 0; i < packageCount; i++) {
18484            PackageParser.Package pkg = mPackages.valueAt(i);
18485            PackageSetting ps = (PackageSetting) pkg.mExtras;
18486            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18487        }
18488    }
18489
18490    private void resetNetworkPolicies(int userId) {
18491        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18492    }
18493
18494    /**
18495     * Reverts user permission state changes (permissions and flags).
18496     *
18497     * @param ps The package for which to reset.
18498     * @param userId The device user for which to do a reset.
18499     */
18500    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18501            final PackageSetting ps, final int userId) {
18502        if (ps.pkg == null) {
18503            return;
18504        }
18505
18506        // These are flags that can change base on user actions.
18507        final int userSettableMask = FLAG_PERMISSION_USER_SET
18508                | FLAG_PERMISSION_USER_FIXED
18509                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18510                | FLAG_PERMISSION_REVIEW_REQUIRED;
18511
18512        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18513                | FLAG_PERMISSION_POLICY_FIXED;
18514
18515        boolean writeInstallPermissions = false;
18516        boolean writeRuntimePermissions = false;
18517
18518        final int permissionCount = ps.pkg.requestedPermissions.size();
18519        for (int i = 0; i < permissionCount; i++) {
18520            String permission = ps.pkg.requestedPermissions.get(i);
18521
18522            BasePermission bp = mSettings.mPermissions.get(permission);
18523            if (bp == null) {
18524                continue;
18525            }
18526
18527            // If shared user we just reset the state to which only this app contributed.
18528            if (ps.sharedUser != null) {
18529                boolean used = false;
18530                final int packageCount = ps.sharedUser.packages.size();
18531                for (int j = 0; j < packageCount; j++) {
18532                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18533                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18534                            && pkg.pkg.requestedPermissions.contains(permission)) {
18535                        used = true;
18536                        break;
18537                    }
18538                }
18539                if (used) {
18540                    continue;
18541                }
18542            }
18543
18544            PermissionsState permissionsState = ps.getPermissionsState();
18545
18546            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18547
18548            // Always clear the user settable flags.
18549            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18550                    bp.name) != null;
18551            // If permission review is enabled and this is a legacy app, mark the
18552            // permission as requiring a review as this is the initial state.
18553            int flags = 0;
18554            if (mPermissionReviewRequired
18555                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18556                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18557            }
18558            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18559                if (hasInstallState) {
18560                    writeInstallPermissions = true;
18561                } else {
18562                    writeRuntimePermissions = true;
18563                }
18564            }
18565
18566            // Below is only runtime permission handling.
18567            if (!bp.isRuntime()) {
18568                continue;
18569            }
18570
18571            // Never clobber system or policy.
18572            if ((oldFlags & policyOrSystemFlags) != 0) {
18573                continue;
18574            }
18575
18576            // If this permission was granted by default, make sure it is.
18577            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18578                if (permissionsState.grantRuntimePermission(bp, userId)
18579                        != PERMISSION_OPERATION_FAILURE) {
18580                    writeRuntimePermissions = true;
18581                }
18582            // If permission review is enabled the permissions for a legacy apps
18583            // are represented as constantly granted runtime ones, so don't revoke.
18584            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18585                // Otherwise, reset the permission.
18586                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18587                switch (revokeResult) {
18588                    case PERMISSION_OPERATION_SUCCESS:
18589                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18590                        writeRuntimePermissions = true;
18591                        final int appId = ps.appId;
18592                        mHandler.post(new Runnable() {
18593                            @Override
18594                            public void run() {
18595                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18596                            }
18597                        });
18598                    } break;
18599                }
18600            }
18601        }
18602
18603        // Synchronously write as we are taking permissions away.
18604        if (writeRuntimePermissions) {
18605            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18606        }
18607
18608        // Synchronously write as we are taking permissions away.
18609        if (writeInstallPermissions) {
18610            mSettings.writeLPr();
18611        }
18612    }
18613
18614    /**
18615     * Remove entries from the keystore daemon. Will only remove it if the
18616     * {@code appId} is valid.
18617     */
18618    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18619        if (appId < 0) {
18620            return;
18621        }
18622
18623        final KeyStore keyStore = KeyStore.getInstance();
18624        if (keyStore != null) {
18625            if (userId == UserHandle.USER_ALL) {
18626                for (final int individual : sUserManager.getUserIds()) {
18627                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18628                }
18629            } else {
18630                keyStore.clearUid(UserHandle.getUid(userId, appId));
18631            }
18632        } else {
18633            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18634        }
18635    }
18636
18637    @Override
18638    public void deleteApplicationCacheFiles(final String packageName,
18639            final IPackageDataObserver observer) {
18640        final int userId = UserHandle.getCallingUserId();
18641        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18642    }
18643
18644    @Override
18645    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18646            final IPackageDataObserver observer) {
18647        mContext.enforceCallingOrSelfPermission(
18648                android.Manifest.permission.DELETE_CACHE_FILES, null);
18649        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18650                /* requireFullPermission= */ true, /* checkShell= */ false,
18651                "delete application cache files");
18652
18653        final PackageParser.Package pkg;
18654        synchronized (mPackages) {
18655            pkg = mPackages.get(packageName);
18656        }
18657
18658        // Queue up an async operation since the package deletion may take a little while.
18659        mHandler.post(new Runnable() {
18660            public void run() {
18661                synchronized (mInstallLock) {
18662                    final int flags = StorageManager.FLAG_STORAGE_DE
18663                            | StorageManager.FLAG_STORAGE_CE;
18664                    // We're only clearing cache files, so we don't care if the
18665                    // app is unfrozen and still able to run
18666                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18667                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18668                }
18669                clearExternalStorageDataSync(packageName, userId, false);
18670                if (observer != null) {
18671                    try {
18672                        observer.onRemoveCompleted(packageName, true);
18673                    } catch (RemoteException e) {
18674                        Log.i(TAG, "Observer no longer exists.");
18675                    }
18676                }
18677            }
18678        });
18679    }
18680
18681    @Override
18682    public void getPackageSizeInfo(final String packageName, int userHandle,
18683            final IPackageStatsObserver observer) {
18684        throw new UnsupportedOperationException(
18685                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18686    }
18687
18688    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18689        final PackageSetting ps;
18690        synchronized (mPackages) {
18691            ps = mSettings.mPackages.get(packageName);
18692            if (ps == null) {
18693                Slog.w(TAG, "Failed to find settings for " + packageName);
18694                return false;
18695            }
18696        }
18697
18698        final String[] packageNames = { packageName };
18699        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18700        final String[] codePaths = { ps.codePathString };
18701
18702        try {
18703            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18704                    ps.appId, ceDataInodes, codePaths, stats);
18705
18706            // For now, ignore code size of packages on system partition
18707            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18708                stats.codeSize = 0;
18709            }
18710
18711            // External clients expect these to be tracked separately
18712            stats.dataSize -= stats.cacheSize;
18713
18714        } catch (InstallerException e) {
18715            Slog.w(TAG, String.valueOf(e));
18716            return false;
18717        }
18718
18719        return true;
18720    }
18721
18722    private int getUidTargetSdkVersionLockedLPr(int uid) {
18723        Object obj = mSettings.getUserIdLPr(uid);
18724        if (obj instanceof SharedUserSetting) {
18725            final SharedUserSetting sus = (SharedUserSetting) obj;
18726            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18727            final Iterator<PackageSetting> it = sus.packages.iterator();
18728            while (it.hasNext()) {
18729                final PackageSetting ps = it.next();
18730                if (ps.pkg != null) {
18731                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18732                    if (v < vers) vers = v;
18733                }
18734            }
18735            return vers;
18736        } else if (obj instanceof PackageSetting) {
18737            final PackageSetting ps = (PackageSetting) obj;
18738            if (ps.pkg != null) {
18739                return ps.pkg.applicationInfo.targetSdkVersion;
18740            }
18741        }
18742        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18743    }
18744
18745    @Override
18746    public void addPreferredActivity(IntentFilter filter, int match,
18747            ComponentName[] set, ComponentName activity, int userId) {
18748        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18749                "Adding preferred");
18750    }
18751
18752    private void addPreferredActivityInternal(IntentFilter filter, int match,
18753            ComponentName[] set, ComponentName activity, boolean always, int userId,
18754            String opname) {
18755        // writer
18756        int callingUid = Binder.getCallingUid();
18757        enforceCrossUserPermission(callingUid, userId,
18758                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18759        if (filter.countActions() == 0) {
18760            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18761            return;
18762        }
18763        synchronized (mPackages) {
18764            if (mContext.checkCallingOrSelfPermission(
18765                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18766                    != PackageManager.PERMISSION_GRANTED) {
18767                if (getUidTargetSdkVersionLockedLPr(callingUid)
18768                        < Build.VERSION_CODES.FROYO) {
18769                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18770                            + callingUid);
18771                    return;
18772                }
18773                mContext.enforceCallingOrSelfPermission(
18774                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18775            }
18776
18777            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18778            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18779                    + userId + ":");
18780            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18781            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18782            scheduleWritePackageRestrictionsLocked(userId);
18783            postPreferredActivityChangedBroadcast(userId);
18784        }
18785    }
18786
18787    private void postPreferredActivityChangedBroadcast(int userId) {
18788        mHandler.post(() -> {
18789            final IActivityManager am = ActivityManager.getService();
18790            if (am == null) {
18791                return;
18792            }
18793
18794            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18795            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18796            try {
18797                am.broadcastIntent(null, intent, null, null,
18798                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18799                        null, false, false, userId);
18800            } catch (RemoteException e) {
18801            }
18802        });
18803    }
18804
18805    @Override
18806    public void replacePreferredActivity(IntentFilter filter, int match,
18807            ComponentName[] set, ComponentName activity, int userId) {
18808        if (filter.countActions() != 1) {
18809            throw new IllegalArgumentException(
18810                    "replacePreferredActivity expects filter to have only 1 action.");
18811        }
18812        if (filter.countDataAuthorities() != 0
18813                || filter.countDataPaths() != 0
18814                || filter.countDataSchemes() > 1
18815                || filter.countDataTypes() != 0) {
18816            throw new IllegalArgumentException(
18817                    "replacePreferredActivity expects filter to have no data authorities, " +
18818                    "paths, or types; and at most one scheme.");
18819        }
18820
18821        final int callingUid = Binder.getCallingUid();
18822        enforceCrossUserPermission(callingUid, userId,
18823                true /* requireFullPermission */, false /* checkShell */,
18824                "replace preferred activity");
18825        synchronized (mPackages) {
18826            if (mContext.checkCallingOrSelfPermission(
18827                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18828                    != PackageManager.PERMISSION_GRANTED) {
18829                if (getUidTargetSdkVersionLockedLPr(callingUid)
18830                        < Build.VERSION_CODES.FROYO) {
18831                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18832                            + Binder.getCallingUid());
18833                    return;
18834                }
18835                mContext.enforceCallingOrSelfPermission(
18836                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18837            }
18838
18839            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18840            if (pir != null) {
18841                // Get all of the existing entries that exactly match this filter.
18842                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18843                if (existing != null && existing.size() == 1) {
18844                    PreferredActivity cur = existing.get(0);
18845                    if (DEBUG_PREFERRED) {
18846                        Slog.i(TAG, "Checking replace of preferred:");
18847                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18848                        if (!cur.mPref.mAlways) {
18849                            Slog.i(TAG, "  -- CUR; not mAlways!");
18850                        } else {
18851                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18852                            Slog.i(TAG, "  -- CUR: mSet="
18853                                    + Arrays.toString(cur.mPref.mSetComponents));
18854                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18855                            Slog.i(TAG, "  -- NEW: mMatch="
18856                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18857                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18858                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18859                        }
18860                    }
18861                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18862                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18863                            && cur.mPref.sameSet(set)) {
18864                        // Setting the preferred activity to what it happens to be already
18865                        if (DEBUG_PREFERRED) {
18866                            Slog.i(TAG, "Replacing with same preferred activity "
18867                                    + cur.mPref.mShortComponent + " for user "
18868                                    + userId + ":");
18869                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18870                        }
18871                        return;
18872                    }
18873                }
18874
18875                if (existing != null) {
18876                    if (DEBUG_PREFERRED) {
18877                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18878                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18879                    }
18880                    for (int i = 0; i < existing.size(); i++) {
18881                        PreferredActivity pa = existing.get(i);
18882                        if (DEBUG_PREFERRED) {
18883                            Slog.i(TAG, "Removing existing preferred activity "
18884                                    + pa.mPref.mComponent + ":");
18885                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18886                        }
18887                        pir.removeFilter(pa);
18888                    }
18889                }
18890            }
18891            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18892                    "Replacing preferred");
18893        }
18894    }
18895
18896    @Override
18897    public void clearPackagePreferredActivities(String packageName) {
18898        final int uid = Binder.getCallingUid();
18899        // writer
18900        synchronized (mPackages) {
18901            PackageParser.Package pkg = mPackages.get(packageName);
18902            if (pkg == null || pkg.applicationInfo.uid != uid) {
18903                if (mContext.checkCallingOrSelfPermission(
18904                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18905                        != PackageManager.PERMISSION_GRANTED) {
18906                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18907                            < Build.VERSION_CODES.FROYO) {
18908                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18909                                + Binder.getCallingUid());
18910                        return;
18911                    }
18912                    mContext.enforceCallingOrSelfPermission(
18913                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18914                }
18915            }
18916
18917            int user = UserHandle.getCallingUserId();
18918            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18919                scheduleWritePackageRestrictionsLocked(user);
18920            }
18921        }
18922    }
18923
18924    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18925    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18926        ArrayList<PreferredActivity> removed = null;
18927        boolean changed = false;
18928        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18929            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18930            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18931            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18932                continue;
18933            }
18934            Iterator<PreferredActivity> it = pir.filterIterator();
18935            while (it.hasNext()) {
18936                PreferredActivity pa = it.next();
18937                // Mark entry for removal only if it matches the package name
18938                // and the entry is of type "always".
18939                if (packageName == null ||
18940                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18941                                && pa.mPref.mAlways)) {
18942                    if (removed == null) {
18943                        removed = new ArrayList<PreferredActivity>();
18944                    }
18945                    removed.add(pa);
18946                }
18947            }
18948            if (removed != null) {
18949                for (int j=0; j<removed.size(); j++) {
18950                    PreferredActivity pa = removed.get(j);
18951                    pir.removeFilter(pa);
18952                }
18953                changed = true;
18954            }
18955        }
18956        if (changed) {
18957            postPreferredActivityChangedBroadcast(userId);
18958        }
18959        return changed;
18960    }
18961
18962    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18963    private void clearIntentFilterVerificationsLPw(int userId) {
18964        final int packageCount = mPackages.size();
18965        for (int i = 0; i < packageCount; i++) {
18966            PackageParser.Package pkg = mPackages.valueAt(i);
18967            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18968        }
18969    }
18970
18971    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18972    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18973        if (userId == UserHandle.USER_ALL) {
18974            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18975                    sUserManager.getUserIds())) {
18976                for (int oneUserId : sUserManager.getUserIds()) {
18977                    scheduleWritePackageRestrictionsLocked(oneUserId);
18978                }
18979            }
18980        } else {
18981            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18982                scheduleWritePackageRestrictionsLocked(userId);
18983            }
18984        }
18985    }
18986
18987    void clearDefaultBrowserIfNeeded(String packageName) {
18988        for (int oneUserId : sUserManager.getUserIds()) {
18989            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18990            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18991            if (packageName.equals(defaultBrowserPackageName)) {
18992                setDefaultBrowserPackageName(null, oneUserId);
18993            }
18994        }
18995    }
18996
18997    @Override
18998    public void resetApplicationPreferences(int userId) {
18999        mContext.enforceCallingOrSelfPermission(
19000                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19001        final long identity = Binder.clearCallingIdentity();
19002        // writer
19003        try {
19004            synchronized (mPackages) {
19005                clearPackagePreferredActivitiesLPw(null, userId);
19006                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19007                // TODO: We have to reset the default SMS and Phone. This requires
19008                // significant refactoring to keep all default apps in the package
19009                // manager (cleaner but more work) or have the services provide
19010                // callbacks to the package manager to request a default app reset.
19011                applyFactoryDefaultBrowserLPw(userId);
19012                clearIntentFilterVerificationsLPw(userId);
19013                primeDomainVerificationsLPw(userId);
19014                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19015                scheduleWritePackageRestrictionsLocked(userId);
19016            }
19017            resetNetworkPolicies(userId);
19018        } finally {
19019            Binder.restoreCallingIdentity(identity);
19020        }
19021    }
19022
19023    @Override
19024    public int getPreferredActivities(List<IntentFilter> outFilters,
19025            List<ComponentName> outActivities, String packageName) {
19026
19027        int num = 0;
19028        final int userId = UserHandle.getCallingUserId();
19029        // reader
19030        synchronized (mPackages) {
19031            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19032            if (pir != null) {
19033                final Iterator<PreferredActivity> it = pir.filterIterator();
19034                while (it.hasNext()) {
19035                    final PreferredActivity pa = it.next();
19036                    if (packageName == null
19037                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19038                                    && pa.mPref.mAlways)) {
19039                        if (outFilters != null) {
19040                            outFilters.add(new IntentFilter(pa));
19041                        }
19042                        if (outActivities != null) {
19043                            outActivities.add(pa.mPref.mComponent);
19044                        }
19045                    }
19046                }
19047            }
19048        }
19049
19050        return num;
19051    }
19052
19053    @Override
19054    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19055            int userId) {
19056        int callingUid = Binder.getCallingUid();
19057        if (callingUid != Process.SYSTEM_UID) {
19058            throw new SecurityException(
19059                    "addPersistentPreferredActivity can only be run by the system");
19060        }
19061        if (filter.countActions() == 0) {
19062            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19063            return;
19064        }
19065        synchronized (mPackages) {
19066            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19067                    ":");
19068            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19069            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19070                    new PersistentPreferredActivity(filter, activity));
19071            scheduleWritePackageRestrictionsLocked(userId);
19072            postPreferredActivityChangedBroadcast(userId);
19073        }
19074    }
19075
19076    @Override
19077    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19078        int callingUid = Binder.getCallingUid();
19079        if (callingUid != Process.SYSTEM_UID) {
19080            throw new SecurityException(
19081                    "clearPackagePersistentPreferredActivities can only be run by the system");
19082        }
19083        ArrayList<PersistentPreferredActivity> removed = null;
19084        boolean changed = false;
19085        synchronized (mPackages) {
19086            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19087                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19088                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19089                        .valueAt(i);
19090                if (userId != thisUserId) {
19091                    continue;
19092                }
19093                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19094                while (it.hasNext()) {
19095                    PersistentPreferredActivity ppa = it.next();
19096                    // Mark entry for removal only if it matches the package name.
19097                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19098                        if (removed == null) {
19099                            removed = new ArrayList<PersistentPreferredActivity>();
19100                        }
19101                        removed.add(ppa);
19102                    }
19103                }
19104                if (removed != null) {
19105                    for (int j=0; j<removed.size(); j++) {
19106                        PersistentPreferredActivity ppa = removed.get(j);
19107                        ppir.removeFilter(ppa);
19108                    }
19109                    changed = true;
19110                }
19111            }
19112
19113            if (changed) {
19114                scheduleWritePackageRestrictionsLocked(userId);
19115                postPreferredActivityChangedBroadcast(userId);
19116            }
19117        }
19118    }
19119
19120    /**
19121     * Common machinery for picking apart a restored XML blob and passing
19122     * it to a caller-supplied functor to be applied to the running system.
19123     */
19124    private void restoreFromXml(XmlPullParser parser, int userId,
19125            String expectedStartTag, BlobXmlRestorer functor)
19126            throws IOException, XmlPullParserException {
19127        int type;
19128        while ((type = parser.next()) != XmlPullParser.START_TAG
19129                && type != XmlPullParser.END_DOCUMENT) {
19130        }
19131        if (type != XmlPullParser.START_TAG) {
19132            // oops didn't find a start tag?!
19133            if (DEBUG_BACKUP) {
19134                Slog.e(TAG, "Didn't find start tag during restore");
19135            }
19136            return;
19137        }
19138Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19139        // this is supposed to be TAG_PREFERRED_BACKUP
19140        if (!expectedStartTag.equals(parser.getName())) {
19141            if (DEBUG_BACKUP) {
19142                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19143            }
19144            return;
19145        }
19146
19147        // skip interfering stuff, then we're aligned with the backing implementation
19148        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19149Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19150        functor.apply(parser, userId);
19151    }
19152
19153    private interface BlobXmlRestorer {
19154        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19155    }
19156
19157    /**
19158     * Non-Binder method, support for the backup/restore mechanism: write the
19159     * full set of preferred activities in its canonical XML format.  Returns the
19160     * XML output as a byte array, or null if there is none.
19161     */
19162    @Override
19163    public byte[] getPreferredActivityBackup(int userId) {
19164        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19165            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19166        }
19167
19168        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19169        try {
19170            final XmlSerializer serializer = new FastXmlSerializer();
19171            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19172            serializer.startDocument(null, true);
19173            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19174
19175            synchronized (mPackages) {
19176                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19177            }
19178
19179            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19180            serializer.endDocument();
19181            serializer.flush();
19182        } catch (Exception e) {
19183            if (DEBUG_BACKUP) {
19184                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19185            }
19186            return null;
19187        }
19188
19189        return dataStream.toByteArray();
19190    }
19191
19192    @Override
19193    public void restorePreferredActivities(byte[] backup, int userId) {
19194        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19195            throw new SecurityException("Only the system may call restorePreferredActivities()");
19196        }
19197
19198        try {
19199            final XmlPullParser parser = Xml.newPullParser();
19200            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19201            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19202                    new BlobXmlRestorer() {
19203                        @Override
19204                        public void apply(XmlPullParser parser, int userId)
19205                                throws XmlPullParserException, IOException {
19206                            synchronized (mPackages) {
19207                                mSettings.readPreferredActivitiesLPw(parser, userId);
19208                            }
19209                        }
19210                    } );
19211        } catch (Exception e) {
19212            if (DEBUG_BACKUP) {
19213                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19214            }
19215        }
19216    }
19217
19218    /**
19219     * Non-Binder method, support for the backup/restore mechanism: write the
19220     * default browser (etc) settings in its canonical XML format.  Returns the default
19221     * browser XML representation as a byte array, or null if there is none.
19222     */
19223    @Override
19224    public byte[] getDefaultAppsBackup(int userId) {
19225        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19226            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19227        }
19228
19229        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19230        try {
19231            final XmlSerializer serializer = new FastXmlSerializer();
19232            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19233            serializer.startDocument(null, true);
19234            serializer.startTag(null, TAG_DEFAULT_APPS);
19235
19236            synchronized (mPackages) {
19237                mSettings.writeDefaultAppsLPr(serializer, userId);
19238            }
19239
19240            serializer.endTag(null, TAG_DEFAULT_APPS);
19241            serializer.endDocument();
19242            serializer.flush();
19243        } catch (Exception e) {
19244            if (DEBUG_BACKUP) {
19245                Slog.e(TAG, "Unable to write default apps for backup", e);
19246            }
19247            return null;
19248        }
19249
19250        return dataStream.toByteArray();
19251    }
19252
19253    @Override
19254    public void restoreDefaultApps(byte[] backup, int userId) {
19255        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19256            throw new SecurityException("Only the system may call restoreDefaultApps()");
19257        }
19258
19259        try {
19260            final XmlPullParser parser = Xml.newPullParser();
19261            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19262            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19263                    new BlobXmlRestorer() {
19264                        @Override
19265                        public void apply(XmlPullParser parser, int userId)
19266                                throws XmlPullParserException, IOException {
19267                            synchronized (mPackages) {
19268                                mSettings.readDefaultAppsLPw(parser, userId);
19269                            }
19270                        }
19271                    } );
19272        } catch (Exception e) {
19273            if (DEBUG_BACKUP) {
19274                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19275            }
19276        }
19277    }
19278
19279    @Override
19280    public byte[] getIntentFilterVerificationBackup(int userId) {
19281        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19282            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19283        }
19284
19285        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19286        try {
19287            final XmlSerializer serializer = new FastXmlSerializer();
19288            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19289            serializer.startDocument(null, true);
19290            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19291
19292            synchronized (mPackages) {
19293                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19294            }
19295
19296            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19297            serializer.endDocument();
19298            serializer.flush();
19299        } catch (Exception e) {
19300            if (DEBUG_BACKUP) {
19301                Slog.e(TAG, "Unable to write default apps for backup", e);
19302            }
19303            return null;
19304        }
19305
19306        return dataStream.toByteArray();
19307    }
19308
19309    @Override
19310    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19311        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19312            throw new SecurityException("Only the system may call restorePreferredActivities()");
19313        }
19314
19315        try {
19316            final XmlPullParser parser = Xml.newPullParser();
19317            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19318            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19319                    new BlobXmlRestorer() {
19320                        @Override
19321                        public void apply(XmlPullParser parser, int userId)
19322                                throws XmlPullParserException, IOException {
19323                            synchronized (mPackages) {
19324                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19325                                mSettings.writeLPr();
19326                            }
19327                        }
19328                    } );
19329        } catch (Exception e) {
19330            if (DEBUG_BACKUP) {
19331                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19332            }
19333        }
19334    }
19335
19336    @Override
19337    public byte[] getPermissionGrantBackup(int userId) {
19338        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19339            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19340        }
19341
19342        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19343        try {
19344            final XmlSerializer serializer = new FastXmlSerializer();
19345            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19346            serializer.startDocument(null, true);
19347            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19348
19349            synchronized (mPackages) {
19350                serializeRuntimePermissionGrantsLPr(serializer, userId);
19351            }
19352
19353            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19354            serializer.endDocument();
19355            serializer.flush();
19356        } catch (Exception e) {
19357            if (DEBUG_BACKUP) {
19358                Slog.e(TAG, "Unable to write default apps for backup", e);
19359            }
19360            return null;
19361        }
19362
19363        return dataStream.toByteArray();
19364    }
19365
19366    @Override
19367    public void restorePermissionGrants(byte[] backup, int userId) {
19368        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19369            throw new SecurityException("Only the system may call restorePermissionGrants()");
19370        }
19371
19372        try {
19373            final XmlPullParser parser = Xml.newPullParser();
19374            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19375            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19376                    new BlobXmlRestorer() {
19377                        @Override
19378                        public void apply(XmlPullParser parser, int userId)
19379                                throws XmlPullParserException, IOException {
19380                            synchronized (mPackages) {
19381                                processRestoredPermissionGrantsLPr(parser, userId);
19382                            }
19383                        }
19384                    } );
19385        } catch (Exception e) {
19386            if (DEBUG_BACKUP) {
19387                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19388            }
19389        }
19390    }
19391
19392    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19393            throws IOException {
19394        serializer.startTag(null, TAG_ALL_GRANTS);
19395
19396        final int N = mSettings.mPackages.size();
19397        for (int i = 0; i < N; i++) {
19398            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19399            boolean pkgGrantsKnown = false;
19400
19401            PermissionsState packagePerms = ps.getPermissionsState();
19402
19403            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19404                final int grantFlags = state.getFlags();
19405                // only look at grants that are not system/policy fixed
19406                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19407                    final boolean isGranted = state.isGranted();
19408                    // And only back up the user-twiddled state bits
19409                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19410                        final String packageName = mSettings.mPackages.keyAt(i);
19411                        if (!pkgGrantsKnown) {
19412                            serializer.startTag(null, TAG_GRANT);
19413                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19414                            pkgGrantsKnown = true;
19415                        }
19416
19417                        final boolean userSet =
19418                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19419                        final boolean userFixed =
19420                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19421                        final boolean revoke =
19422                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19423
19424                        serializer.startTag(null, TAG_PERMISSION);
19425                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19426                        if (isGranted) {
19427                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19428                        }
19429                        if (userSet) {
19430                            serializer.attribute(null, ATTR_USER_SET, "true");
19431                        }
19432                        if (userFixed) {
19433                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19434                        }
19435                        if (revoke) {
19436                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19437                        }
19438                        serializer.endTag(null, TAG_PERMISSION);
19439                    }
19440                }
19441            }
19442
19443            if (pkgGrantsKnown) {
19444                serializer.endTag(null, TAG_GRANT);
19445            }
19446        }
19447
19448        serializer.endTag(null, TAG_ALL_GRANTS);
19449    }
19450
19451    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19452            throws XmlPullParserException, IOException {
19453        String pkgName = null;
19454        int outerDepth = parser.getDepth();
19455        int type;
19456        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19457                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19458            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19459                continue;
19460            }
19461
19462            final String tagName = parser.getName();
19463            if (tagName.equals(TAG_GRANT)) {
19464                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19465                if (DEBUG_BACKUP) {
19466                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19467                }
19468            } else if (tagName.equals(TAG_PERMISSION)) {
19469
19470                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19471                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19472
19473                int newFlagSet = 0;
19474                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19475                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19476                }
19477                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19478                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19479                }
19480                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19481                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19482                }
19483                if (DEBUG_BACKUP) {
19484                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19485                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19486                }
19487                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19488                if (ps != null) {
19489                    // Already installed so we apply the grant immediately
19490                    if (DEBUG_BACKUP) {
19491                        Slog.v(TAG, "        + already installed; applying");
19492                    }
19493                    PermissionsState perms = ps.getPermissionsState();
19494                    BasePermission bp = mSettings.mPermissions.get(permName);
19495                    if (bp != null) {
19496                        if (isGranted) {
19497                            perms.grantRuntimePermission(bp, userId);
19498                        }
19499                        if (newFlagSet != 0) {
19500                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19501                        }
19502                    }
19503                } else {
19504                    // Need to wait for post-restore install to apply the grant
19505                    if (DEBUG_BACKUP) {
19506                        Slog.v(TAG, "        - not yet installed; saving for later");
19507                    }
19508                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19509                            isGranted, newFlagSet, userId);
19510                }
19511            } else {
19512                PackageManagerService.reportSettingsProblem(Log.WARN,
19513                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19514                XmlUtils.skipCurrentTag(parser);
19515            }
19516        }
19517
19518        scheduleWriteSettingsLocked();
19519        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19520    }
19521
19522    @Override
19523    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19524            int sourceUserId, int targetUserId, int flags) {
19525        mContext.enforceCallingOrSelfPermission(
19526                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19527        int callingUid = Binder.getCallingUid();
19528        enforceOwnerRights(ownerPackage, callingUid);
19529        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19530        if (intentFilter.countActions() == 0) {
19531            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19532            return;
19533        }
19534        synchronized (mPackages) {
19535            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19536                    ownerPackage, targetUserId, flags);
19537            CrossProfileIntentResolver resolver =
19538                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19539            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19540            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19541            if (existing != null) {
19542                int size = existing.size();
19543                for (int i = 0; i < size; i++) {
19544                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19545                        return;
19546                    }
19547                }
19548            }
19549            resolver.addFilter(newFilter);
19550            scheduleWritePackageRestrictionsLocked(sourceUserId);
19551        }
19552    }
19553
19554    @Override
19555    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19556        mContext.enforceCallingOrSelfPermission(
19557                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19558        int callingUid = Binder.getCallingUid();
19559        enforceOwnerRights(ownerPackage, callingUid);
19560        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19561        synchronized (mPackages) {
19562            CrossProfileIntentResolver resolver =
19563                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19564            ArraySet<CrossProfileIntentFilter> set =
19565                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19566            for (CrossProfileIntentFilter filter : set) {
19567                if (filter.getOwnerPackage().equals(ownerPackage)) {
19568                    resolver.removeFilter(filter);
19569                }
19570            }
19571            scheduleWritePackageRestrictionsLocked(sourceUserId);
19572        }
19573    }
19574
19575    // Enforcing that callingUid is owning pkg on userId
19576    private void enforceOwnerRights(String pkg, int callingUid) {
19577        // The system owns everything.
19578        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19579            return;
19580        }
19581        int callingUserId = UserHandle.getUserId(callingUid);
19582        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19583        if (pi == null) {
19584            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19585                    + callingUserId);
19586        }
19587        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19588            throw new SecurityException("Calling uid " + callingUid
19589                    + " does not own package " + pkg);
19590        }
19591    }
19592
19593    @Override
19594    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19595        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19596    }
19597
19598    /**
19599     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19600     * then reports the most likely home activity or null if there are more than one.
19601     */
19602    public ComponentName getDefaultHomeActivity(int userId) {
19603        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19604        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19605        if (cn != null) {
19606            return cn;
19607        }
19608
19609        // Find the launcher with the highest priority and return that component if there are no
19610        // other home activity with the same priority.
19611        int lastPriority = Integer.MIN_VALUE;
19612        ComponentName lastComponent = null;
19613        final int size = allHomeCandidates.size();
19614        for (int i = 0; i < size; i++) {
19615            final ResolveInfo ri = allHomeCandidates.get(i);
19616            if (ri.priority > lastPriority) {
19617                lastComponent = ri.activityInfo.getComponentName();
19618                lastPriority = ri.priority;
19619            } else if (ri.priority == lastPriority) {
19620                // Two components found with same priority.
19621                lastComponent = null;
19622            }
19623        }
19624        return lastComponent;
19625    }
19626
19627    private Intent getHomeIntent() {
19628        Intent intent = new Intent(Intent.ACTION_MAIN);
19629        intent.addCategory(Intent.CATEGORY_HOME);
19630        intent.addCategory(Intent.CATEGORY_DEFAULT);
19631        return intent;
19632    }
19633
19634    private IntentFilter getHomeFilter() {
19635        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19636        filter.addCategory(Intent.CATEGORY_HOME);
19637        filter.addCategory(Intent.CATEGORY_DEFAULT);
19638        return filter;
19639    }
19640
19641    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19642            int userId) {
19643        Intent intent  = getHomeIntent();
19644        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19645                PackageManager.GET_META_DATA, userId);
19646        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19647                true, false, false, userId);
19648
19649        allHomeCandidates.clear();
19650        if (list != null) {
19651            for (ResolveInfo ri : list) {
19652                allHomeCandidates.add(ri);
19653            }
19654        }
19655        return (preferred == null || preferred.activityInfo == null)
19656                ? null
19657                : new ComponentName(preferred.activityInfo.packageName,
19658                        preferred.activityInfo.name);
19659    }
19660
19661    @Override
19662    public void setHomeActivity(ComponentName comp, int userId) {
19663        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19664        getHomeActivitiesAsUser(homeActivities, userId);
19665
19666        boolean found = false;
19667
19668        final int size = homeActivities.size();
19669        final ComponentName[] set = new ComponentName[size];
19670        for (int i = 0; i < size; i++) {
19671            final ResolveInfo candidate = homeActivities.get(i);
19672            final ActivityInfo info = candidate.activityInfo;
19673            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19674            set[i] = activityName;
19675            if (!found && activityName.equals(comp)) {
19676                found = true;
19677            }
19678        }
19679        if (!found) {
19680            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19681                    + userId);
19682        }
19683        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19684                set, comp, userId);
19685    }
19686
19687    private @Nullable String getSetupWizardPackageName() {
19688        final Intent intent = new Intent(Intent.ACTION_MAIN);
19689        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19690
19691        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19692                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19693                        | MATCH_DISABLED_COMPONENTS,
19694                UserHandle.myUserId());
19695        if (matches.size() == 1) {
19696            return matches.get(0).getComponentInfo().packageName;
19697        } else {
19698            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19699                    + ": matches=" + matches);
19700            return null;
19701        }
19702    }
19703
19704    private @Nullable String getStorageManagerPackageName() {
19705        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19706
19707        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19708                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19709                        | MATCH_DISABLED_COMPONENTS,
19710                UserHandle.myUserId());
19711        if (matches.size() == 1) {
19712            return matches.get(0).getComponentInfo().packageName;
19713        } else {
19714            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19715                    + matches.size() + ": matches=" + matches);
19716            return null;
19717        }
19718    }
19719
19720    @Override
19721    public void setApplicationEnabledSetting(String appPackageName,
19722            int newState, int flags, int userId, String callingPackage) {
19723        if (!sUserManager.exists(userId)) return;
19724        if (callingPackage == null) {
19725            callingPackage = Integer.toString(Binder.getCallingUid());
19726        }
19727        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19728    }
19729
19730    @Override
19731    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19732        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19733        synchronized (mPackages) {
19734            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19735            if (pkgSetting != null) {
19736                pkgSetting.setUpdateAvailable(updateAvailable);
19737            }
19738        }
19739    }
19740
19741    @Override
19742    public void setComponentEnabledSetting(ComponentName componentName,
19743            int newState, int flags, int userId) {
19744        if (!sUserManager.exists(userId)) return;
19745        setEnabledSetting(componentName.getPackageName(),
19746                componentName.getClassName(), newState, flags, userId, null);
19747    }
19748
19749    private void setEnabledSetting(final String packageName, String className, int newState,
19750            final int flags, int userId, String callingPackage) {
19751        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19752              || newState == COMPONENT_ENABLED_STATE_ENABLED
19753              || newState == COMPONENT_ENABLED_STATE_DISABLED
19754              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19755              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19756            throw new IllegalArgumentException("Invalid new component state: "
19757                    + newState);
19758        }
19759        PackageSetting pkgSetting;
19760        final int uid = Binder.getCallingUid();
19761        final int permission;
19762        if (uid == Process.SYSTEM_UID) {
19763            permission = PackageManager.PERMISSION_GRANTED;
19764        } else {
19765            permission = mContext.checkCallingOrSelfPermission(
19766                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19767        }
19768        enforceCrossUserPermission(uid, userId,
19769                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19770        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19771        boolean sendNow = false;
19772        boolean isApp = (className == null);
19773        String componentName = isApp ? packageName : className;
19774        int packageUid = -1;
19775        ArrayList<String> components;
19776
19777        // writer
19778        synchronized (mPackages) {
19779            pkgSetting = mSettings.mPackages.get(packageName);
19780            if (pkgSetting == null) {
19781                if (className == null) {
19782                    throw new IllegalArgumentException("Unknown package: " + packageName);
19783                }
19784                throw new IllegalArgumentException(
19785                        "Unknown component: " + packageName + "/" + className);
19786            }
19787        }
19788
19789        // Limit who can change which apps
19790        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19791            // Don't allow apps that don't have permission to modify other apps
19792            if (!allowedByPermission) {
19793                throw new SecurityException(
19794                        "Permission Denial: attempt to change component state from pid="
19795                        + Binder.getCallingPid()
19796                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19797            }
19798            // Don't allow changing protected packages.
19799            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19800                throw new SecurityException("Cannot disable a protected package: " + packageName);
19801            }
19802        }
19803
19804        synchronized (mPackages) {
19805            if (uid == Process.SHELL_UID
19806                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19807                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19808                // unless it is a test package.
19809                int oldState = pkgSetting.getEnabled(userId);
19810                if (className == null
19811                    &&
19812                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19813                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19814                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19815                    &&
19816                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19817                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19818                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19819                    // ok
19820                } else {
19821                    throw new SecurityException(
19822                            "Shell cannot change component state for " + packageName + "/"
19823                            + className + " to " + newState);
19824                }
19825            }
19826            if (className == null) {
19827                // We're dealing with an application/package level state change
19828                if (pkgSetting.getEnabled(userId) == newState) {
19829                    // Nothing to do
19830                    return;
19831                }
19832                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19833                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19834                    // Don't care about who enables an app.
19835                    callingPackage = null;
19836                }
19837                pkgSetting.setEnabled(newState, userId, callingPackage);
19838                // pkgSetting.pkg.mSetEnabled = newState;
19839            } else {
19840                // We're dealing with a component level state change
19841                // First, verify that this is a valid class name.
19842                PackageParser.Package pkg = pkgSetting.pkg;
19843                if (pkg == null || !pkg.hasComponentClassName(className)) {
19844                    if (pkg != null &&
19845                            pkg.applicationInfo.targetSdkVersion >=
19846                                    Build.VERSION_CODES.JELLY_BEAN) {
19847                        throw new IllegalArgumentException("Component class " + className
19848                                + " does not exist in " + packageName);
19849                    } else {
19850                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19851                                + className + " does not exist in " + packageName);
19852                    }
19853                }
19854                switch (newState) {
19855                case COMPONENT_ENABLED_STATE_ENABLED:
19856                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19857                        return;
19858                    }
19859                    break;
19860                case COMPONENT_ENABLED_STATE_DISABLED:
19861                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19862                        return;
19863                    }
19864                    break;
19865                case COMPONENT_ENABLED_STATE_DEFAULT:
19866                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19867                        return;
19868                    }
19869                    break;
19870                default:
19871                    Slog.e(TAG, "Invalid new component state: " + newState);
19872                    return;
19873                }
19874            }
19875            scheduleWritePackageRestrictionsLocked(userId);
19876            updateSequenceNumberLP(packageName, new int[] { userId });
19877            final long callingId = Binder.clearCallingIdentity();
19878            try {
19879                updateInstantAppInstallerLocked();
19880            } finally {
19881                Binder.restoreCallingIdentity(callingId);
19882            }
19883            components = mPendingBroadcasts.get(userId, packageName);
19884            final boolean newPackage = components == null;
19885            if (newPackage) {
19886                components = new ArrayList<String>();
19887            }
19888            if (!components.contains(componentName)) {
19889                components.add(componentName);
19890            }
19891            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19892                sendNow = true;
19893                // Purge entry from pending broadcast list if another one exists already
19894                // since we are sending one right away.
19895                mPendingBroadcasts.remove(userId, packageName);
19896            } else {
19897                if (newPackage) {
19898                    mPendingBroadcasts.put(userId, packageName, components);
19899                }
19900                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19901                    // Schedule a message
19902                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19903                }
19904            }
19905        }
19906
19907        long callingId = Binder.clearCallingIdentity();
19908        try {
19909            if (sendNow) {
19910                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19911                sendPackageChangedBroadcast(packageName,
19912                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19913            }
19914        } finally {
19915            Binder.restoreCallingIdentity(callingId);
19916        }
19917    }
19918
19919    @Override
19920    public void flushPackageRestrictionsAsUser(int userId) {
19921        if (!sUserManager.exists(userId)) {
19922            return;
19923        }
19924        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19925                false /* checkShell */, "flushPackageRestrictions");
19926        synchronized (mPackages) {
19927            mSettings.writePackageRestrictionsLPr(userId);
19928            mDirtyUsers.remove(userId);
19929            if (mDirtyUsers.isEmpty()) {
19930                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19931            }
19932        }
19933    }
19934
19935    private void sendPackageChangedBroadcast(String packageName,
19936            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19937        if (DEBUG_INSTALL)
19938            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19939                    + componentNames);
19940        Bundle extras = new Bundle(4);
19941        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19942        String nameList[] = new String[componentNames.size()];
19943        componentNames.toArray(nameList);
19944        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19945        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19946        extras.putInt(Intent.EXTRA_UID, packageUid);
19947        // If this is not reporting a change of the overall package, then only send it
19948        // to registered receivers.  We don't want to launch a swath of apps for every
19949        // little component state change.
19950        final int flags = !componentNames.contains(packageName)
19951                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19952        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19953                new int[] {UserHandle.getUserId(packageUid)});
19954    }
19955
19956    @Override
19957    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19958        if (!sUserManager.exists(userId)) return;
19959        final int uid = Binder.getCallingUid();
19960        final int permission = mContext.checkCallingOrSelfPermission(
19961                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19962        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19963        enforceCrossUserPermission(uid, userId,
19964                true /* requireFullPermission */, true /* checkShell */, "stop package");
19965        // writer
19966        synchronized (mPackages) {
19967            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19968                    allowedByPermission, uid, userId)) {
19969                scheduleWritePackageRestrictionsLocked(userId);
19970            }
19971        }
19972    }
19973
19974    @Override
19975    public String getInstallerPackageName(String packageName) {
19976        // reader
19977        synchronized (mPackages) {
19978            return mSettings.getInstallerPackageNameLPr(packageName);
19979        }
19980    }
19981
19982    public boolean isOrphaned(String packageName) {
19983        // reader
19984        synchronized (mPackages) {
19985            return mSettings.isOrphaned(packageName);
19986        }
19987    }
19988
19989    @Override
19990    public int getApplicationEnabledSetting(String packageName, int userId) {
19991        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19992        int uid = Binder.getCallingUid();
19993        enforceCrossUserPermission(uid, userId,
19994                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19995        // reader
19996        synchronized (mPackages) {
19997            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19998        }
19999    }
20000
20001    @Override
20002    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20003        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20004        int uid = Binder.getCallingUid();
20005        enforceCrossUserPermission(uid, userId,
20006                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20007        // reader
20008        synchronized (mPackages) {
20009            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20010        }
20011    }
20012
20013    @Override
20014    public void enterSafeMode() {
20015        enforceSystemOrRoot("Only the system can request entering safe mode");
20016
20017        if (!mSystemReady) {
20018            mSafeMode = true;
20019        }
20020    }
20021
20022    @Override
20023    public void systemReady() {
20024        mSystemReady = true;
20025
20026        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20027        // disabled after already being started.
20028        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20029                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20030
20031        // Read the compatibilty setting when the system is ready.
20032        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20033                mContext.getContentResolver(),
20034                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20035        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20036        if (DEBUG_SETTINGS) {
20037            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20038        }
20039
20040        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20041
20042        synchronized (mPackages) {
20043            // Verify that all of the preferred activity components actually
20044            // exist.  It is possible for applications to be updated and at
20045            // that point remove a previously declared activity component that
20046            // had been set as a preferred activity.  We try to clean this up
20047            // the next time we encounter that preferred activity, but it is
20048            // possible for the user flow to never be able to return to that
20049            // situation so here we do a sanity check to make sure we haven't
20050            // left any junk around.
20051            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20052            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20053                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20054                removed.clear();
20055                for (PreferredActivity pa : pir.filterSet()) {
20056                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20057                        removed.add(pa);
20058                    }
20059                }
20060                if (removed.size() > 0) {
20061                    for (int r=0; r<removed.size(); r++) {
20062                        PreferredActivity pa = removed.get(r);
20063                        Slog.w(TAG, "Removing dangling preferred activity: "
20064                                + pa.mPref.mComponent);
20065                        pir.removeFilter(pa);
20066                    }
20067                    mSettings.writePackageRestrictionsLPr(
20068                            mSettings.mPreferredActivities.keyAt(i));
20069                }
20070            }
20071
20072            for (int userId : UserManagerService.getInstance().getUserIds()) {
20073                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20074                    grantPermissionsUserIds = ArrayUtils.appendInt(
20075                            grantPermissionsUserIds, userId);
20076                }
20077            }
20078        }
20079        sUserManager.systemReady();
20080
20081        // If we upgraded grant all default permissions before kicking off.
20082        for (int userId : grantPermissionsUserIds) {
20083            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20084        }
20085
20086        // If we did not grant default permissions, we preload from this the
20087        // default permission exceptions lazily to ensure we don't hit the
20088        // disk on a new user creation.
20089        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20090            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20091        }
20092
20093        // Kick off any messages waiting for system ready
20094        if (mPostSystemReadyMessages != null) {
20095            for (Message msg : mPostSystemReadyMessages) {
20096                msg.sendToTarget();
20097            }
20098            mPostSystemReadyMessages = null;
20099        }
20100
20101        // Watch for external volumes that come and go over time
20102        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20103        storage.registerListener(mStorageListener);
20104
20105        mInstallerService.systemReady();
20106        mPackageDexOptimizer.systemReady();
20107
20108        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20109                StorageManagerInternal.class);
20110        StorageManagerInternal.addExternalStoragePolicy(
20111                new StorageManagerInternal.ExternalStorageMountPolicy() {
20112            @Override
20113            public int getMountMode(int uid, String packageName) {
20114                if (Process.isIsolated(uid)) {
20115                    return Zygote.MOUNT_EXTERNAL_NONE;
20116                }
20117                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20118                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20119                }
20120                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20121                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20122                }
20123                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20124                    return Zygote.MOUNT_EXTERNAL_READ;
20125                }
20126                return Zygote.MOUNT_EXTERNAL_WRITE;
20127            }
20128
20129            @Override
20130            public boolean hasExternalStorage(int uid, String packageName) {
20131                return true;
20132            }
20133        });
20134
20135        // Now that we're mostly running, clean up stale users and apps
20136        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20137        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20138
20139        if (mPrivappPermissionsViolations != null) {
20140            Slog.wtf(TAG,"Signature|privileged permissions not in "
20141                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20142            mPrivappPermissionsViolations = null;
20143        }
20144    }
20145
20146    public void waitForAppDataPrepared() {
20147        if (mPrepareAppDataFuture == null) {
20148            return;
20149        }
20150        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20151        mPrepareAppDataFuture = null;
20152    }
20153
20154    @Override
20155    public boolean isSafeMode() {
20156        return mSafeMode;
20157    }
20158
20159    @Override
20160    public boolean hasSystemUidErrors() {
20161        return mHasSystemUidErrors;
20162    }
20163
20164    static String arrayToString(int[] array) {
20165        StringBuffer buf = new StringBuffer(128);
20166        buf.append('[');
20167        if (array != null) {
20168            for (int i=0; i<array.length; i++) {
20169                if (i > 0) buf.append(", ");
20170                buf.append(array[i]);
20171            }
20172        }
20173        buf.append(']');
20174        return buf.toString();
20175    }
20176
20177    static class DumpState {
20178        public static final int DUMP_LIBS = 1 << 0;
20179        public static final int DUMP_FEATURES = 1 << 1;
20180        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20181        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20182        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20183        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20184        public static final int DUMP_PERMISSIONS = 1 << 6;
20185        public static final int DUMP_PACKAGES = 1 << 7;
20186        public static final int DUMP_SHARED_USERS = 1 << 8;
20187        public static final int DUMP_MESSAGES = 1 << 9;
20188        public static final int DUMP_PROVIDERS = 1 << 10;
20189        public static final int DUMP_VERIFIERS = 1 << 11;
20190        public static final int DUMP_PREFERRED = 1 << 12;
20191        public static final int DUMP_PREFERRED_XML = 1 << 13;
20192        public static final int DUMP_KEYSETS = 1 << 14;
20193        public static final int DUMP_VERSION = 1 << 15;
20194        public static final int DUMP_INSTALLS = 1 << 16;
20195        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20196        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20197        public static final int DUMP_FROZEN = 1 << 19;
20198        public static final int DUMP_DEXOPT = 1 << 20;
20199        public static final int DUMP_COMPILER_STATS = 1 << 21;
20200        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20201
20202        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20203
20204        private int mTypes;
20205
20206        private int mOptions;
20207
20208        private boolean mTitlePrinted;
20209
20210        private SharedUserSetting mSharedUser;
20211
20212        public boolean isDumping(int type) {
20213            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20214                return true;
20215            }
20216
20217            return (mTypes & type) != 0;
20218        }
20219
20220        public void setDump(int type) {
20221            mTypes |= type;
20222        }
20223
20224        public boolean isOptionEnabled(int option) {
20225            return (mOptions & option) != 0;
20226        }
20227
20228        public void setOptionEnabled(int option) {
20229            mOptions |= option;
20230        }
20231
20232        public boolean onTitlePrinted() {
20233            final boolean printed = mTitlePrinted;
20234            mTitlePrinted = true;
20235            return printed;
20236        }
20237
20238        public boolean getTitlePrinted() {
20239            return mTitlePrinted;
20240        }
20241
20242        public void setTitlePrinted(boolean enabled) {
20243            mTitlePrinted = enabled;
20244        }
20245
20246        public SharedUserSetting getSharedUser() {
20247            return mSharedUser;
20248        }
20249
20250        public void setSharedUser(SharedUserSetting user) {
20251            mSharedUser = user;
20252        }
20253    }
20254
20255    @Override
20256    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20257            FileDescriptor err, String[] args, ShellCallback callback,
20258            ResultReceiver resultReceiver) {
20259        (new PackageManagerShellCommand(this)).exec(
20260                this, in, out, err, args, callback, resultReceiver);
20261    }
20262
20263    @Override
20264    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20265        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20266                != PackageManager.PERMISSION_GRANTED) {
20267            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20268                    + Binder.getCallingPid()
20269                    + ", uid=" + Binder.getCallingUid()
20270                    + " without permission "
20271                    + android.Manifest.permission.DUMP);
20272            return;
20273        }
20274
20275        DumpState dumpState = new DumpState();
20276        boolean fullPreferred = false;
20277        boolean checkin = false;
20278
20279        String packageName = null;
20280        ArraySet<String> permissionNames = null;
20281
20282        int opti = 0;
20283        while (opti < args.length) {
20284            String opt = args[opti];
20285            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20286                break;
20287            }
20288            opti++;
20289
20290            if ("-a".equals(opt)) {
20291                // Right now we only know how to print all.
20292            } else if ("-h".equals(opt)) {
20293                pw.println("Package manager dump options:");
20294                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20295                pw.println("    --checkin: dump for a checkin");
20296                pw.println("    -f: print details of intent filters");
20297                pw.println("    -h: print this help");
20298                pw.println("  cmd may be one of:");
20299                pw.println("    l[ibraries]: list known shared libraries");
20300                pw.println("    f[eatures]: list device features");
20301                pw.println("    k[eysets]: print known keysets");
20302                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20303                pw.println("    perm[issions]: dump permissions");
20304                pw.println("    permission [name ...]: dump declaration and use of given permission");
20305                pw.println("    pref[erred]: print preferred package settings");
20306                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20307                pw.println("    prov[iders]: dump content providers");
20308                pw.println("    p[ackages]: dump installed packages");
20309                pw.println("    s[hared-users]: dump shared user IDs");
20310                pw.println("    m[essages]: print collected runtime messages");
20311                pw.println("    v[erifiers]: print package verifier info");
20312                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20313                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20314                pw.println("    version: print database version info");
20315                pw.println("    write: write current settings now");
20316                pw.println("    installs: details about install sessions");
20317                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20318                pw.println("    dexopt: dump dexopt state");
20319                pw.println("    compiler-stats: dump compiler statistics");
20320                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20321                pw.println("    <package.name>: info about given package");
20322                return;
20323            } else if ("--checkin".equals(opt)) {
20324                checkin = true;
20325            } else if ("-f".equals(opt)) {
20326                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20327            } else if ("--proto".equals(opt)) {
20328                dumpProto(fd);
20329                return;
20330            } else {
20331                pw.println("Unknown argument: " + opt + "; use -h for help");
20332            }
20333        }
20334
20335        // Is the caller requesting to dump a particular piece of data?
20336        if (opti < args.length) {
20337            String cmd = args[opti];
20338            opti++;
20339            // Is this a package name?
20340            if ("android".equals(cmd) || cmd.contains(".")) {
20341                packageName = cmd;
20342                // When dumping a single package, we always dump all of its
20343                // filter information since the amount of data will be reasonable.
20344                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20345            } else if ("check-permission".equals(cmd)) {
20346                if (opti >= args.length) {
20347                    pw.println("Error: check-permission missing permission argument");
20348                    return;
20349                }
20350                String perm = args[opti];
20351                opti++;
20352                if (opti >= args.length) {
20353                    pw.println("Error: check-permission missing package argument");
20354                    return;
20355                }
20356
20357                String pkg = args[opti];
20358                opti++;
20359                int user = UserHandle.getUserId(Binder.getCallingUid());
20360                if (opti < args.length) {
20361                    try {
20362                        user = Integer.parseInt(args[opti]);
20363                    } catch (NumberFormatException e) {
20364                        pw.println("Error: check-permission user argument is not a number: "
20365                                + args[opti]);
20366                        return;
20367                    }
20368                }
20369
20370                // Normalize package name to handle renamed packages and static libs
20371                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20372
20373                pw.println(checkPermission(perm, pkg, user));
20374                return;
20375            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20376                dumpState.setDump(DumpState.DUMP_LIBS);
20377            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20378                dumpState.setDump(DumpState.DUMP_FEATURES);
20379            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20380                if (opti >= args.length) {
20381                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20382                            | DumpState.DUMP_SERVICE_RESOLVERS
20383                            | DumpState.DUMP_RECEIVER_RESOLVERS
20384                            | DumpState.DUMP_CONTENT_RESOLVERS);
20385                } else {
20386                    while (opti < args.length) {
20387                        String name = args[opti];
20388                        if ("a".equals(name) || "activity".equals(name)) {
20389                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20390                        } else if ("s".equals(name) || "service".equals(name)) {
20391                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20392                        } else if ("r".equals(name) || "receiver".equals(name)) {
20393                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20394                        } else if ("c".equals(name) || "content".equals(name)) {
20395                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20396                        } else {
20397                            pw.println("Error: unknown resolver table type: " + name);
20398                            return;
20399                        }
20400                        opti++;
20401                    }
20402                }
20403            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20404                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20405            } else if ("permission".equals(cmd)) {
20406                if (opti >= args.length) {
20407                    pw.println("Error: permission requires permission name");
20408                    return;
20409                }
20410                permissionNames = new ArraySet<>();
20411                while (opti < args.length) {
20412                    permissionNames.add(args[opti]);
20413                    opti++;
20414                }
20415                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20416                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20417            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20418                dumpState.setDump(DumpState.DUMP_PREFERRED);
20419            } else if ("preferred-xml".equals(cmd)) {
20420                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20421                if (opti < args.length && "--full".equals(args[opti])) {
20422                    fullPreferred = true;
20423                    opti++;
20424                }
20425            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20426                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20427            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20428                dumpState.setDump(DumpState.DUMP_PACKAGES);
20429            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20430                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20431            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20432                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20433            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20434                dumpState.setDump(DumpState.DUMP_MESSAGES);
20435            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20436                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20437            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20438                    || "intent-filter-verifiers".equals(cmd)) {
20439                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20440            } else if ("version".equals(cmd)) {
20441                dumpState.setDump(DumpState.DUMP_VERSION);
20442            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20443                dumpState.setDump(DumpState.DUMP_KEYSETS);
20444            } else if ("installs".equals(cmd)) {
20445                dumpState.setDump(DumpState.DUMP_INSTALLS);
20446            } else if ("frozen".equals(cmd)) {
20447                dumpState.setDump(DumpState.DUMP_FROZEN);
20448            } else if ("dexopt".equals(cmd)) {
20449                dumpState.setDump(DumpState.DUMP_DEXOPT);
20450            } else if ("compiler-stats".equals(cmd)) {
20451                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20452            } else if ("enabled-overlays".equals(cmd)) {
20453                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20454            } else if ("write".equals(cmd)) {
20455                synchronized (mPackages) {
20456                    mSettings.writeLPr();
20457                    pw.println("Settings written.");
20458                    return;
20459                }
20460            }
20461        }
20462
20463        if (checkin) {
20464            pw.println("vers,1");
20465        }
20466
20467        // reader
20468        synchronized (mPackages) {
20469            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20470                if (!checkin) {
20471                    if (dumpState.onTitlePrinted())
20472                        pw.println();
20473                    pw.println("Database versions:");
20474                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20475                }
20476            }
20477
20478            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20479                if (!checkin) {
20480                    if (dumpState.onTitlePrinted())
20481                        pw.println();
20482                    pw.println("Verifiers:");
20483                    pw.print("  Required: ");
20484                    pw.print(mRequiredVerifierPackage);
20485                    pw.print(" (uid=");
20486                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20487                            UserHandle.USER_SYSTEM));
20488                    pw.println(")");
20489                } else if (mRequiredVerifierPackage != null) {
20490                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20491                    pw.print(",");
20492                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20493                            UserHandle.USER_SYSTEM));
20494                }
20495            }
20496
20497            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20498                    packageName == null) {
20499                if (mIntentFilterVerifierComponent != null) {
20500                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20501                    if (!checkin) {
20502                        if (dumpState.onTitlePrinted())
20503                            pw.println();
20504                        pw.println("Intent Filter Verifier:");
20505                        pw.print("  Using: ");
20506                        pw.print(verifierPackageName);
20507                        pw.print(" (uid=");
20508                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20509                                UserHandle.USER_SYSTEM));
20510                        pw.println(")");
20511                    } else if (verifierPackageName != null) {
20512                        pw.print("ifv,"); pw.print(verifierPackageName);
20513                        pw.print(",");
20514                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20515                                UserHandle.USER_SYSTEM));
20516                    }
20517                } else {
20518                    pw.println();
20519                    pw.println("No Intent Filter Verifier available!");
20520                }
20521            }
20522
20523            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20524                boolean printedHeader = false;
20525                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20526                while (it.hasNext()) {
20527                    String libName = it.next();
20528                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20529                    if (versionedLib == null) {
20530                        continue;
20531                    }
20532                    final int versionCount = versionedLib.size();
20533                    for (int i = 0; i < versionCount; i++) {
20534                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20535                        if (!checkin) {
20536                            if (!printedHeader) {
20537                                if (dumpState.onTitlePrinted())
20538                                    pw.println();
20539                                pw.println("Libraries:");
20540                                printedHeader = true;
20541                            }
20542                            pw.print("  ");
20543                        } else {
20544                            pw.print("lib,");
20545                        }
20546                        pw.print(libEntry.info.getName());
20547                        if (libEntry.info.isStatic()) {
20548                            pw.print(" version=" + libEntry.info.getVersion());
20549                        }
20550                        if (!checkin) {
20551                            pw.print(" -> ");
20552                        }
20553                        if (libEntry.path != null) {
20554                            pw.print(" (jar) ");
20555                            pw.print(libEntry.path);
20556                        } else {
20557                            pw.print(" (apk) ");
20558                            pw.print(libEntry.apk);
20559                        }
20560                        pw.println();
20561                    }
20562                }
20563            }
20564
20565            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20566                if (dumpState.onTitlePrinted())
20567                    pw.println();
20568                if (!checkin) {
20569                    pw.println("Features:");
20570                }
20571
20572                synchronized (mAvailableFeatures) {
20573                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20574                        if (checkin) {
20575                            pw.print("feat,");
20576                            pw.print(feat.name);
20577                            pw.print(",");
20578                            pw.println(feat.version);
20579                        } else {
20580                            pw.print("  ");
20581                            pw.print(feat.name);
20582                            if (feat.version > 0) {
20583                                pw.print(" version=");
20584                                pw.print(feat.version);
20585                            }
20586                            pw.println();
20587                        }
20588                    }
20589                }
20590            }
20591
20592            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20593                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20594                        : "Activity Resolver Table:", "  ", packageName,
20595                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20596                    dumpState.setTitlePrinted(true);
20597                }
20598            }
20599            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20600                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20601                        : "Receiver Resolver Table:", "  ", packageName,
20602                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20603                    dumpState.setTitlePrinted(true);
20604                }
20605            }
20606            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20607                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20608                        : "Service Resolver Table:", "  ", packageName,
20609                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20610                    dumpState.setTitlePrinted(true);
20611                }
20612            }
20613            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20614                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20615                        : "Provider Resolver Table:", "  ", packageName,
20616                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20617                    dumpState.setTitlePrinted(true);
20618                }
20619            }
20620
20621            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20622                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20623                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20624                    int user = mSettings.mPreferredActivities.keyAt(i);
20625                    if (pir.dump(pw,
20626                            dumpState.getTitlePrinted()
20627                                ? "\nPreferred Activities User " + user + ":"
20628                                : "Preferred Activities User " + user + ":", "  ",
20629                            packageName, true, false)) {
20630                        dumpState.setTitlePrinted(true);
20631                    }
20632                }
20633            }
20634
20635            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20636                pw.flush();
20637                FileOutputStream fout = new FileOutputStream(fd);
20638                BufferedOutputStream str = new BufferedOutputStream(fout);
20639                XmlSerializer serializer = new FastXmlSerializer();
20640                try {
20641                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20642                    serializer.startDocument(null, true);
20643                    serializer.setFeature(
20644                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20645                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20646                    serializer.endDocument();
20647                    serializer.flush();
20648                } catch (IllegalArgumentException e) {
20649                    pw.println("Failed writing: " + e);
20650                } catch (IllegalStateException e) {
20651                    pw.println("Failed writing: " + e);
20652                } catch (IOException e) {
20653                    pw.println("Failed writing: " + e);
20654                }
20655            }
20656
20657            if (!checkin
20658                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20659                    && packageName == null) {
20660                pw.println();
20661                int count = mSettings.mPackages.size();
20662                if (count == 0) {
20663                    pw.println("No applications!");
20664                    pw.println();
20665                } else {
20666                    final String prefix = "  ";
20667                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20668                    if (allPackageSettings.size() == 0) {
20669                        pw.println("No domain preferred apps!");
20670                        pw.println();
20671                    } else {
20672                        pw.println("App verification status:");
20673                        pw.println();
20674                        count = 0;
20675                        for (PackageSetting ps : allPackageSettings) {
20676                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20677                            if (ivi == null || ivi.getPackageName() == null) continue;
20678                            pw.println(prefix + "Package: " + ivi.getPackageName());
20679                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20680                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20681                            pw.println();
20682                            count++;
20683                        }
20684                        if (count == 0) {
20685                            pw.println(prefix + "No app verification established.");
20686                            pw.println();
20687                        }
20688                        for (int userId : sUserManager.getUserIds()) {
20689                            pw.println("App linkages for user " + userId + ":");
20690                            pw.println();
20691                            count = 0;
20692                            for (PackageSetting ps : allPackageSettings) {
20693                                final long status = ps.getDomainVerificationStatusForUser(userId);
20694                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20695                                        && !DEBUG_DOMAIN_VERIFICATION) {
20696                                    continue;
20697                                }
20698                                pw.println(prefix + "Package: " + ps.name);
20699                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20700                                String statusStr = IntentFilterVerificationInfo.
20701                                        getStatusStringFromValue(status);
20702                                pw.println(prefix + "Status:  " + statusStr);
20703                                pw.println();
20704                                count++;
20705                            }
20706                            if (count == 0) {
20707                                pw.println(prefix + "No configured app linkages.");
20708                                pw.println();
20709                            }
20710                        }
20711                    }
20712                }
20713            }
20714
20715            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20716                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20717                if (packageName == null && permissionNames == null) {
20718                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20719                        if (iperm == 0) {
20720                            if (dumpState.onTitlePrinted())
20721                                pw.println();
20722                            pw.println("AppOp Permissions:");
20723                        }
20724                        pw.print("  AppOp Permission ");
20725                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20726                        pw.println(":");
20727                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20728                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20729                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20730                        }
20731                    }
20732                }
20733            }
20734
20735            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20736                boolean printedSomething = false;
20737                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20738                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20739                        continue;
20740                    }
20741                    if (!printedSomething) {
20742                        if (dumpState.onTitlePrinted())
20743                            pw.println();
20744                        pw.println("Registered ContentProviders:");
20745                        printedSomething = true;
20746                    }
20747                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20748                    pw.print("    "); pw.println(p.toString());
20749                }
20750                printedSomething = false;
20751                for (Map.Entry<String, PackageParser.Provider> entry :
20752                        mProvidersByAuthority.entrySet()) {
20753                    PackageParser.Provider p = entry.getValue();
20754                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20755                        continue;
20756                    }
20757                    if (!printedSomething) {
20758                        if (dumpState.onTitlePrinted())
20759                            pw.println();
20760                        pw.println("ContentProvider Authorities:");
20761                        printedSomething = true;
20762                    }
20763                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20764                    pw.print("    "); pw.println(p.toString());
20765                    if (p.info != null && p.info.applicationInfo != null) {
20766                        final String appInfo = p.info.applicationInfo.toString();
20767                        pw.print("      applicationInfo="); pw.println(appInfo);
20768                    }
20769                }
20770            }
20771
20772            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20773                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20774            }
20775
20776            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20777                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20778            }
20779
20780            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20781                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20782            }
20783
20784            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20785                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20786            }
20787
20788            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20789                // XXX should handle packageName != null by dumping only install data that
20790                // the given package is involved with.
20791                if (dumpState.onTitlePrinted()) pw.println();
20792                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20793            }
20794
20795            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20796                // XXX should handle packageName != null by dumping only install data that
20797                // the given package is involved with.
20798                if (dumpState.onTitlePrinted()) pw.println();
20799
20800                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20801                ipw.println();
20802                ipw.println("Frozen packages:");
20803                ipw.increaseIndent();
20804                if (mFrozenPackages.size() == 0) {
20805                    ipw.println("(none)");
20806                } else {
20807                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20808                        ipw.println(mFrozenPackages.valueAt(i));
20809                    }
20810                }
20811                ipw.decreaseIndent();
20812            }
20813
20814            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20815                if (dumpState.onTitlePrinted()) pw.println();
20816                dumpDexoptStateLPr(pw, packageName);
20817            }
20818
20819            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20820                if (dumpState.onTitlePrinted()) pw.println();
20821                dumpCompilerStatsLPr(pw, packageName);
20822            }
20823
20824            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20825                if (dumpState.onTitlePrinted()) pw.println();
20826                dumpEnabledOverlaysLPr(pw);
20827            }
20828
20829            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20830                if (dumpState.onTitlePrinted()) pw.println();
20831                mSettings.dumpReadMessagesLPr(pw, dumpState);
20832
20833                pw.println();
20834                pw.println("Package warning messages:");
20835                BufferedReader in = null;
20836                String line = null;
20837                try {
20838                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20839                    while ((line = in.readLine()) != null) {
20840                        if (line.contains("ignored: updated version")) continue;
20841                        pw.println(line);
20842                    }
20843                } catch (IOException ignored) {
20844                } finally {
20845                    IoUtils.closeQuietly(in);
20846                }
20847            }
20848
20849            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20850                BufferedReader in = null;
20851                String line = null;
20852                try {
20853                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20854                    while ((line = in.readLine()) != null) {
20855                        if (line.contains("ignored: updated version")) continue;
20856                        pw.print("msg,");
20857                        pw.println(line);
20858                    }
20859                } catch (IOException ignored) {
20860                } finally {
20861                    IoUtils.closeQuietly(in);
20862                }
20863            }
20864        }
20865    }
20866
20867    private void dumpProto(FileDescriptor fd) {
20868        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20869
20870        synchronized (mPackages) {
20871            final long requiredVerifierPackageToken =
20872                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20873            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20874            proto.write(
20875                    PackageServiceDumpProto.PackageShortProto.UID,
20876                    getPackageUid(
20877                            mRequiredVerifierPackage,
20878                            MATCH_DEBUG_TRIAGED_MISSING,
20879                            UserHandle.USER_SYSTEM));
20880            proto.end(requiredVerifierPackageToken);
20881
20882            if (mIntentFilterVerifierComponent != null) {
20883                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20884                final long verifierPackageToken =
20885                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20886                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20887                proto.write(
20888                        PackageServiceDumpProto.PackageShortProto.UID,
20889                        getPackageUid(
20890                                verifierPackageName,
20891                                MATCH_DEBUG_TRIAGED_MISSING,
20892                                UserHandle.USER_SYSTEM));
20893                proto.end(verifierPackageToken);
20894            }
20895
20896            dumpSharedLibrariesProto(proto);
20897            dumpFeaturesProto(proto);
20898            mSettings.dumpPackagesProto(proto);
20899            mSettings.dumpSharedUsersProto(proto);
20900            dumpMessagesProto(proto);
20901        }
20902        proto.flush();
20903    }
20904
20905    private void dumpMessagesProto(ProtoOutputStream proto) {
20906        BufferedReader in = null;
20907        String line = null;
20908        try {
20909            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20910            while ((line = in.readLine()) != null) {
20911                if (line.contains("ignored: updated version")) continue;
20912                proto.write(PackageServiceDumpProto.MESSAGES, line);
20913            }
20914        } catch (IOException ignored) {
20915        } finally {
20916            IoUtils.closeQuietly(in);
20917        }
20918    }
20919
20920    private void dumpFeaturesProto(ProtoOutputStream proto) {
20921        synchronized (mAvailableFeatures) {
20922            final int count = mAvailableFeatures.size();
20923            for (int i = 0; i < count; i++) {
20924                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20925                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20926                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20927                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20928                proto.end(featureToken);
20929            }
20930        }
20931    }
20932
20933    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20934        final int count = mSharedLibraries.size();
20935        for (int i = 0; i < count; i++) {
20936            final String libName = mSharedLibraries.keyAt(i);
20937            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20938            if (versionedLib == null) {
20939                continue;
20940            }
20941            final int versionCount = versionedLib.size();
20942            for (int j = 0; j < versionCount; j++) {
20943                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20944                final long sharedLibraryToken =
20945                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20946                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20947                final boolean isJar = (libEntry.path != null);
20948                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20949                if (isJar) {
20950                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20951                } else {
20952                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20953                }
20954                proto.end(sharedLibraryToken);
20955            }
20956        }
20957    }
20958
20959    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20960        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20961        ipw.println();
20962        ipw.println("Dexopt state:");
20963        ipw.increaseIndent();
20964        Collection<PackageParser.Package> packages = null;
20965        if (packageName != null) {
20966            PackageParser.Package targetPackage = mPackages.get(packageName);
20967            if (targetPackage != null) {
20968                packages = Collections.singletonList(targetPackage);
20969            } else {
20970                ipw.println("Unable to find package: " + packageName);
20971                return;
20972            }
20973        } else {
20974            packages = mPackages.values();
20975        }
20976
20977        for (PackageParser.Package pkg : packages) {
20978            ipw.println("[" + pkg.packageName + "]");
20979            ipw.increaseIndent();
20980            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20981            ipw.decreaseIndent();
20982        }
20983    }
20984
20985    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20986        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20987        ipw.println();
20988        ipw.println("Compiler stats:");
20989        ipw.increaseIndent();
20990        Collection<PackageParser.Package> packages = null;
20991        if (packageName != null) {
20992            PackageParser.Package targetPackage = mPackages.get(packageName);
20993            if (targetPackage != null) {
20994                packages = Collections.singletonList(targetPackage);
20995            } else {
20996                ipw.println("Unable to find package: " + packageName);
20997                return;
20998            }
20999        } else {
21000            packages = mPackages.values();
21001        }
21002
21003        for (PackageParser.Package pkg : packages) {
21004            ipw.println("[" + pkg.packageName + "]");
21005            ipw.increaseIndent();
21006
21007            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21008            if (stats == null) {
21009                ipw.println("(No recorded stats)");
21010            } else {
21011                stats.dump(ipw);
21012            }
21013            ipw.decreaseIndent();
21014        }
21015    }
21016
21017    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21018        pw.println("Enabled overlay paths:");
21019        final int N = mEnabledOverlayPaths.size();
21020        for (int i = 0; i < N; i++) {
21021            final int userId = mEnabledOverlayPaths.keyAt(i);
21022            pw.println(String.format("    User %d:", userId));
21023            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21024                mEnabledOverlayPaths.valueAt(i);
21025            final int M = userSpecificOverlays.size();
21026            for (int j = 0; j < M; j++) {
21027                final String targetPackageName = userSpecificOverlays.keyAt(j);
21028                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21029                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21030            }
21031        }
21032    }
21033
21034    private String dumpDomainString(String packageName) {
21035        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21036                .getList();
21037        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21038
21039        ArraySet<String> result = new ArraySet<>();
21040        if (iviList.size() > 0) {
21041            for (IntentFilterVerificationInfo ivi : iviList) {
21042                for (String host : ivi.getDomains()) {
21043                    result.add(host);
21044                }
21045            }
21046        }
21047        if (filters != null && filters.size() > 0) {
21048            for (IntentFilter filter : filters) {
21049                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21050                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21051                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21052                    result.addAll(filter.getHostsList());
21053                }
21054            }
21055        }
21056
21057        StringBuilder sb = new StringBuilder(result.size() * 16);
21058        for (String domain : result) {
21059            if (sb.length() > 0) sb.append(" ");
21060            sb.append(domain);
21061        }
21062        return sb.toString();
21063    }
21064
21065    // ------- apps on sdcard specific code -------
21066    static final boolean DEBUG_SD_INSTALL = false;
21067
21068    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21069
21070    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21071
21072    private boolean mMediaMounted = false;
21073
21074    static String getEncryptKey() {
21075        try {
21076            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21077                    SD_ENCRYPTION_KEYSTORE_NAME);
21078            if (sdEncKey == null) {
21079                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21080                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21081                if (sdEncKey == null) {
21082                    Slog.e(TAG, "Failed to create encryption keys");
21083                    return null;
21084                }
21085            }
21086            return sdEncKey;
21087        } catch (NoSuchAlgorithmException nsae) {
21088            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21089            return null;
21090        } catch (IOException ioe) {
21091            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21092            return null;
21093        }
21094    }
21095
21096    /*
21097     * Update media status on PackageManager.
21098     */
21099    @Override
21100    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21101        int callingUid = Binder.getCallingUid();
21102        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21103            throw new SecurityException("Media status can only be updated by the system");
21104        }
21105        // reader; this apparently protects mMediaMounted, but should probably
21106        // be a different lock in that case.
21107        synchronized (mPackages) {
21108            Log.i(TAG, "Updating external media status from "
21109                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21110                    + (mediaStatus ? "mounted" : "unmounted"));
21111            if (DEBUG_SD_INSTALL)
21112                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21113                        + ", mMediaMounted=" + mMediaMounted);
21114            if (mediaStatus == mMediaMounted) {
21115                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21116                        : 0, -1);
21117                mHandler.sendMessage(msg);
21118                return;
21119            }
21120            mMediaMounted = mediaStatus;
21121        }
21122        // Queue up an async operation since the package installation may take a
21123        // little while.
21124        mHandler.post(new Runnable() {
21125            public void run() {
21126                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21127            }
21128        });
21129    }
21130
21131    /**
21132     * Called by StorageManagerService when the initial ASECs to scan are available.
21133     * Should block until all the ASEC containers are finished being scanned.
21134     */
21135    public void scanAvailableAsecs() {
21136        updateExternalMediaStatusInner(true, false, false);
21137    }
21138
21139    /*
21140     * Collect information of applications on external media, map them against
21141     * existing containers and update information based on current mount status.
21142     * Please note that we always have to report status if reportStatus has been
21143     * set to true especially when unloading packages.
21144     */
21145    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21146            boolean externalStorage) {
21147        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21148        int[] uidArr = EmptyArray.INT;
21149
21150        final String[] list = PackageHelper.getSecureContainerList();
21151        if (ArrayUtils.isEmpty(list)) {
21152            Log.i(TAG, "No secure containers found");
21153        } else {
21154            // Process list of secure containers and categorize them
21155            // as active or stale based on their package internal state.
21156
21157            // reader
21158            synchronized (mPackages) {
21159                for (String cid : list) {
21160                    // Leave stages untouched for now; installer service owns them
21161                    if (PackageInstallerService.isStageName(cid)) continue;
21162
21163                    if (DEBUG_SD_INSTALL)
21164                        Log.i(TAG, "Processing container " + cid);
21165                    String pkgName = getAsecPackageName(cid);
21166                    if (pkgName == null) {
21167                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21168                        continue;
21169                    }
21170                    if (DEBUG_SD_INSTALL)
21171                        Log.i(TAG, "Looking for pkg : " + pkgName);
21172
21173                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21174                    if (ps == null) {
21175                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21176                        continue;
21177                    }
21178
21179                    /*
21180                     * Skip packages that are not external if we're unmounting
21181                     * external storage.
21182                     */
21183                    if (externalStorage && !isMounted && !isExternal(ps)) {
21184                        continue;
21185                    }
21186
21187                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21188                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21189                    // The package status is changed only if the code path
21190                    // matches between settings and the container id.
21191                    if (ps.codePathString != null
21192                            && ps.codePathString.startsWith(args.getCodePath())) {
21193                        if (DEBUG_SD_INSTALL) {
21194                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21195                                    + " at code path: " + ps.codePathString);
21196                        }
21197
21198                        // We do have a valid package installed on sdcard
21199                        processCids.put(args, ps.codePathString);
21200                        final int uid = ps.appId;
21201                        if (uid != -1) {
21202                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21203                        }
21204                    } else {
21205                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21206                                + ps.codePathString);
21207                    }
21208                }
21209            }
21210
21211            Arrays.sort(uidArr);
21212        }
21213
21214        // Process packages with valid entries.
21215        if (isMounted) {
21216            if (DEBUG_SD_INSTALL)
21217                Log.i(TAG, "Loading packages");
21218            loadMediaPackages(processCids, uidArr, externalStorage);
21219            startCleaningPackages();
21220            mInstallerService.onSecureContainersAvailable();
21221        } else {
21222            if (DEBUG_SD_INSTALL)
21223                Log.i(TAG, "Unloading packages");
21224            unloadMediaPackages(processCids, uidArr, reportStatus);
21225        }
21226    }
21227
21228    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21229            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21230        final int size = infos.size();
21231        final String[] packageNames = new String[size];
21232        final int[] packageUids = new int[size];
21233        for (int i = 0; i < size; i++) {
21234            final ApplicationInfo info = infos.get(i);
21235            packageNames[i] = info.packageName;
21236            packageUids[i] = info.uid;
21237        }
21238        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21239                finishedReceiver);
21240    }
21241
21242    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21243            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21244        sendResourcesChangedBroadcast(mediaStatus, replacing,
21245                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21246    }
21247
21248    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21249            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21250        int size = pkgList.length;
21251        if (size > 0) {
21252            // Send broadcasts here
21253            Bundle extras = new Bundle();
21254            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21255            if (uidArr != null) {
21256                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21257            }
21258            if (replacing) {
21259                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21260            }
21261            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21262                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21263            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21264        }
21265    }
21266
21267   /*
21268     * Look at potentially valid container ids from processCids If package
21269     * information doesn't match the one on record or package scanning fails,
21270     * the cid is added to list of removeCids. We currently don't delete stale
21271     * containers.
21272     */
21273    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21274            boolean externalStorage) {
21275        ArrayList<String> pkgList = new ArrayList<String>();
21276        Set<AsecInstallArgs> keys = processCids.keySet();
21277
21278        for (AsecInstallArgs args : keys) {
21279            String codePath = processCids.get(args);
21280            if (DEBUG_SD_INSTALL)
21281                Log.i(TAG, "Loading container : " + args.cid);
21282            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21283            try {
21284                // Make sure there are no container errors first.
21285                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21286                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21287                            + " when installing from sdcard");
21288                    continue;
21289                }
21290                // Check code path here.
21291                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21292                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21293                            + " does not match one in settings " + codePath);
21294                    continue;
21295                }
21296                // Parse package
21297                int parseFlags = mDefParseFlags;
21298                if (args.isExternalAsec()) {
21299                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21300                }
21301                if (args.isFwdLocked()) {
21302                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21303                }
21304
21305                synchronized (mInstallLock) {
21306                    PackageParser.Package pkg = null;
21307                    try {
21308                        // Sadly we don't know the package name yet to freeze it
21309                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21310                                SCAN_IGNORE_FROZEN, 0, null);
21311                    } catch (PackageManagerException e) {
21312                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21313                    }
21314                    // Scan the package
21315                    if (pkg != null) {
21316                        /*
21317                         * TODO why is the lock being held? doPostInstall is
21318                         * called in other places without the lock. This needs
21319                         * to be straightened out.
21320                         */
21321                        // writer
21322                        synchronized (mPackages) {
21323                            retCode = PackageManager.INSTALL_SUCCEEDED;
21324                            pkgList.add(pkg.packageName);
21325                            // Post process args
21326                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21327                                    pkg.applicationInfo.uid);
21328                        }
21329                    } else {
21330                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21331                    }
21332                }
21333
21334            } finally {
21335                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21336                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21337                }
21338            }
21339        }
21340        // writer
21341        synchronized (mPackages) {
21342            // If the platform SDK has changed since the last time we booted,
21343            // we need to re-grant app permission to catch any new ones that
21344            // appear. This is really a hack, and means that apps can in some
21345            // cases get permissions that the user didn't initially explicitly
21346            // allow... it would be nice to have some better way to handle
21347            // this situation.
21348            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21349                    : mSettings.getInternalVersion();
21350            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21351                    : StorageManager.UUID_PRIVATE_INTERNAL;
21352
21353            int updateFlags = UPDATE_PERMISSIONS_ALL;
21354            if (ver.sdkVersion != mSdkVersion) {
21355                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21356                        + mSdkVersion + "; regranting permissions for external");
21357                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21358            }
21359            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21360
21361            // Yay, everything is now upgraded
21362            ver.forceCurrent();
21363
21364            // can downgrade to reader
21365            // Persist settings
21366            mSettings.writeLPr();
21367        }
21368        // Send a broadcast to let everyone know we are done processing
21369        if (pkgList.size() > 0) {
21370            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21371        }
21372    }
21373
21374   /*
21375     * Utility method to unload a list of specified containers
21376     */
21377    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21378        // Just unmount all valid containers.
21379        for (AsecInstallArgs arg : cidArgs) {
21380            synchronized (mInstallLock) {
21381                arg.doPostDeleteLI(false);
21382           }
21383       }
21384   }
21385
21386    /*
21387     * Unload packages mounted on external media. This involves deleting package
21388     * data from internal structures, sending broadcasts about disabled packages,
21389     * gc'ing to free up references, unmounting all secure containers
21390     * corresponding to packages on external media, and posting a
21391     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21392     * that we always have to post this message if status has been requested no
21393     * matter what.
21394     */
21395    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21396            final boolean reportStatus) {
21397        if (DEBUG_SD_INSTALL)
21398            Log.i(TAG, "unloading media packages");
21399        ArrayList<String> pkgList = new ArrayList<String>();
21400        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21401        final Set<AsecInstallArgs> keys = processCids.keySet();
21402        for (AsecInstallArgs args : keys) {
21403            String pkgName = args.getPackageName();
21404            if (DEBUG_SD_INSTALL)
21405                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21406            // Delete package internally
21407            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21408            synchronized (mInstallLock) {
21409                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21410                final boolean res;
21411                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21412                        "unloadMediaPackages")) {
21413                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21414                            null);
21415                }
21416                if (res) {
21417                    pkgList.add(pkgName);
21418                } else {
21419                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21420                    failedList.add(args);
21421                }
21422            }
21423        }
21424
21425        // reader
21426        synchronized (mPackages) {
21427            // We didn't update the settings after removing each package;
21428            // write them now for all packages.
21429            mSettings.writeLPr();
21430        }
21431
21432        // We have to absolutely send UPDATED_MEDIA_STATUS only
21433        // after confirming that all the receivers processed the ordered
21434        // broadcast when packages get disabled, force a gc to clean things up.
21435        // and unload all the containers.
21436        if (pkgList.size() > 0) {
21437            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21438                    new IIntentReceiver.Stub() {
21439                public void performReceive(Intent intent, int resultCode, String data,
21440                        Bundle extras, boolean ordered, boolean sticky,
21441                        int sendingUser) throws RemoteException {
21442                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21443                            reportStatus ? 1 : 0, 1, keys);
21444                    mHandler.sendMessage(msg);
21445                }
21446            });
21447        } else {
21448            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21449                    keys);
21450            mHandler.sendMessage(msg);
21451        }
21452    }
21453
21454    private void loadPrivatePackages(final VolumeInfo vol) {
21455        mHandler.post(new Runnable() {
21456            @Override
21457            public void run() {
21458                loadPrivatePackagesInner(vol);
21459            }
21460        });
21461    }
21462
21463    private void loadPrivatePackagesInner(VolumeInfo vol) {
21464        final String volumeUuid = vol.fsUuid;
21465        if (TextUtils.isEmpty(volumeUuid)) {
21466            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21467            return;
21468        }
21469
21470        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21471        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21472        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21473
21474        final VersionInfo ver;
21475        final List<PackageSetting> packages;
21476        synchronized (mPackages) {
21477            ver = mSettings.findOrCreateVersion(volumeUuid);
21478            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21479        }
21480
21481        for (PackageSetting ps : packages) {
21482            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21483            synchronized (mInstallLock) {
21484                final PackageParser.Package pkg;
21485                try {
21486                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21487                    loaded.add(pkg.applicationInfo);
21488
21489                } catch (PackageManagerException e) {
21490                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21491                }
21492
21493                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21494                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21495                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21496                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21497                }
21498            }
21499        }
21500
21501        // Reconcile app data for all started/unlocked users
21502        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21503        final UserManager um = mContext.getSystemService(UserManager.class);
21504        UserManagerInternal umInternal = getUserManagerInternal();
21505        for (UserInfo user : um.getUsers()) {
21506            final int flags;
21507            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21508                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21509            } else if (umInternal.isUserRunning(user.id)) {
21510                flags = StorageManager.FLAG_STORAGE_DE;
21511            } else {
21512                continue;
21513            }
21514
21515            try {
21516                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21517                synchronized (mInstallLock) {
21518                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21519                }
21520            } catch (IllegalStateException e) {
21521                // Device was probably ejected, and we'll process that event momentarily
21522                Slog.w(TAG, "Failed to prepare storage: " + e);
21523            }
21524        }
21525
21526        synchronized (mPackages) {
21527            int updateFlags = UPDATE_PERMISSIONS_ALL;
21528            if (ver.sdkVersion != mSdkVersion) {
21529                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21530                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21531                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21532            }
21533            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21534
21535            // Yay, everything is now upgraded
21536            ver.forceCurrent();
21537
21538            mSettings.writeLPr();
21539        }
21540
21541        for (PackageFreezer freezer : freezers) {
21542            freezer.close();
21543        }
21544
21545        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21546        sendResourcesChangedBroadcast(true, false, loaded, null);
21547    }
21548
21549    private void unloadPrivatePackages(final VolumeInfo vol) {
21550        mHandler.post(new Runnable() {
21551            @Override
21552            public void run() {
21553                unloadPrivatePackagesInner(vol);
21554            }
21555        });
21556    }
21557
21558    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21559        final String volumeUuid = vol.fsUuid;
21560        if (TextUtils.isEmpty(volumeUuid)) {
21561            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21562            return;
21563        }
21564
21565        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21566        synchronized (mInstallLock) {
21567        synchronized (mPackages) {
21568            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21569            for (PackageSetting ps : packages) {
21570                if (ps.pkg == null) continue;
21571
21572                final ApplicationInfo info = ps.pkg.applicationInfo;
21573                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21574                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21575
21576                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21577                        "unloadPrivatePackagesInner")) {
21578                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21579                            false, null)) {
21580                        unloaded.add(info);
21581                    } else {
21582                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21583                    }
21584                }
21585
21586                // Try very hard to release any references to this package
21587                // so we don't risk the system server being killed due to
21588                // open FDs
21589                AttributeCache.instance().removePackage(ps.name);
21590            }
21591
21592            mSettings.writeLPr();
21593        }
21594        }
21595
21596        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21597        sendResourcesChangedBroadcast(false, false, unloaded, null);
21598
21599        // Try very hard to release any references to this path so we don't risk
21600        // the system server being killed due to open FDs
21601        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21602
21603        for (int i = 0; i < 3; i++) {
21604            System.gc();
21605            System.runFinalization();
21606        }
21607    }
21608
21609    private void assertPackageKnown(String volumeUuid, String packageName)
21610            throws PackageManagerException {
21611        synchronized (mPackages) {
21612            // Normalize package name to handle renamed packages
21613            packageName = normalizePackageNameLPr(packageName);
21614
21615            final PackageSetting ps = mSettings.mPackages.get(packageName);
21616            if (ps == null) {
21617                throw new PackageManagerException("Package " + packageName + " is unknown");
21618            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21619                throw new PackageManagerException(
21620                        "Package " + packageName + " found on unknown volume " + volumeUuid
21621                                + "; expected volume " + ps.volumeUuid);
21622            }
21623        }
21624    }
21625
21626    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21627            throws PackageManagerException {
21628        synchronized (mPackages) {
21629            // Normalize package name to handle renamed packages
21630            packageName = normalizePackageNameLPr(packageName);
21631
21632            final PackageSetting ps = mSettings.mPackages.get(packageName);
21633            if (ps == null) {
21634                throw new PackageManagerException("Package " + packageName + " is unknown");
21635            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21636                throw new PackageManagerException(
21637                        "Package " + packageName + " found on unknown volume " + volumeUuid
21638                                + "; expected volume " + ps.volumeUuid);
21639            } else if (!ps.getInstalled(userId)) {
21640                throw new PackageManagerException(
21641                        "Package " + packageName + " not installed for user " + userId);
21642            }
21643        }
21644    }
21645
21646    private List<String> collectAbsoluteCodePaths() {
21647        synchronized (mPackages) {
21648            List<String> codePaths = new ArrayList<>();
21649            final int packageCount = mSettings.mPackages.size();
21650            for (int i = 0; i < packageCount; i++) {
21651                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21652                codePaths.add(ps.codePath.getAbsolutePath());
21653            }
21654            return codePaths;
21655        }
21656    }
21657
21658    /**
21659     * Examine all apps present on given mounted volume, and destroy apps that
21660     * aren't expected, either due to uninstallation or reinstallation on
21661     * another volume.
21662     */
21663    private void reconcileApps(String volumeUuid) {
21664        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21665        List<File> filesToDelete = null;
21666
21667        final File[] files = FileUtils.listFilesOrEmpty(
21668                Environment.getDataAppDirectory(volumeUuid));
21669        for (File file : files) {
21670            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21671                    && !PackageInstallerService.isStageName(file.getName());
21672            if (!isPackage) {
21673                // Ignore entries which are not packages
21674                continue;
21675            }
21676
21677            String absolutePath = file.getAbsolutePath();
21678
21679            boolean pathValid = false;
21680            final int absoluteCodePathCount = absoluteCodePaths.size();
21681            for (int i = 0; i < absoluteCodePathCount; i++) {
21682                String absoluteCodePath = absoluteCodePaths.get(i);
21683                if (absolutePath.startsWith(absoluteCodePath)) {
21684                    pathValid = true;
21685                    break;
21686                }
21687            }
21688
21689            if (!pathValid) {
21690                if (filesToDelete == null) {
21691                    filesToDelete = new ArrayList<>();
21692                }
21693                filesToDelete.add(file);
21694            }
21695        }
21696
21697        if (filesToDelete != null) {
21698            final int fileToDeleteCount = filesToDelete.size();
21699            for (int i = 0; i < fileToDeleteCount; i++) {
21700                File fileToDelete = filesToDelete.get(i);
21701                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21702                synchronized (mInstallLock) {
21703                    removeCodePathLI(fileToDelete);
21704                }
21705            }
21706        }
21707    }
21708
21709    /**
21710     * Reconcile all app data for the given user.
21711     * <p>
21712     * Verifies that directories exist and that ownership and labeling is
21713     * correct for all installed apps on all mounted volumes.
21714     */
21715    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21716        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21717        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21718            final String volumeUuid = vol.getFsUuid();
21719            synchronized (mInstallLock) {
21720                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21721            }
21722        }
21723    }
21724
21725    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21726            boolean migrateAppData) {
21727        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21728    }
21729
21730    /**
21731     * Reconcile all app data on given mounted volume.
21732     * <p>
21733     * Destroys app data that isn't expected, either due to uninstallation or
21734     * reinstallation on another volume.
21735     * <p>
21736     * Verifies that directories exist and that ownership and labeling is
21737     * correct for all installed apps.
21738     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21739     */
21740    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21741            boolean migrateAppData, boolean onlyCoreApps) {
21742        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21743                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21744        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21745
21746        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21747        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21748
21749        // First look for stale data that doesn't belong, and check if things
21750        // have changed since we did our last restorecon
21751        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21752            if (StorageManager.isFileEncryptedNativeOrEmulated()
21753                    && !StorageManager.isUserKeyUnlocked(userId)) {
21754                throw new RuntimeException(
21755                        "Yikes, someone asked us to reconcile CE storage while " + userId
21756                                + " was still locked; this would have caused massive data loss!");
21757            }
21758
21759            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21760            for (File file : files) {
21761                final String packageName = file.getName();
21762                try {
21763                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21764                } catch (PackageManagerException e) {
21765                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21766                    try {
21767                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21768                                StorageManager.FLAG_STORAGE_CE, 0);
21769                    } catch (InstallerException e2) {
21770                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21771                    }
21772                }
21773            }
21774        }
21775        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21776            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21777            for (File file : files) {
21778                final String packageName = file.getName();
21779                try {
21780                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21781                } catch (PackageManagerException e) {
21782                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21783                    try {
21784                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21785                                StorageManager.FLAG_STORAGE_DE, 0);
21786                    } catch (InstallerException e2) {
21787                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21788                    }
21789                }
21790            }
21791        }
21792
21793        // Ensure that data directories are ready to roll for all packages
21794        // installed for this volume and user
21795        final List<PackageSetting> packages;
21796        synchronized (mPackages) {
21797            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21798        }
21799        int preparedCount = 0;
21800        for (PackageSetting ps : packages) {
21801            final String packageName = ps.name;
21802            if (ps.pkg == null) {
21803                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21804                // TODO: might be due to legacy ASEC apps; we should circle back
21805                // and reconcile again once they're scanned
21806                continue;
21807            }
21808            // Skip non-core apps if requested
21809            if (onlyCoreApps && !ps.pkg.coreApp) {
21810                result.add(packageName);
21811                continue;
21812            }
21813
21814            if (ps.getInstalled(userId)) {
21815                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21816                preparedCount++;
21817            }
21818        }
21819
21820        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21821        return result;
21822    }
21823
21824    /**
21825     * Prepare app data for the given app just after it was installed or
21826     * upgraded. This method carefully only touches users that it's installed
21827     * for, and it forces a restorecon to handle any seinfo changes.
21828     * <p>
21829     * Verifies that directories exist and that ownership and labeling is
21830     * correct for all installed apps. If there is an ownership mismatch, it
21831     * will try recovering system apps by wiping data; third-party app data is
21832     * left intact.
21833     * <p>
21834     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21835     */
21836    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21837        final PackageSetting ps;
21838        synchronized (mPackages) {
21839            ps = mSettings.mPackages.get(pkg.packageName);
21840            mSettings.writeKernelMappingLPr(ps);
21841        }
21842
21843        final UserManager um = mContext.getSystemService(UserManager.class);
21844        UserManagerInternal umInternal = getUserManagerInternal();
21845        for (UserInfo user : um.getUsers()) {
21846            final int flags;
21847            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21848                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21849            } else if (umInternal.isUserRunning(user.id)) {
21850                flags = StorageManager.FLAG_STORAGE_DE;
21851            } else {
21852                continue;
21853            }
21854
21855            if (ps.getInstalled(user.id)) {
21856                // TODO: when user data is locked, mark that we're still dirty
21857                prepareAppDataLIF(pkg, user.id, flags);
21858            }
21859        }
21860    }
21861
21862    /**
21863     * Prepare app data for the given app.
21864     * <p>
21865     * Verifies that directories exist and that ownership and labeling is
21866     * correct for all installed apps. If there is an ownership mismatch, this
21867     * will try recovering system apps by wiping data; third-party app data is
21868     * left intact.
21869     */
21870    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21871        if (pkg == null) {
21872            Slog.wtf(TAG, "Package was null!", new Throwable());
21873            return;
21874        }
21875        prepareAppDataLeafLIF(pkg, userId, flags);
21876        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21877        for (int i = 0; i < childCount; i++) {
21878            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21879        }
21880    }
21881
21882    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21883            boolean maybeMigrateAppData) {
21884        prepareAppDataLIF(pkg, userId, flags);
21885
21886        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21887            // We may have just shuffled around app data directories, so
21888            // prepare them one more time
21889            prepareAppDataLIF(pkg, userId, flags);
21890        }
21891    }
21892
21893    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21894        if (DEBUG_APP_DATA) {
21895            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21896                    + Integer.toHexString(flags));
21897        }
21898
21899        final String volumeUuid = pkg.volumeUuid;
21900        final String packageName = pkg.packageName;
21901        final ApplicationInfo app = pkg.applicationInfo;
21902        final int appId = UserHandle.getAppId(app.uid);
21903
21904        Preconditions.checkNotNull(app.seInfo);
21905
21906        long ceDataInode = -1;
21907        try {
21908            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21909                    appId, app.seInfo, app.targetSdkVersion);
21910        } catch (InstallerException e) {
21911            if (app.isSystemApp()) {
21912                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21913                        + ", but trying to recover: " + e);
21914                destroyAppDataLeafLIF(pkg, userId, flags);
21915                try {
21916                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21917                            appId, app.seInfo, app.targetSdkVersion);
21918                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21919                } catch (InstallerException e2) {
21920                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21921                }
21922            } else {
21923                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21924            }
21925        }
21926
21927        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21928            // TODO: mark this structure as dirty so we persist it!
21929            synchronized (mPackages) {
21930                final PackageSetting ps = mSettings.mPackages.get(packageName);
21931                if (ps != null) {
21932                    ps.setCeDataInode(ceDataInode, userId);
21933                }
21934            }
21935        }
21936
21937        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21938    }
21939
21940    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21941        if (pkg == null) {
21942            Slog.wtf(TAG, "Package was null!", new Throwable());
21943            return;
21944        }
21945        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21946        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21947        for (int i = 0; i < childCount; i++) {
21948            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21949        }
21950    }
21951
21952    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21953        final String volumeUuid = pkg.volumeUuid;
21954        final String packageName = pkg.packageName;
21955        final ApplicationInfo app = pkg.applicationInfo;
21956
21957        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21958            // Create a native library symlink only if we have native libraries
21959            // and if the native libraries are 32 bit libraries. We do not provide
21960            // this symlink for 64 bit libraries.
21961            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21962                final String nativeLibPath = app.nativeLibraryDir;
21963                try {
21964                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21965                            nativeLibPath, userId);
21966                } catch (InstallerException e) {
21967                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21968                }
21969            }
21970        }
21971    }
21972
21973    /**
21974     * For system apps on non-FBE devices, this method migrates any existing
21975     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21976     * requested by the app.
21977     */
21978    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21979        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21980                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21981            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21982                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21983            try {
21984                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21985                        storageTarget);
21986            } catch (InstallerException e) {
21987                logCriticalInfo(Log.WARN,
21988                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21989            }
21990            return true;
21991        } else {
21992            return false;
21993        }
21994    }
21995
21996    public PackageFreezer freezePackage(String packageName, String killReason) {
21997        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21998    }
21999
22000    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22001        return new PackageFreezer(packageName, userId, killReason);
22002    }
22003
22004    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22005            String killReason) {
22006        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22007    }
22008
22009    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22010            String killReason) {
22011        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22012            return new PackageFreezer();
22013        } else {
22014            return freezePackage(packageName, userId, killReason);
22015        }
22016    }
22017
22018    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22019            String killReason) {
22020        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22021    }
22022
22023    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22024            String killReason) {
22025        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22026            return new PackageFreezer();
22027        } else {
22028            return freezePackage(packageName, userId, killReason);
22029        }
22030    }
22031
22032    /**
22033     * Class that freezes and kills the given package upon creation, and
22034     * unfreezes it upon closing. This is typically used when doing surgery on
22035     * app code/data to prevent the app from running while you're working.
22036     */
22037    private class PackageFreezer implements AutoCloseable {
22038        private final String mPackageName;
22039        private final PackageFreezer[] mChildren;
22040
22041        private final boolean mWeFroze;
22042
22043        private final AtomicBoolean mClosed = new AtomicBoolean();
22044        private final CloseGuard mCloseGuard = CloseGuard.get();
22045
22046        /**
22047         * Create and return a stub freezer that doesn't actually do anything,
22048         * typically used when someone requested
22049         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22050         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22051         */
22052        public PackageFreezer() {
22053            mPackageName = null;
22054            mChildren = null;
22055            mWeFroze = false;
22056            mCloseGuard.open("close");
22057        }
22058
22059        public PackageFreezer(String packageName, int userId, String killReason) {
22060            synchronized (mPackages) {
22061                mPackageName = packageName;
22062                mWeFroze = mFrozenPackages.add(mPackageName);
22063
22064                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22065                if (ps != null) {
22066                    killApplication(ps.name, ps.appId, userId, killReason);
22067                }
22068
22069                final PackageParser.Package p = mPackages.get(packageName);
22070                if (p != null && p.childPackages != null) {
22071                    final int N = p.childPackages.size();
22072                    mChildren = new PackageFreezer[N];
22073                    for (int i = 0; i < N; i++) {
22074                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22075                                userId, killReason);
22076                    }
22077                } else {
22078                    mChildren = null;
22079                }
22080            }
22081            mCloseGuard.open("close");
22082        }
22083
22084        @Override
22085        protected void finalize() throws Throwable {
22086            try {
22087                mCloseGuard.warnIfOpen();
22088                close();
22089            } finally {
22090                super.finalize();
22091            }
22092        }
22093
22094        @Override
22095        public void close() {
22096            mCloseGuard.close();
22097            if (mClosed.compareAndSet(false, true)) {
22098                synchronized (mPackages) {
22099                    if (mWeFroze) {
22100                        mFrozenPackages.remove(mPackageName);
22101                    }
22102
22103                    if (mChildren != null) {
22104                        for (PackageFreezer freezer : mChildren) {
22105                            freezer.close();
22106                        }
22107                    }
22108                }
22109            }
22110        }
22111    }
22112
22113    /**
22114     * Verify that given package is currently frozen.
22115     */
22116    private void checkPackageFrozen(String packageName) {
22117        synchronized (mPackages) {
22118            if (!mFrozenPackages.contains(packageName)) {
22119                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22120            }
22121        }
22122    }
22123
22124    @Override
22125    public int movePackage(final String packageName, final String volumeUuid) {
22126        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22127
22128        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22129        final int moveId = mNextMoveId.getAndIncrement();
22130        mHandler.post(new Runnable() {
22131            @Override
22132            public void run() {
22133                try {
22134                    movePackageInternal(packageName, volumeUuid, moveId, user);
22135                } catch (PackageManagerException e) {
22136                    Slog.w(TAG, "Failed to move " + packageName, e);
22137                    mMoveCallbacks.notifyStatusChanged(moveId,
22138                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22139                }
22140            }
22141        });
22142        return moveId;
22143    }
22144
22145    private void movePackageInternal(final String packageName, final String volumeUuid,
22146            final int moveId, UserHandle user) throws PackageManagerException {
22147        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22148        final PackageManager pm = mContext.getPackageManager();
22149
22150        final boolean currentAsec;
22151        final String currentVolumeUuid;
22152        final File codeFile;
22153        final String installerPackageName;
22154        final String packageAbiOverride;
22155        final int appId;
22156        final String seinfo;
22157        final String label;
22158        final int targetSdkVersion;
22159        final PackageFreezer freezer;
22160        final int[] installedUserIds;
22161
22162        // reader
22163        synchronized (mPackages) {
22164            final PackageParser.Package pkg = mPackages.get(packageName);
22165            final PackageSetting ps = mSettings.mPackages.get(packageName);
22166            if (pkg == null || ps == null) {
22167                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22168            }
22169
22170            if (pkg.applicationInfo.isSystemApp()) {
22171                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22172                        "Cannot move system application");
22173            }
22174
22175            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22176            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22177                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22178            if (isInternalStorage && !allow3rdPartyOnInternal) {
22179                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22180                        "3rd party apps are not allowed on internal storage");
22181            }
22182
22183            if (pkg.applicationInfo.isExternalAsec()) {
22184                currentAsec = true;
22185                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22186            } else if (pkg.applicationInfo.isForwardLocked()) {
22187                currentAsec = true;
22188                currentVolumeUuid = "forward_locked";
22189            } else {
22190                currentAsec = false;
22191                currentVolumeUuid = ps.volumeUuid;
22192
22193                final File probe = new File(pkg.codePath);
22194                final File probeOat = new File(probe, "oat");
22195                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22196                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22197                            "Move only supported for modern cluster style installs");
22198                }
22199            }
22200
22201            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22202                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22203                        "Package already moved to " + volumeUuid);
22204            }
22205            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22206                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22207                        "Device admin cannot be moved");
22208            }
22209
22210            if (mFrozenPackages.contains(packageName)) {
22211                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22212                        "Failed to move already frozen package");
22213            }
22214
22215            codeFile = new File(pkg.codePath);
22216            installerPackageName = ps.installerPackageName;
22217            packageAbiOverride = ps.cpuAbiOverrideString;
22218            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22219            seinfo = pkg.applicationInfo.seInfo;
22220            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22221            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22222            freezer = freezePackage(packageName, "movePackageInternal");
22223            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22224        }
22225
22226        final Bundle extras = new Bundle();
22227        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22228        extras.putString(Intent.EXTRA_TITLE, label);
22229        mMoveCallbacks.notifyCreated(moveId, extras);
22230
22231        int installFlags;
22232        final boolean moveCompleteApp;
22233        final File measurePath;
22234
22235        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22236            installFlags = INSTALL_INTERNAL;
22237            moveCompleteApp = !currentAsec;
22238            measurePath = Environment.getDataAppDirectory(volumeUuid);
22239        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22240            installFlags = INSTALL_EXTERNAL;
22241            moveCompleteApp = false;
22242            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22243        } else {
22244            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22245            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22246                    || !volume.isMountedWritable()) {
22247                freezer.close();
22248                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22249                        "Move location not mounted private volume");
22250            }
22251
22252            Preconditions.checkState(!currentAsec);
22253
22254            installFlags = INSTALL_INTERNAL;
22255            moveCompleteApp = true;
22256            measurePath = Environment.getDataAppDirectory(volumeUuid);
22257        }
22258
22259        final PackageStats stats = new PackageStats(null, -1);
22260        synchronized (mInstaller) {
22261            for (int userId : installedUserIds) {
22262                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22263                    freezer.close();
22264                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22265                            "Failed to measure package size");
22266                }
22267            }
22268        }
22269
22270        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22271                + stats.dataSize);
22272
22273        final long startFreeBytes = measurePath.getFreeSpace();
22274        final long sizeBytes;
22275        if (moveCompleteApp) {
22276            sizeBytes = stats.codeSize + stats.dataSize;
22277        } else {
22278            sizeBytes = stats.codeSize;
22279        }
22280
22281        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22282            freezer.close();
22283            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22284                    "Not enough free space to move");
22285        }
22286
22287        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22288
22289        final CountDownLatch installedLatch = new CountDownLatch(1);
22290        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22291            @Override
22292            public void onUserActionRequired(Intent intent) throws RemoteException {
22293                throw new IllegalStateException();
22294            }
22295
22296            @Override
22297            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22298                    Bundle extras) throws RemoteException {
22299                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22300                        + PackageManager.installStatusToString(returnCode, msg));
22301
22302                installedLatch.countDown();
22303                freezer.close();
22304
22305                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22306                switch (status) {
22307                    case PackageInstaller.STATUS_SUCCESS:
22308                        mMoveCallbacks.notifyStatusChanged(moveId,
22309                                PackageManager.MOVE_SUCCEEDED);
22310                        break;
22311                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22312                        mMoveCallbacks.notifyStatusChanged(moveId,
22313                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22314                        break;
22315                    default:
22316                        mMoveCallbacks.notifyStatusChanged(moveId,
22317                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22318                        break;
22319                }
22320            }
22321        };
22322
22323        final MoveInfo move;
22324        if (moveCompleteApp) {
22325            // Kick off a thread to report progress estimates
22326            new Thread() {
22327                @Override
22328                public void run() {
22329                    while (true) {
22330                        try {
22331                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22332                                break;
22333                            }
22334                        } catch (InterruptedException ignored) {
22335                        }
22336
22337                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22338                        final int progress = 10 + (int) MathUtils.constrain(
22339                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22340                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22341                    }
22342                }
22343            }.start();
22344
22345            final String dataAppName = codeFile.getName();
22346            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22347                    dataAppName, appId, seinfo, targetSdkVersion);
22348        } else {
22349            move = null;
22350        }
22351
22352        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22353
22354        final Message msg = mHandler.obtainMessage(INIT_COPY);
22355        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22356        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22357                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22358                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22359                PackageManager.INSTALL_REASON_UNKNOWN);
22360        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22361        msg.obj = params;
22362
22363        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22364                System.identityHashCode(msg.obj));
22365        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22366                System.identityHashCode(msg.obj));
22367
22368        mHandler.sendMessage(msg);
22369    }
22370
22371    @Override
22372    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22373        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22374
22375        final int realMoveId = mNextMoveId.getAndIncrement();
22376        final Bundle extras = new Bundle();
22377        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22378        mMoveCallbacks.notifyCreated(realMoveId, extras);
22379
22380        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22381            @Override
22382            public void onCreated(int moveId, Bundle extras) {
22383                // Ignored
22384            }
22385
22386            @Override
22387            public void onStatusChanged(int moveId, int status, long estMillis) {
22388                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22389            }
22390        };
22391
22392        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22393        storage.setPrimaryStorageUuid(volumeUuid, callback);
22394        return realMoveId;
22395    }
22396
22397    @Override
22398    public int getMoveStatus(int moveId) {
22399        mContext.enforceCallingOrSelfPermission(
22400                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22401        return mMoveCallbacks.mLastStatus.get(moveId);
22402    }
22403
22404    @Override
22405    public void registerMoveCallback(IPackageMoveObserver callback) {
22406        mContext.enforceCallingOrSelfPermission(
22407                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22408        mMoveCallbacks.register(callback);
22409    }
22410
22411    @Override
22412    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22413        mContext.enforceCallingOrSelfPermission(
22414                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22415        mMoveCallbacks.unregister(callback);
22416    }
22417
22418    @Override
22419    public boolean setInstallLocation(int loc) {
22420        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22421                null);
22422        if (getInstallLocation() == loc) {
22423            return true;
22424        }
22425        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22426                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22427            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22428                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22429            return true;
22430        }
22431        return false;
22432   }
22433
22434    @Override
22435    public int getInstallLocation() {
22436        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22437                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22438                PackageHelper.APP_INSTALL_AUTO);
22439    }
22440
22441    /** Called by UserManagerService */
22442    void cleanUpUser(UserManagerService userManager, int userHandle) {
22443        synchronized (mPackages) {
22444            mDirtyUsers.remove(userHandle);
22445            mUserNeedsBadging.delete(userHandle);
22446            mSettings.removeUserLPw(userHandle);
22447            mPendingBroadcasts.remove(userHandle);
22448            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22449            removeUnusedPackagesLPw(userManager, userHandle);
22450        }
22451    }
22452
22453    /**
22454     * We're removing userHandle and would like to remove any downloaded packages
22455     * that are no longer in use by any other user.
22456     * @param userHandle the user being removed
22457     */
22458    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22459        final boolean DEBUG_CLEAN_APKS = false;
22460        int [] users = userManager.getUserIds();
22461        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22462        while (psit.hasNext()) {
22463            PackageSetting ps = psit.next();
22464            if (ps.pkg == null) {
22465                continue;
22466            }
22467            final String packageName = ps.pkg.packageName;
22468            // Skip over if system app
22469            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22470                continue;
22471            }
22472            if (DEBUG_CLEAN_APKS) {
22473                Slog.i(TAG, "Checking package " + packageName);
22474            }
22475            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22476            if (keep) {
22477                if (DEBUG_CLEAN_APKS) {
22478                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22479                }
22480            } else {
22481                for (int i = 0; i < users.length; i++) {
22482                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22483                        keep = true;
22484                        if (DEBUG_CLEAN_APKS) {
22485                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22486                                    + users[i]);
22487                        }
22488                        break;
22489                    }
22490                }
22491            }
22492            if (!keep) {
22493                if (DEBUG_CLEAN_APKS) {
22494                    Slog.i(TAG, "  Removing package " + packageName);
22495                }
22496                mHandler.post(new Runnable() {
22497                    public void run() {
22498                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22499                                userHandle, 0);
22500                    } //end run
22501                });
22502            }
22503        }
22504    }
22505
22506    /** Called by UserManagerService */
22507    void createNewUser(int userId, String[] disallowedPackages) {
22508        synchronized (mInstallLock) {
22509            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22510        }
22511        synchronized (mPackages) {
22512            scheduleWritePackageRestrictionsLocked(userId);
22513            scheduleWritePackageListLocked(userId);
22514            applyFactoryDefaultBrowserLPw(userId);
22515            primeDomainVerificationsLPw(userId);
22516        }
22517    }
22518
22519    void onNewUserCreated(final int userId) {
22520        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22521        // If permission review for legacy apps is required, we represent
22522        // dagerous permissions for such apps as always granted runtime
22523        // permissions to keep per user flag state whether review is needed.
22524        // Hence, if a new user is added we have to propagate dangerous
22525        // permission grants for these legacy apps.
22526        if (mPermissionReviewRequired) {
22527            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22528                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22529        }
22530    }
22531
22532    @Override
22533    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22534        mContext.enforceCallingOrSelfPermission(
22535                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22536                "Only package verification agents can read the verifier device identity");
22537
22538        synchronized (mPackages) {
22539            return mSettings.getVerifierDeviceIdentityLPw();
22540        }
22541    }
22542
22543    @Override
22544    public void setPermissionEnforced(String permission, boolean enforced) {
22545        // TODO: Now that we no longer change GID for storage, this should to away.
22546        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22547                "setPermissionEnforced");
22548        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22549            synchronized (mPackages) {
22550                if (mSettings.mReadExternalStorageEnforced == null
22551                        || mSettings.mReadExternalStorageEnforced != enforced) {
22552                    mSettings.mReadExternalStorageEnforced = enforced;
22553                    mSettings.writeLPr();
22554                }
22555            }
22556            // kill any non-foreground processes so we restart them and
22557            // grant/revoke the GID.
22558            final IActivityManager am = ActivityManager.getService();
22559            if (am != null) {
22560                final long token = Binder.clearCallingIdentity();
22561                try {
22562                    am.killProcessesBelowForeground("setPermissionEnforcement");
22563                } catch (RemoteException e) {
22564                } finally {
22565                    Binder.restoreCallingIdentity(token);
22566                }
22567            }
22568        } else {
22569            throw new IllegalArgumentException("No selective enforcement for " + permission);
22570        }
22571    }
22572
22573    @Override
22574    @Deprecated
22575    public boolean isPermissionEnforced(String permission) {
22576        return true;
22577    }
22578
22579    @Override
22580    public boolean isStorageLow() {
22581        final long token = Binder.clearCallingIdentity();
22582        try {
22583            final DeviceStorageMonitorInternal
22584                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22585            if (dsm != null) {
22586                return dsm.isMemoryLow();
22587            } else {
22588                return false;
22589            }
22590        } finally {
22591            Binder.restoreCallingIdentity(token);
22592        }
22593    }
22594
22595    @Override
22596    public IPackageInstaller getPackageInstaller() {
22597        return mInstallerService;
22598    }
22599
22600    private boolean userNeedsBadging(int userId) {
22601        int index = mUserNeedsBadging.indexOfKey(userId);
22602        if (index < 0) {
22603            final UserInfo userInfo;
22604            final long token = Binder.clearCallingIdentity();
22605            try {
22606                userInfo = sUserManager.getUserInfo(userId);
22607            } finally {
22608                Binder.restoreCallingIdentity(token);
22609            }
22610            final boolean b;
22611            if (userInfo != null && userInfo.isManagedProfile()) {
22612                b = true;
22613            } else {
22614                b = false;
22615            }
22616            mUserNeedsBadging.put(userId, b);
22617            return b;
22618        }
22619        return mUserNeedsBadging.valueAt(index);
22620    }
22621
22622    @Override
22623    public KeySet getKeySetByAlias(String packageName, String alias) {
22624        if (packageName == null || alias == null) {
22625            return null;
22626        }
22627        synchronized(mPackages) {
22628            final PackageParser.Package pkg = mPackages.get(packageName);
22629            if (pkg == null) {
22630                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22631                throw new IllegalArgumentException("Unknown package: " + packageName);
22632            }
22633            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22634            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22635        }
22636    }
22637
22638    @Override
22639    public KeySet getSigningKeySet(String packageName) {
22640        if (packageName == null) {
22641            return null;
22642        }
22643        synchronized(mPackages) {
22644            final PackageParser.Package pkg = mPackages.get(packageName);
22645            if (pkg == null) {
22646                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22647                throw new IllegalArgumentException("Unknown package: " + packageName);
22648            }
22649            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22650                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22651                throw new SecurityException("May not access signing KeySet of other apps.");
22652            }
22653            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22654            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22655        }
22656    }
22657
22658    @Override
22659    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22660        if (packageName == null || ks == null) {
22661            return false;
22662        }
22663        synchronized(mPackages) {
22664            final PackageParser.Package pkg = mPackages.get(packageName);
22665            if (pkg == null) {
22666                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22667                throw new IllegalArgumentException("Unknown package: " + packageName);
22668            }
22669            IBinder ksh = ks.getToken();
22670            if (ksh instanceof KeySetHandle) {
22671                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22672                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22673            }
22674            return false;
22675        }
22676    }
22677
22678    @Override
22679    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22680        if (packageName == null || ks == null) {
22681            return false;
22682        }
22683        synchronized(mPackages) {
22684            final PackageParser.Package pkg = mPackages.get(packageName);
22685            if (pkg == null) {
22686                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22687                throw new IllegalArgumentException("Unknown package: " + packageName);
22688            }
22689            IBinder ksh = ks.getToken();
22690            if (ksh instanceof KeySetHandle) {
22691                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22692                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22693            }
22694            return false;
22695        }
22696    }
22697
22698    private void deletePackageIfUnusedLPr(final String packageName) {
22699        PackageSetting ps = mSettings.mPackages.get(packageName);
22700        if (ps == null) {
22701            return;
22702        }
22703        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22704            // TODO Implement atomic delete if package is unused
22705            // It is currently possible that the package will be deleted even if it is installed
22706            // after this method returns.
22707            mHandler.post(new Runnable() {
22708                public void run() {
22709                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22710                            0, PackageManager.DELETE_ALL_USERS);
22711                }
22712            });
22713        }
22714    }
22715
22716    /**
22717     * Check and throw if the given before/after packages would be considered a
22718     * downgrade.
22719     */
22720    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22721            throws PackageManagerException {
22722        if (after.versionCode < before.mVersionCode) {
22723            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22724                    "Update version code " + after.versionCode + " is older than current "
22725                    + before.mVersionCode);
22726        } else if (after.versionCode == before.mVersionCode) {
22727            if (after.baseRevisionCode < before.baseRevisionCode) {
22728                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22729                        "Update base revision code " + after.baseRevisionCode
22730                        + " is older than current " + before.baseRevisionCode);
22731            }
22732
22733            if (!ArrayUtils.isEmpty(after.splitNames)) {
22734                for (int i = 0; i < after.splitNames.length; i++) {
22735                    final String splitName = after.splitNames[i];
22736                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22737                    if (j != -1) {
22738                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22739                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22740                                    "Update split " + splitName + " revision code "
22741                                    + after.splitRevisionCodes[i] + " is older than current "
22742                                    + before.splitRevisionCodes[j]);
22743                        }
22744                    }
22745                }
22746            }
22747        }
22748    }
22749
22750    private static class MoveCallbacks extends Handler {
22751        private static final int MSG_CREATED = 1;
22752        private static final int MSG_STATUS_CHANGED = 2;
22753
22754        private final RemoteCallbackList<IPackageMoveObserver>
22755                mCallbacks = new RemoteCallbackList<>();
22756
22757        private final SparseIntArray mLastStatus = new SparseIntArray();
22758
22759        public MoveCallbacks(Looper looper) {
22760            super(looper);
22761        }
22762
22763        public void register(IPackageMoveObserver callback) {
22764            mCallbacks.register(callback);
22765        }
22766
22767        public void unregister(IPackageMoveObserver callback) {
22768            mCallbacks.unregister(callback);
22769        }
22770
22771        @Override
22772        public void handleMessage(Message msg) {
22773            final SomeArgs args = (SomeArgs) msg.obj;
22774            final int n = mCallbacks.beginBroadcast();
22775            for (int i = 0; i < n; i++) {
22776                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22777                try {
22778                    invokeCallback(callback, msg.what, args);
22779                } catch (RemoteException ignored) {
22780                }
22781            }
22782            mCallbacks.finishBroadcast();
22783            args.recycle();
22784        }
22785
22786        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22787                throws RemoteException {
22788            switch (what) {
22789                case MSG_CREATED: {
22790                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22791                    break;
22792                }
22793                case MSG_STATUS_CHANGED: {
22794                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22795                    break;
22796                }
22797            }
22798        }
22799
22800        private void notifyCreated(int moveId, Bundle extras) {
22801            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22802
22803            final SomeArgs args = SomeArgs.obtain();
22804            args.argi1 = moveId;
22805            args.arg2 = extras;
22806            obtainMessage(MSG_CREATED, args).sendToTarget();
22807        }
22808
22809        private void notifyStatusChanged(int moveId, int status) {
22810            notifyStatusChanged(moveId, status, -1);
22811        }
22812
22813        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22814            Slog.v(TAG, "Move " + moveId + " status " + status);
22815
22816            final SomeArgs args = SomeArgs.obtain();
22817            args.argi1 = moveId;
22818            args.argi2 = status;
22819            args.arg3 = estMillis;
22820            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22821
22822            synchronized (mLastStatus) {
22823                mLastStatus.put(moveId, status);
22824            }
22825        }
22826    }
22827
22828    private final static class OnPermissionChangeListeners extends Handler {
22829        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22830
22831        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22832                new RemoteCallbackList<>();
22833
22834        public OnPermissionChangeListeners(Looper looper) {
22835            super(looper);
22836        }
22837
22838        @Override
22839        public void handleMessage(Message msg) {
22840            switch (msg.what) {
22841                case MSG_ON_PERMISSIONS_CHANGED: {
22842                    final int uid = msg.arg1;
22843                    handleOnPermissionsChanged(uid);
22844                } break;
22845            }
22846        }
22847
22848        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22849            mPermissionListeners.register(listener);
22850
22851        }
22852
22853        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22854            mPermissionListeners.unregister(listener);
22855        }
22856
22857        public void onPermissionsChanged(int uid) {
22858            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22859                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22860            }
22861        }
22862
22863        private void handleOnPermissionsChanged(int uid) {
22864            final int count = mPermissionListeners.beginBroadcast();
22865            try {
22866                for (int i = 0; i < count; i++) {
22867                    IOnPermissionsChangeListener callback = mPermissionListeners
22868                            .getBroadcastItem(i);
22869                    try {
22870                        callback.onPermissionsChanged(uid);
22871                    } catch (RemoteException e) {
22872                        Log.e(TAG, "Permission listener is dead", e);
22873                    }
22874                }
22875            } finally {
22876                mPermissionListeners.finishBroadcast();
22877            }
22878        }
22879    }
22880
22881    private class PackageManagerInternalImpl extends PackageManagerInternal {
22882        @Override
22883        public void setLocationPackagesProvider(PackagesProvider provider) {
22884            synchronized (mPackages) {
22885                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22886            }
22887        }
22888
22889        @Override
22890        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22891            synchronized (mPackages) {
22892                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22893            }
22894        }
22895
22896        @Override
22897        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22898            synchronized (mPackages) {
22899                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22900            }
22901        }
22902
22903        @Override
22904        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22905            synchronized (mPackages) {
22906                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22907            }
22908        }
22909
22910        @Override
22911        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22912            synchronized (mPackages) {
22913                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22914            }
22915        }
22916
22917        @Override
22918        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22919            synchronized (mPackages) {
22920                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22921            }
22922        }
22923
22924        @Override
22925        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22926            synchronized (mPackages) {
22927                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22928                        packageName, userId);
22929            }
22930        }
22931
22932        @Override
22933        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22934            synchronized (mPackages) {
22935                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22936                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22937                        packageName, userId);
22938            }
22939        }
22940
22941        @Override
22942        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22943            synchronized (mPackages) {
22944                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22945                        packageName, userId);
22946            }
22947        }
22948
22949        @Override
22950        public void setKeepUninstalledPackages(final List<String> packageList) {
22951            Preconditions.checkNotNull(packageList);
22952            List<String> removedFromList = null;
22953            synchronized (mPackages) {
22954                if (mKeepUninstalledPackages != null) {
22955                    final int packagesCount = mKeepUninstalledPackages.size();
22956                    for (int i = 0; i < packagesCount; i++) {
22957                        String oldPackage = mKeepUninstalledPackages.get(i);
22958                        if (packageList != null && packageList.contains(oldPackage)) {
22959                            continue;
22960                        }
22961                        if (removedFromList == null) {
22962                            removedFromList = new ArrayList<>();
22963                        }
22964                        removedFromList.add(oldPackage);
22965                    }
22966                }
22967                mKeepUninstalledPackages = new ArrayList<>(packageList);
22968                if (removedFromList != null) {
22969                    final int removedCount = removedFromList.size();
22970                    for (int i = 0; i < removedCount; i++) {
22971                        deletePackageIfUnusedLPr(removedFromList.get(i));
22972                    }
22973                }
22974            }
22975        }
22976
22977        @Override
22978        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22979            synchronized (mPackages) {
22980                // If we do not support permission review, done.
22981                if (!mPermissionReviewRequired) {
22982                    return false;
22983                }
22984
22985                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22986                if (packageSetting == null) {
22987                    return false;
22988                }
22989
22990                // Permission review applies only to apps not supporting the new permission model.
22991                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22992                    return false;
22993                }
22994
22995                // Legacy apps have the permission and get user consent on launch.
22996                PermissionsState permissionsState = packageSetting.getPermissionsState();
22997                return permissionsState.isPermissionReviewRequired(userId);
22998            }
22999        }
23000
23001        @Override
23002        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23003            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23004        }
23005
23006        @Override
23007        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23008                int userId) {
23009            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23010        }
23011
23012        @Override
23013        public void setDeviceAndProfileOwnerPackages(
23014                int deviceOwnerUserId, String deviceOwnerPackage,
23015                SparseArray<String> profileOwnerPackages) {
23016            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23017                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23018        }
23019
23020        @Override
23021        public boolean isPackageDataProtected(int userId, String packageName) {
23022            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23023        }
23024
23025        @Override
23026        public boolean isPackageEphemeral(int userId, String packageName) {
23027            synchronized (mPackages) {
23028                final PackageSetting ps = mSettings.mPackages.get(packageName);
23029                return ps != null ? ps.getInstantApp(userId) : false;
23030            }
23031        }
23032
23033        @Override
23034        public boolean wasPackageEverLaunched(String packageName, int userId) {
23035            synchronized (mPackages) {
23036                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23037            }
23038        }
23039
23040        @Override
23041        public void grantRuntimePermission(String packageName, String name, int userId,
23042                boolean overridePolicy) {
23043            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23044                    overridePolicy);
23045        }
23046
23047        @Override
23048        public void revokeRuntimePermission(String packageName, String name, int userId,
23049                boolean overridePolicy) {
23050            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23051                    overridePolicy);
23052        }
23053
23054        @Override
23055        public String getNameForUid(int uid) {
23056            return PackageManagerService.this.getNameForUid(uid);
23057        }
23058
23059        @Override
23060        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23061                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23062            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23063                    responseObj, origIntent, resolvedType, callingPackage, userId);
23064        }
23065
23066        @Override
23067        public void grantEphemeralAccess(int userId, Intent intent,
23068                int targetAppId, int ephemeralAppId) {
23069            synchronized (mPackages) {
23070                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23071                        targetAppId, ephemeralAppId);
23072            }
23073        }
23074
23075        @Override
23076        public void pruneInstantApps() {
23077            synchronized (mPackages) {
23078                mInstantAppRegistry.pruneInstantAppsLPw();
23079            }
23080        }
23081
23082        @Override
23083        public String getSetupWizardPackageName() {
23084            return mSetupWizardPackage;
23085        }
23086
23087        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23088            if (policy != null) {
23089                mExternalSourcesPolicy = policy;
23090            }
23091        }
23092
23093        @Override
23094        public boolean isPackagePersistent(String packageName) {
23095            synchronized (mPackages) {
23096                PackageParser.Package pkg = mPackages.get(packageName);
23097                return pkg != null
23098                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23099                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23100                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23101                        : false;
23102            }
23103        }
23104
23105        @Override
23106        public List<PackageInfo> getOverlayPackages(int userId) {
23107            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23108            synchronized (mPackages) {
23109                for (PackageParser.Package p : mPackages.values()) {
23110                    if (p.mOverlayTarget != null) {
23111                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23112                        if (pkg != null) {
23113                            overlayPackages.add(pkg);
23114                        }
23115                    }
23116                }
23117            }
23118            return overlayPackages;
23119        }
23120
23121        @Override
23122        public List<String> getTargetPackageNames(int userId) {
23123            List<String> targetPackages = new ArrayList<>();
23124            synchronized (mPackages) {
23125                for (PackageParser.Package p : mPackages.values()) {
23126                    if (p.mOverlayTarget == null) {
23127                        targetPackages.add(p.packageName);
23128                    }
23129                }
23130            }
23131            return targetPackages;
23132        }
23133
23134        @Override
23135        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23136                @Nullable List<String> overlayPackageNames) {
23137            synchronized (mPackages) {
23138                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23139                    Slog.e(TAG, "failed to find package " + targetPackageName);
23140                    return false;
23141                }
23142
23143                ArrayList<String> paths = null;
23144                if (overlayPackageNames != null) {
23145                    final int N = overlayPackageNames.size();
23146                    paths = new ArrayList<>(N);
23147                    for (int i = 0; i < N; i++) {
23148                        final String packageName = overlayPackageNames.get(i);
23149                        final PackageParser.Package pkg = mPackages.get(packageName);
23150                        if (pkg == null) {
23151                            Slog.e(TAG, "failed to find package " + packageName);
23152                            return false;
23153                        }
23154                        paths.add(pkg.baseCodePath);
23155                    }
23156                }
23157
23158                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23159                    mEnabledOverlayPaths.get(userId);
23160                if (userSpecificOverlays == null) {
23161                    userSpecificOverlays = new ArrayMap<>();
23162                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23163                }
23164
23165                if (paths != null && paths.size() > 0) {
23166                    userSpecificOverlays.put(targetPackageName, paths);
23167                } else {
23168                    userSpecificOverlays.remove(targetPackageName);
23169                }
23170                return true;
23171            }
23172        }
23173
23174        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23175                int flags, int userId) {
23176            return resolveIntentInternal(
23177                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23178        }
23179    }
23180
23181    @Override
23182    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23183        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23184        synchronized (mPackages) {
23185            final long identity = Binder.clearCallingIdentity();
23186            try {
23187                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23188                        packageNames, userId);
23189            } finally {
23190                Binder.restoreCallingIdentity(identity);
23191            }
23192        }
23193    }
23194
23195    @Override
23196    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23197        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23198        synchronized (mPackages) {
23199            final long identity = Binder.clearCallingIdentity();
23200            try {
23201                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23202                        packageNames, userId);
23203            } finally {
23204                Binder.restoreCallingIdentity(identity);
23205            }
23206        }
23207    }
23208
23209    private static void enforceSystemOrPhoneCaller(String tag) {
23210        int callingUid = Binder.getCallingUid();
23211        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23212            throw new SecurityException(
23213                    "Cannot call " + tag + " from UID " + callingUid);
23214        }
23215    }
23216
23217    boolean isHistoricalPackageUsageAvailable() {
23218        return mPackageUsage.isHistoricalPackageUsageAvailable();
23219    }
23220
23221    /**
23222     * Return a <b>copy</b> of the collection of packages known to the package manager.
23223     * @return A copy of the values of mPackages.
23224     */
23225    Collection<PackageParser.Package> getPackages() {
23226        synchronized (mPackages) {
23227            return new ArrayList<>(mPackages.values());
23228        }
23229    }
23230
23231    /**
23232     * Logs process start information (including base APK hash) to the security log.
23233     * @hide
23234     */
23235    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23236            String apkFile, int pid) {
23237        if (!SecurityLog.isLoggingEnabled()) {
23238            return;
23239        }
23240        Bundle data = new Bundle();
23241        data.putLong("startTimestamp", System.currentTimeMillis());
23242        data.putString("processName", processName);
23243        data.putInt("uid", uid);
23244        data.putString("seinfo", seinfo);
23245        data.putString("apkFile", apkFile);
23246        data.putInt("pid", pid);
23247        Message msg = mProcessLoggingHandler.obtainMessage(
23248                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23249        msg.setData(data);
23250        mProcessLoggingHandler.sendMessage(msg);
23251    }
23252
23253    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23254        return mCompilerStats.getPackageStats(pkgName);
23255    }
23256
23257    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23258        return getOrCreateCompilerPackageStats(pkg.packageName);
23259    }
23260
23261    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23262        return mCompilerStats.getOrCreatePackageStats(pkgName);
23263    }
23264
23265    public void deleteCompilerPackageStats(String pkgName) {
23266        mCompilerStats.deletePackageStats(pkgName);
23267    }
23268
23269    @Override
23270    public int getInstallReason(String packageName, int userId) {
23271        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23272                true /* requireFullPermission */, false /* checkShell */,
23273                "get install reason");
23274        synchronized (mPackages) {
23275            final PackageSetting ps = mSettings.mPackages.get(packageName);
23276            if (ps != null) {
23277                return ps.getInstallReason(userId);
23278            }
23279        }
23280        return PackageManager.INSTALL_REASON_UNKNOWN;
23281    }
23282
23283    @Override
23284    public boolean canRequestPackageInstalls(String packageName, int userId) {
23285        int callingUid = Binder.getCallingUid();
23286        int uid = getPackageUid(packageName, 0, userId);
23287        if (callingUid != uid && callingUid != Process.ROOT_UID
23288                && callingUid != Process.SYSTEM_UID) {
23289            throw new SecurityException(
23290                    "Caller uid " + callingUid + " does not own package " + packageName);
23291        }
23292        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23293        if (info == null) {
23294            return false;
23295        }
23296        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23297            throw new UnsupportedOperationException(
23298                    "Operation only supported on apps targeting Android O or higher");
23299        }
23300        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23301        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23302        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23303            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23304        }
23305        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23306            return false;
23307        }
23308        if (mExternalSourcesPolicy != null) {
23309            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23310            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23311                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23312            }
23313        }
23314        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23315    }
23316}
23317